Reputation: 47
I have to do same things when following event occur on a form
1) An input text box value is changed by keyboard or mouse(pasting) 2) A checked box is checked/unchecked 3) A select option is changed
currently I am doing
$(':text').on('input', function() {
//Same code
}
$(':checkbox').on('change', function() {
//Same code
}
$('select').on('change', function() {
//Same code
}
but i want to write single function for all there events like
$(':text', ':checkbox', 'select' ).on('???', function() {
//Same code
}
Please help me on it
Thank you in advance
Upvotes: 0
Views: 1028
Reputation: 4038
Bind your single/multiple event/s with multiple elements using class attribute. Assign same class to all elements and find the event type that has been fired. According to the fired event code your implementation.
Try this way :
HTML :
<input class="elements" type="text" />
<input class="elements" type="checkbox" />
<select class="elements">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<input class="elements" type="button" value="Click here" />
jQuery :
$(".elements").on("change click", function(e){
var nodes = e.target;
if(nodes.nodeName == "INPUT"){
if(nodes.type == "text" && e.type == "change"){
// code goes here
alert("Input changed");
}else if(nodes.type == "checkbox" && e.type == "change"){
// code goes here
alert("Checkbox state changed");
}else if(nodes.type == "button" && e.type == "click"){
alert("Button is clicked");
}
}
else if(nodes.nodeName == "SELECT" && e.type == "change"){
// code goes here
alert("Select option changed");
}
});
Resources :
Upvotes: 0
Reputation: 4896
You may use something like this. But this will trigger both change and input events for the :text.
$(':checkbox, :text, select').on('change input',function(e) {
//code
});
Upvotes: 3
Reputation: 5382
I would suggest using @Shyju's answer, as it is much more scalable and friendly, but based off of your question, here is an implementation.
Listen to the document for click events and delegate it to the selectors you pass in:
$(document).on('click', ':text, :checkbox, select', function() {
doFunction();
});
Here's a JSFiddle working example
Upvotes: 0
Reputation: 218752
Add a CSS class to these input boxes and use that class as your jQuery selector for binding your event.
HTML
<input type="text" class="changable" />
<input type="checkbox" class="changable" />
and jQuery
$(function(){
$(document).on("change",".changable",function(e){
var _this=$(this);
// do something now.
});
});
Upvotes: 1