简体   繁体   English

如何以编程方式设置radiobutton并使用js选择选项

[英]How to programmatically set radiobutton and select option with js

For ex. 对于前者 we have 我们有

<select id="menu">
<option value="1">sample 1</option>
<option value="2">sample 2</option>
</select>

and

<input type="radio" id="parentcheck" value="1">Button 1 
<input type="radio" id="parentcheck" value="2">Button 2 

I want to simply "clone" user input. 我想简单地“克隆”用户输入。 Let's say we want to set them to exact values and trigger their functions. 假设我们想要将它们设置为精确值并触发它们的功能。


In my case i have functions for both of them 在我的情况下,我有两个功能

 $("#menu").change(function () {...
 $(".parentcheck").click(function () {...

For ex. 对于前者 how to select Sample 1 and Button 1 and fire their function? 如何选择样品1和按钮1并激活它们的功能?

For the first case you can use .val() and trigger the event manually in both cases. 对于第一种情况,您可以使用.val()并在两种情况下手动触发事件。

Consider the following 考虑以下

$('#menu').val(2).trigger('change');

In the above, we select the option with the value of 2. 在上面,我们选择值为2的选项。

And for the radio buttons 而对于单选按钮

$('#parentcheck').prop('checked', true).trigger('change');

Just set the attribute of the option/checkbox 只需设置选项/复选框的属性即可

For the options it is "selected" and for the checkboxes it is "checked" 对于选项,它被“选中”,对于复选框,它被“选中”

Also, trigger the event after that using trigger() 此外,使用trigger()在此之后触发事件

Example: 例:

$( '#menu option[value=whatever]' ).attr( 'selected', 'selected' ).trigger( 'change' );
$( '.parentcheck' ).attr( 'checked', 'checked' ).trigger( 'click' );

Again the same answer 同样的答案

$("#menu option[value='1]").prop("selected",true).trigger("change");

$("input[type='radio'][value='1']").prop("checked",true).trigger("change");

use .prop instead of .attr 使用.prop而不是.attr

I think this is something you are looking for... 我认为这是你正在寻找的东西......

$("#menu option[value='1]").attr("selected",true).trigger("change");
$("input[type='radio'][value='1']").attr("checked",true).trigger("change");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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