jQuery newbie: how to update radio buttons values in my case?
I have a group of radio buttons on my page:
<input type="radio" name="fruit" value="apple" checked> apple
<input type="radio" name="fruit" value="orange"> orange
<input type="radio" name="fruit" value="banana"> banana
If I want to 开发者_开发百科update the appearance value of the radio buttons dynamically, how to do it in jQuery (or what is the best way to do it in jQuery)? I am using jQuery 1.5.1
I mean for example, update the values from :
"apple", "orange" and "banana"
to
"watermelon", "pear" and "strawberry".
First you will need to add value attributes to each of the radio buttons
<input type="radio" name="fruit" value="apple" checked> apple
<input type="radio" name="fruit" value="orange"> orange
<input type="radio" name="fruit" value="banana"> banana
you can then use jquery to update the values with
$("input[value='apple']").val("Melon");
Ideally you would want to add a unique identifier to each of the radio buttons for example
<input id="option1" type="radio" name="fruit" value="apple" checked="checked"> <label for="option1">apple</label>
<input id="option2" type="radio" name="fruit" value="orange" checked="checked"> <label for="option2">orange</label>
<input id="option3" type="radio" name="fruit" value="banana" checked="checked"> <label for="option3">banana</label>
By adding an id to each of the radio buttons allows you to do the following:
$("#option1").val("Melon"); //This will update the radio button value
$("label[for='option1']").html("Melon"); //This will update the label value
Also by wrapping the labels in label tags makes them clickable to select the associated radio button
精彩评论