jQuery how to properly use onChange

只愿长相守 提交于 2019-12-13 02:36:15

问题


I am using Drupal 7 (quite new to both Drupal and Javascript / jQuery) and I got a class called "field-name-field-activity", now what I want is to put an onchange of every input in that class.

jQuery('.field-name-field-activity :input').onchange = function() {
    //enter code here
};

I am not sure if I'm using my onchange right here, I also saw some people using onChange instead of onchange, not sure what the difference is, but can anybody tell me how to use onchange the right way in my example?


回答1:


This is a simple error of syntax try this jQuery('.field-name-field-activity :input').change(function() { //enter code here });

here is a link to the api reference http://api.jquery.com/change/




回答2:


With jquery just change will work:

$('.field-name-field-activity').change(function() {
  // your code here
});

Edit:

As the event is to be bind with text type, a better way is to use input event like:

$('.field-name-field-activity').on('input', function() {
    // your code here
});

The onchange event may not work correctly on some browsers in case of text fields.




回答3:


Try like this:

jQuery('.field-name-field-activity input').change(function() {
    //enter code here
});

SIMPLE DEMO HERE




回答4:


Concerning performance I would suggest not to use the ":input"-Selector.

Because :input is a jQuery extension and not part of the CSS specification, queries using >:input cannot take advantage of the performance boost provided by the native DOM >querySelectorAll() method.

Source: http://api.jquery.com/input-selector/

If the classname relates to input-Elements only anyway, just use the class-selector like Ankit Jaiswal suggested, because a single-class-selector performs best.

Source: Jquery element+class selector performance




回答5:


Try this -

jQuery('.field-name-field-activity').on('change',function() {
    //enter code here
});

http://api.jquery.com/change/



来源:https://stackoverflow.com/questions/16354847/jquery-how-to-properly-use-onchange

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!