Skip to Content Skip to Menu

jQuery : simple event listening technique

Event listening in jQuery has served me well when doing small custom events. It helps to use this technique so that the majority of browsers support the code being executed.

A typical example for using event listening is when I a click or change event has occured on one form input, to then display something different in another.

Example:

 

HTML

<form method="post">
<div class="form-container">
<select id="select-box" name="select-box">
<option value="First Selected Option">First Selected Option</option>
<option value="Second Selected Option">Second Select Option</option>
<option value="Third Selected Option">Third Select Option</option>
</select>&nbsp;
<input id="select-value" name="select-value" readonly="readonly" type="text" />
</div>
</form>

Javascript

$(document).ready(function(){
//within the container holding the form, listing for the click or change event
$(".form-container").change(function(event){changeValue(event);});
$(".form-container").click(function(event){changeValue(event);});

//function to handle the event
function changeValue(event)
{
//if the target of the event is a select or input tag execute the code
if($(event.target).is("select, input"))
{
//get the current select box value
var new_string = $(event.target).val();
//show the value in the input
$("#select-value").val(new_string);
}
};
});

Let me know if it does not work in your browser.