I’m writing a lot of JQuery code recently that seems to repeat itself and I’m wondering if there are any shortcuts for the following:
1) Selecting multiple elements by name, i.e.
$("input[type=text][name=one][name=two][name=three]").live(); <-- is that correct syntax
2) Multiple live bindings, i.e.
$("input[type=text]").live('blur and click',function(){});
Thanks
Edit:
I’ve also got this use case, where I want to flip display on multiple elements, I found this on this forum, but I haven’t tested it yet. Here’s my impl and I’d welcome feedback on the strategy
$("#btn_account_edit").live('click',function(){
flip_display_on_off(
$("#btn_account_edit_cancel, #btn_account_save, #account_edit_form"),
$("#btn_account_edit, #account_edit_static"),
false,true);
});
$("#btn_account_edit_cancel").live('click',function(){
flip_display_on_off(
$("#btn_account_edit_cancel, #btn_account_save, #account_edit_form"),
$("#btn_account_edit, #account_edit_static"),
true,false);
});
function flip_display_on_off($element_set1,$element_set2,flip1,flip2) {
var display1 = 'block' ? if flip1 : 'none';
var display2 = 'none' ? if flip2 : 'block';
for (i =0; i < element_set1.length; i++) {
$element_set1[i].css('display',display1);
}
for (i =0; i < element_set2.length; i++) {
$element_set2[i].css('display',display2);
}
}
Second Edit:
This is the final version of the code, tested and works perfectly! Thanks to @thecodeparadox
$("#btn_account_edit").live('click',function(){
flip_display_on_off(
$("#btn_account_edit_cancel, #btn_account_save, #account_edit_form"),
$("#btn_account_edit, #account_edit_static"),
true);
});
$("#btn_account_edit_cancel").live('click',function(){
flip_display_on_off(
$("#btn_account_edit_cancel, #btn_account_save, #account_edit_form"),
$("#btn_account_edit, #account_edit_static"),
false);
});
function flip_display_on_off($element_set1, $element_set2, flip1) {
$element_set1.css('display', flip1 ? 'block' : 'none');
$element_set2.css('display', flip1 ? 'none' : 'block');
}
Answer to your question : 01
To select different selector they need to be separated by comma, read more about jQuery Selectore
is correct.
Answer to your question : 02
for multiple live event bind event name should be separated by comma also. Read more about jQuery events.
In case of live event binding, we shouldn’t use live because its deprecated. Instead of that we need to use .on().
There is another option for live event delegation called .delegate(). It implement like following:
According to comment
Want to send array of input fields as parameter of a function
According to Edit
NOTE I think you don’t need any loopy.
I hope you get all answers. Happy coding 🙁