Changing radio button values and adding classes with jquery
I'm trying to user jquery to add/remove a class on a pair of divs which consist of a background images. The div/image is meant to act as a radio box for a pair of hidden radio boxes.
When clicking the div/image the script should apply the class 'selected' to the clicked div and remove it (if necessary) from the other; and select the appropriate hidden radio button.
To the best of my knowledge the below script should work, but isn't and I'm not really sure what I'm doing incorrectly right now. Any ideas stackers?
SCRIPT
$("div#like").click(function() {
var $radios = $('input:radio[name=vote]');
$("div#dislike").removeClass("selected");
$("div#like").addClass("selected");
$radios.filter('[value=likes]').attr('checked', true);
});
$("div#dislike").click(function() {
var $radios = $('input:radio[name=vote]');
$("div#like").removeClass("selected");
$("div#dislike").addClass("selected");
$radios.filter('[value=likes]').attr('checked', true);
});
HTML
<form action="createComment.php" method="post">
<div id="like" ><input class="like" type="radio" name="vote" value="likes" /></div>
<div id="dislike" ><input class="dislike" type="radio" name="vote" value="dislikes" /></div><br/>
</form>
[EDIT 3:07PM] What if I went this route?
$("div#like").click(function() {
var $radios = $('input:radio[name=vote]');
$("div#dislike").removeClass("selected");
$("div#like").ad开发者_运维百科dClass("selected");
$radios.filter('[value=likes]').attr('checked', true);
$radios.filter('[value=dislikes]').attr('checked', false);
});
$("div#dislike").click(function() {
var $radios = $('input:radio[name=vote]');
$("div#like").removeClass("selected");
$("div#dislike").addClass("selected");
$radios.filter('[value=dislikes]').attr('checked', true);
$radios.filter('[value=likes]').attr('checked', false);
});
Don't set the attribute checked="checked"
using javascript. Instead, use
radioButton.checked = true
Using jquery you can do,
$radios.filter('[value=likes]').get(0).checked = true
Here is a nice little example for you, http://jsfiddle.net/cu2y8/6/
You set checked to true on the [value=likes] button regardless of which div gets clicked.
Make sure you select the [value=dislikes] button when the dislike div is clicked.
精彩评论