Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind an event for all inputs of form?

I have a form with inputs (with id's). And i need to bind one event to click on any input in this form.

Now, I use this construction:

    $("#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?

like image 704
skywind Avatar asked Jan 25 '12 07:01

skywind


People also ask

What method can you use to bind an event to an element?

jQuery bind() Method The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs.

How do you attach a event to element which should be executed only once?

Syntax: $(". event-handler-btn"). one("click", function (e) { // Code to be executed once });

How do you use event inputs?

How it works: First, select the <input> element with the id message and the <p> element with the id result . Then, attach an event handler to the input event of the <input> element. Inside the input event handler, update the textContent property of the <p> element.

Which input event will you use on an input tag to get notified every time a user focuses on something else?

Which input event will you use on an input tag to get notified every time a user focuses on something else? The HTML DOM event onfocus is triggered whenever an HTML element it is assigned to receives focus from the user. This event is usually used with <input>, <select> and <a> tags.


2 Answers

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

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

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

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

And if neither is possible, you can always use a comma-separated list of selectors:

$("#siteAddress, #phoneNumber, #reg-email, #reg-login")
    .click(function() { /* do something */})
like image 181
zneak Avatar answered Oct 24 '22 14:10

zneak


Depending on the types of inputs you have, you could do it broadly or fine grain it. For example, if they're all input type elements, just do it broadly:

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

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

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

It's all in the selectors! Hope this helps...

like image 31
Chris Kempen Avatar answered Oct 24 '22 13:10

Chris Kempen