jQuery - Select Element Where Value Equals

I'm trying to find a simple way to check a radio option using jQuery based on its initial value at render time.

<form>
<input type="radio" name="myRadio" value="weekly" />Weekly <br />
<input type="radio" name="myRadio" value="monthly" />Monthly <br />
<input type="radio" name="myRadio" value="yearly" />Yearly <br />
</form>

And the Javascript:

$('input [value="weekly"]').prop("checked", true);

I have a JS fiddle set up here: http://jsfiddle.net/xpvt214o/448712/

The interesting thing is that it works using the native browser document.querySelector but it doesn't seem to work using jQuery. I'd like to stick with jQuery's way of doing this to ensure consistency in the code.

Also, the reason I want to select by value is that the JSON API I'm calling returns an enumerated string type. It would be really annoying if I had to add a unique ID attribute to each radio option and then use a switch case to select the appropriate button based on the enumerated string type.

Upvotes: 3

Views: 6350

Answers (2)

jvk
jvk

Reputation: 2201

$(function(){
          $('input[type="radio"][value="weekly"]').prop('checked', true);    

        })   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="radio" name="myRadio" value="weekly" />Weekly <br />
<input type="radio" name="myRadio" value="monthly" />Monthly <br />
<input type="radio" name="myRadio" value="yearly" />Yearly <br />
</form>

Upvotes: 1

Matheus Cuba
Matheus Cuba

Reputation: 2156

Simple remove the space between your selector and the attribute:

$('input[value="weekly"]').prop("checked", true);

$('input[value="weekly"]').prop("checked", true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="radio" name="myRadio" value="weekly" />Weekly <br />
  <input type="radio" name="myRadio" value="monthly" />Monthly <br />
  <input type="radio" name="myRadio" value="yearly" />Yearly <br />
</form>

With space, you are telling jQuery to select elements that have [value="weekly"] but are descendants of an input element

Upvotes: 3

Related Questions