Reputation: 80
I made this jsfiddle: http://jsfiddle.net/6tZmc/1/
Basically, I would like to update an empty span based on radio button choice. Here is the code:
html
<div>
<p>Your chose: <span id="animal"></span></p>
</div>
<div>
<h2>Pick an Animal:</h2>
<input type="radio" name="pets" value="cat" />Cats<br />
<input type="radio" name="pets" value="dog" />Dogs
</div>
jQuery:
function petChoice(){
var chosenPet = $('input[name="pets"]:checked').val();
if(chosenPet = 'cat'){
$("span#animal").text();
$("span#animal").text("Cats");
}else if (chosenPet = 'dog'){
$("span#animal").text();
$("span#animal").text("Dogs");
}else{
$("span#animal").text();
}
}
$("input[name='pets']").click(function(){
petChoice();
});
Thanks in advance
Upvotes: 0
Views: 57
Reputation: 21477
function petChoice(){
var chosenPet = $('input[name="pets"]:checked').val();
if(chosenPet == 'cat'){
$("span#animal").html("Cats");
}else if (chosenPet == 'dog'){
$("span#animal").html("Dogs");
}else{
$("span#animal").empty();
}
}
$("input[name='pets']").click(function(){
petChoice();
});
jsfiddle: http://jsfiddle.net/6tZmc/4/
Upvotes: 0
Reputation: 5298
In your if statement you are trying to assign cats
and dogs
to chosenPet
when in fact, you'd like to test equality. Change =
to ==
Upvotes: 4
Reputation: 10658
Don't forget to wrap you function so that it is executed after the document
is ready.
Also you can shorten your function by just setting the text to the value of the radio button that was clicked. In jQuery events, this
refers to the element that triggered the event.
$(function () {
$("input[name='pets']").click(function () {
$("#animal").text($(this).val());
});
});
Working fiddle.
Upvotes: 1