最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Javascript OnChange for Checkbox - Stack Overflow

programmeradmin1浏览0评论

I have 5 checkboxes and 1 textarea in my form and would like to just hook OnChange() for all of these. However, for whatever reason nothing I have found on Stack Overflow seems to be getting called.

As this is the most basic example I found, what is wrong with this?

<script src=".10.2/jquery.min.js"/>
<script type="text/javascript">
$(document).ready(function()
{
    $("input").on("input", function()
    {
        alert("CHANGED");
    });
}
</script>

I have 5 checkboxes and 1 textarea in my form and would like to just hook OnChange() for all of these. However, for whatever reason nothing I have found on Stack Overflow seems to be getting called.

As this is the most basic example I found, what is wrong with this?

<script src="http://ajax.googleapis./ajax/libs/jquery/1.10.2/jquery.min.js"/>
<script type="text/javascript">
$(document).ready(function()
{
    $("input").on("input", function()
    {
        alert("CHANGED");
    });
}
</script>
Share Improve this question asked Jan 3, 2014 at 11:25 user470760user470760 1
  • First of all, it does not work on a textarea, input != textarea. Try $("input, textarea").on("change", function() { alert("changed"); }) – putvande Commented Jan 3, 2014 at 11:26
Add a ment  | 

5 Answers 5

Reset to default 3

you should handle change event:

$('input:checkbox,textarea').change(function () {
   alert('changed');
});

The oninput event is only triggered when the text of an input changes, so it won't be fired for checkboxes. Try binding to the change event for checkboxes and the input event on textareas:

$("textarea").on("input", yourFunction);
$("input:checkbox").on("change", yourFunction);

function yourFunction() {
    alert("CHANGED");
}

jsFiddle which demonstrates the above.

Note: The difference in this answer is the alert is triggered immediately in the textarea, not only on blur of the element.

Additional Note: The oninput event isn't supported in < IE9

Why you bind input event for checkbox, it's only fire for textarea?

You need to bind change event :

Try this one:

Updated

$(document).ready(function()
{
    $("textarea").on("input", function(){
      alert("CHANGED");
    });

    $("input").on("change", function(){
        alert("CHANGED");
    });
});

Try in fiddle

Checkboxes usually used with same name property so in selector name property will be usefull

$("input[name='interests']").change(function(){
   /*some code*/
});

It will not work on textarea . you can assign all radio button and textarea a same class and then

$(".your_class_name").on("change", function()
{
    alert("CHANGED");
});
发布评论

评论列表(0)

  1. 暂无评论