开发者

How to programmatically set radiobutton and select option with js

开发者 https://www.devze.com 2023-04-10 17:20 出处:网络
For ex. we have <select id=\"menu\"> <option value=\"1\">sample 1</option> <option value=\"2\">sample 2</option>

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 t开发者_如何学Gohem 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?


For the first case you can use .val() and trigger the event manually in both cases.

Consider the following

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

In the above, we select the option with the value of 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()

Example:

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


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");


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

0

精彩评论

暂无评论...
验证码 换一张
取 消