Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 979
LEQADA Avatar asked Oct 05 '11 17:10

LEQADA


2 Answers

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');
like image 151
cillierscharl Avatar answered Oct 04 '22 21:10

cillierscharl


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' );
like image 45
DarkDevine Avatar answered Oct 04 '22 20:10

DarkDevine