Reputation: 47
I had a similar issue previously, and was able to get that sorted for an either/or situation. What I want is the "yes" radio button to toggle the appearance of a div with additional questions. After looking at other solutions in the forums, I think my HTML is solid but my jquery is wonky. I'm not sure what I'm doing wrong.
$(document).ready(function(){
$("input[name$='yes']").click(function(){
var test = $(this).val();
$("div.desc").show();
});
});
Here's a fiddle with my html as well as jQuery : http://jsfiddle.net/g63m9yyg/
Also, if there are any good jQuery/JS tutorials or resources, please refer me. HTML/CSS was easy for me to pick up but I'm struggling with jQuery, and I'm using it a lot for this project.
Thank you!
Upvotes: 0
Views: 49
Reputation: 66133
I believe you have forgotten to load the jQuery library in your fiddle. Also, the input element with the name ifmachinery
does not exist... I believe you are referring to the one with the name machinery
?
Instead of binding the click event to inputs, I usually recommend binding it to the .change()
event, and then use a logic to decide what to do depending on the value of the input. In this sense your code will be extensible and easily modifiable, and likely to be more verbose.
$(document).ready(function(){
$("input[name='machinery']").change(function(){
if($(this).val()=='yes') {
$("div.desc").show();
} else {
$("div.desc").hide();
}
});
});
http://jsfiddle.net/teddyrised/g63m9yyg/2/
If you want this logic to apply when the page is first loaded, you will have to run/execute this logic on DOM ready, too. Instead of repeating the function twice, i.e.:
$(document).ready(function(){
// Run when DOM is ready
if($(this).val()=='yes') {
$("div.desc").show();
} else {
$(("div.desc").hide();
}
// When input is changed
$("input[name='machinery']").change(function(){
if($(this).val()=='yes') {
$("div.desc").show();
} else {
$(("div.desc").hide();
}
});
});
You can simply put the logic in a function, and call it with both DOM ready and input onChange events:
$(document).ready(function(){
// Define logic
var ifMachinery = function(ele) {
if(ele.val()=='yes') {
$("div.desc").show();
} else {
$("div.desc").hide();
}
}
// Run logic on DOM ready
ifMachinery($("input[name='machinery']"));
// Run logic when input onChange is fired
$("input[name='machinery']").change(function() {
ifMachinery($(this));
});
});
http://jsfiddle.net/teddyrised/g63m9yyg/3/
Upvotes: 1