jquery - content to appear on ONE particular select option.
I am new here. I am trying to learn jquery - and i have a problem that I can't fix. I think I am pretty close? but i've worked myself up into a muddle over it and now i cant see the wood for the trees.
I have a form with a select in it. if the user selects the option 'YES' then i want another peice of content to appear. if the user selects no, then they just carry on filling in the form. i do realise that perhaps this could have been done with radio buttons, but i am bound to the snippet of html i have and can't change it.
<form>
<select id="test-select">
<option>select</option>
<option>yes</option>
<option>no</option>
</select>
<div class="show-me">
<p>HOORAAAAYYYYYYYYYY!!!!!!!</p>
</div>
<!--more form goes below this line here - not important to the question -->
</form&开发者_Go百科gt;
so far, i have the jquery working that it can get the values of the options. but then i am stuck. in my head i realise i need to do something IF the value of the option equals YES but i have no idea how to write that. the piece below is not working at all for me.
$(function(){
$("#test-select").change(function(){
var selectedValue = $(this).find(":selected").val();
console.log("the value you selected: " + selectedValue);
if $(selectedValue).contains('yes') {
console.log("you have selected yes - so write something to show the div now");
}
else {
console.log("you have not selected yes, carry on filling in form");
}
});
});
can anyone explain the next step to me please, so i can understand jquery better and where i am slipping up
i have seen a post here where someone has content changing on each different select, but i only want my div to appear when YES has been selected so i couldn't translate that into how to fix my problem unfortuantely. i did try!
thank you!
First off I believe you just need to do
var selectedValue = $(this).val();
To get the selected item in a list. Then you just need to do something like ...
if (selectedValue == "yes")
{ $(".show-me").show(); }
else
{ $(".show-me").hide(); }
Edit: Here is a link to an example in jsfiddle http://jsfiddle.net/hR2sx/
You're overthinking it!
if $(selectedValue).contains('yes') {
This line won't work, since calling $() against selectedValue will attempt to make it a jQuery object, whereas before it was a string.
You should try this instead:
if (selectedValue=="yes") {
DEMO FIDDLE
$('.show-me').hide();
$("#test-select").change(function() {
var val = $(this).val();
if(val == 'yes'){
$('.show-me').fadeIn();
}
else{
$('.show-me').fadeOut();
// do the rest........
}
});
use
var selectedValue = $("#test-select option:selected").val();
if(selectedValue == "yes") { ...
Make sure the div is display:none
by default:
$(function(){
$('#test-select').change(function() {
$('div.show-me').toggle('yes'==$(this).val());
});
});
精彩评论