How to bind an event for all form inputs?

I have a form with inputs (with identifiers). And I need to bind one event to click any input in this form.

Now I use this construct:

$("#siteAdress").click(function(){ $("#reg-login").click(); }); $("#phoneNumber").click(function(){ $("#reg-login").click(); }); $("#reg-email").click(function(){ $("#reg-login").click(); }); $("#reg-login").click(function(){ // DO SOMETHING }); 

How to optimize it?

+6
source share
5 answers

The easiest way is probably to add the class to all the elements you need to bind and use it:

 $(".event-user").click(function() { /* do something */ }) 

If this is not an option, you can use id for your form and request all its children:

 $("#my-form input[type=text]").click(function() { /* do something */ }) 

And if none of them is possible, you can always use a list of selectors separated by commas:

 $("#siteAddress, #phoneNumber, #reg-email, #reg-login") .click(function() { /* do something */}) 
+14
source

Depending on the types of inputs you have, you can make it wide or fine grained. For example, if all elements are of type input , just do it broadly:

 $('input').click(function(){ ... }); 

Otherwise, if you want to do this specifically for text input types, for example, you can do this:

 $('input[type="text"]').click(function(){ ... }); 

All in the selectors! Hope this helps ...

+2
source

Use this

 $("form input:text").click(function(){ $("#reg-login").click(); }); 
+1
source

You must use the general> sign. This means that you can get the form identifier, and then with a single line add a click function for all children:

 $('#formId > input').each(function () { $(this).click(function () { //SOME CODE - btw you can ge the value with this.value; }) }); 

hope this helps.

+1
source
  $('form input').click(function (e) { SearchForm();//Call function you want return false; }); $('form input').keypress(function (e) { SearchForm();//Call function you want return false; }); 
+1
source

Source: https://habr.com/ru/post/906826/


All Articles