user947668
user947668

Reputation: 2728

Set first options selected using jquery

There are two options lists with different names, i need to set first options selected in both of them.

<input type="radio" name="first_list" value="0">abc
<input type="radio" name="first_list" value="1">cba

<input type="radio" name="second_list" value="0">opc
<input type="radio" name="second_list" value="1">cpo

Sure, i can do this way:

$("input:radio[name='first_list'][value='0']").attr("checked", "checked");
$("input:radio[name='second_list'][value='0']").attr("checked", "checked");

Maybe there is another more compact way to do this?

Upvotes: 0

Views: 186

Answers (4)

Jobelle
Jobelle

Reputation: 2834

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>

    $(document).ready(function () {
        $('input:radio[value="0"]').prop("checked",true)

    });
</script>
</head>
<body>
 <input type="radio" name="first_list" value="0">abc
<input type="radio" name="first_list" value="1">cba

<input type="radio" name="second_list" value="0">opc
<input type="radio" name="second_list" value="1">cpo</body>
</html>

Upvotes: 0

Jay Blanchard
Jay Blanchard

Reputation: 34416

If the markup you show above is complete you can use prop to check the boxes -

$('input:radio:even').prop('checked', true);

http://jsfiddle.net/r82RE/

Upvotes: 0

andrux
andrux

Reputation: 2922

Try this, it will work no matter how many inputs you have on each set and even if the values are not consistent between sets:

$( $( 'input[type=radio]' ).toArray().reverse() ).prop( 'checked', true );​​​​​​​​​​​​​

It will actually check all radio inputs from last to first, but only the very first will remain checked.

Upvotes: 0

jcolicchio
jcolicchio

Reputation: 808

$("input:radio[value='0']").attr("checked", "checked");​

This worked for me: http://jsfiddle.net/jcolicchio/46WXn/

Upvotes: 2

Related Questions