jquery on('change'… not working in multiple tags [duplicate]

左心房为你撑大大i 提交于 2019-12-12 03:25:38

问题


I can't get the .val() of my second input select when I use jquery .on('change' function()

I have 2 select elements:

<select id="itemsA">
   <option selected disabled>Select option</option>
   <option value="a">Item A</option>
   <option value="b">Item B</option>
   <option value="c">Item C</option>
   <option value="d">Item D</option>
</select>
<select id="itemsB">
   <option selected disabled>Select option</option>
   <option value="1">Item 1</option>
   <option value="2">Item 2</option>
   <option value="3">Item 3</option>
   <option value="4">Item 4</option>
</select>

Here is my jquery code

$(document).ready(function(){
    $("select").on('change', function(){
        var mySel = $("select").val();
        console.log(mySel);
    });
});

I get the value of the first input select but the second one always give me null as value check.


回答1:


$(document).ready(function(){
    $("select").on('change', function(){
        var mySel = $(this).val();
        console.log(mySel);
    });
});

You need to use this!

** When you were using $('select') the val function can return a string only so it returns the first available value out of the selection made of 2 in your case



来源:https://stackoverflow.com/questions/36874750/jquery-onchange-not-working-in-multiple-tags

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