[英]How do I trigger an initial change event for radio buttons with jquery?
我正在尝试启用/禁用一组单选按钮底部的“其他”字段,如下所示:
window.init = function() { debugger; var form = $("#myform"); var enableOther = function() { var other = $(this).val() == 'other'; form.find('input[name=other]').prop('disabled', !other); }; var options = form.find('input:radio[name=myradio]'); options.change(enableOther); //now I want to call the on-change handler to update the initial disabled value $.proxy(enableOther, options)(); //these don't work //options.trigger('change'); //options.triggerHandler('change'); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button onclick="debugger; init();">Init</button> <form id="myform"> <ul> <li><input type="radio" name="myradio" value="1" />Item 1</li> <li><input type="radio" name="myradio" value="2" />Item 2</li> <li><input type="radio" name="myradio" value="3" />Item 3</li> <li><input type="radio" name="myradio" value="other" />Other</li> <li><input type="text" name="other" /></li> </ul> </form>
(单击“初始化”,选择“其他”,再次单击“初始化”,然后该字段错误地变为禁用状态)
单击每个项目时此方法工作正常,但我希望能够在init函数.change()
我的.change()
jQuery回调触发器一次(此片段会变为具有持久值的弹出形式)。 我已经尝试过.proxy
和trigger
,但是我似乎正在获取所有单选按钮,而.val()
是单个值,而不是所选的值。
我应该如何人为地触发此回调?
单选按钮很奇怪。
在回调中,将选择器用于选中的那个。
var myval = $('input[type="radio"][name="myradio"]:checked').val();
var other = myval == 'other';
注意:请使用[type="radio"]
而不是:radio
因为当浏览器支持选择器时,它可以提高选择器的效率。
测试:为证明概念,请在调用init之前设置OTHER:
$('input[type="radio"][name="myradio"]').eq(3).prop('checked',true);
然后是不是:
$('input[type="radio"][name="myradio"]').eq(2).prop('checked',true);
然后使用您尝试过的方法:
options.trigger('change');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.