简体   繁体   中英

Why does $.change() fire on a submit button?

I have a $.change() event, but when a submit button is pressed, the change event fires again. It is only supposed to fire once when a text is inputted into a input text box.

$('input:submit', top.document).bind('click', function (e) {
    alert("submitting")
});

$('input').change(function (e) {
    alert("fire");
});

Edit: For whatever reason, a change event is invoked when the input button is clicked. (thanks Anthony)

The way to fix this is simply don't select the submit button.

You can try

$('input:text')

To select only text fields.

Or you can do

$('input:not(:submit)')

To select all input elements except the submit button(s).

Read about selectors here

Edit: Using <button> instead won't work. It still counts as an input field, but it's value is separate from the text displayed on the button.

$('input').change(function(e){ alert("fire") }); applies that event to ALL input elements, including <input type="submit".../> . If you really want EVERY SINGLE text input element to have a change event, you want ``$('input[type=text]').change(function(e){ alert("fire") });` Otherwise, it might be best to use an id or class.

@Mark,

You are spot on and I'd edit you if I could to help out. Maybe someday soon...

@ajowi,

Submit buttons are inputs. At least most of them are:

  <input type="submit" />

So Mark,it's not that they are doing anything with the button text, it's that the input, which is a button, is being changed by act of clicking on it.

So his solutions were great. Go with

  $("input:text").change

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM