JQuery custom event dispatching and listening using trigger and bind


Today i create a simple application in which there are 3 text field and a submit button, submit button should be disabled until there is no text in input fields so i use JQuery’s trigger method to trigger custom event with some additional parameters( for R&D only)   and JQuery’s bind function to bind a function, which will be called when an  event triggered, We can bind more then one events to a single function

<!DOCTYPE html>
<html>
<head>
	<title>as3atoz</title>
	<script type="text/javascript" src="../day2/jquery-1.6.1.min.js"></script>
	<script>
	$("document").ready(function(){ 

		function enableSubmit()
		{
			$("#submitBtn").attr("disabled",false);
		} 

		function disableSubmit()
		{
			$("#submitBtn").attr("disabled",true); 	
		}

		$(document).bind('A_CHANGE B_CHANGE C_CHANGE', function(e,param1,param2) {
			$('#debug').html("DEBUG ::"+e.type +", "+param1+ ", "+param2);
			if($('#a_txt').val() != "" && $('#b_txt').val()  != "" && $('#c_txt').val() != ""){
				enableSubmit();
			} else {
				disableSubmit();
			}			
		});	

		$('#a_txt').keyup(function() {
			$(document).trigger('A_CHANGE',[$(this).val(),"param2"]);
		});

		$('#b_txt').keyup(function() {
			$(document).trigger('B_CHANGE', [$(this).val(),["a","b","c"]]);
		});

		$('#c_txt').keyup(function() {
			$(document).trigger('C_CHANGE', [$(this).val(),{a:"one",b:"two"}]);
		});
		disableSubmit();
	});

	</script>
</head>
<body>
	<form>		
	  <input id="a_txt"/>
	  <input id="b_txt"/>
	  <input id="c_txt"/>
	  <input id="submitBtn"  type="submit"/>
	  <div id="debug"></div>
	</form>
</body>
</html>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s