patternjavascriptMinor
Show one form that corresponds to the selected radio button
Viewed 0 times
showtheradioonecorrespondsthatselectedbuttonform
Problem
This piece of code I have written works, but I don't think its the best solution.
What I am doing is check if a certain radio is checked if it is show this div if else show this div if this radio is checked etc.
Can someone point me in the right direction on this one? I would love to know how to write less do more.
What I am doing is check if a certain radio is checked if it is show this div if else show this div if this radio is checked etc.
Can someone point me in the right direction on this one? I would love to know how to write less do more.
$(document).ready(function () {
$('.Form').hide();
$('input').click(function () {
if ($('input[value=informed]:checked').length) {
$('#ContactFormOne').show();
$("#ContactFormTwo, #ContactFormThree, #ContactFormFour, #ContactFormFive, #ContactSix'").hide();
} else if ($('input[value=release]:checked').length) {
$('#ContactFormTwo').show();
$("#ContactFormOne, #ContactFormThree, #ContactFormFour, #ContactFormFive, #ContactSix'").hide();
} else if ($('input[value=intake]:checked').length) {
$('#ContactFormThree').show();
$("#ContactFormTwo, #ContactFormOne, #ContactFormFour, #ContactFormFive, #ContactSix'").hide();
} else if ($('input[value=checklist]:checked').length) {
$('#ContactFormFour').show();
$("#ContactFormTwo, #ContactFormOne, #ContactFormThree, #ContactFormFive, #ContactSix'").hide();
} else if ($('input[value=health]:checked').length) {
$('#ContactFormFive').show();
$("#ContactFormTwo, #ContactFormOne, #ContactFormThree, #ContactFormFour, #ContactSix'").hide();
}
})
});Solution
Though your conditions are fine, I'd suggest you for a radical change in the code.
The code will be:
where, I'm assuming you have jQuery 1.9.1.
For a better answer, please include your HTML in the question too.
- Change the
ids as follows:
ContactFormOnetoinformed
ContactFormTwotorelease
ContactFormThreetointake
ContactFormFourtochecklist
ContactFormFivetohealth
- The code will get a lot shorter now.
The code will be:
$(document).ready(function () {
$('.Form').hide();
$('input').on( 'change', function () {
var ValUe = $(this).val();
$('.Form').hide(); //Replace the '.Form' selector with the element that is containing your contact forms.
$('#' + ValUe).show();
})
});where, I'm assuming you have jQuery 1.9.1.
For a better answer, please include your HTML in the question too.
Code Snippets
$(document).ready(function () {
$('.Form').hide();
$('input').on( 'change', function () {
<!--check if its One-->
var ValUe = $(this).val();
$('.Form').hide(); //Replace the '.Form' selector with the element that is containing your contact forms.
$('#' + ValUe).show();
})
});Context
StackExchange Code Review Q#23724, answer score: 3
Revisions (0)
No revisions yet.