I have 5 questions in a form, and a few of them have a YES / NO response. I wanted to just be able to toggle the yes and no buttons once the user selected one of them. The i
You can use .closest('div') to target the closest div of the element that triggered the .change() event and use .find() to target the class.
One function to to deal with all change events for elements with the class of MyToggle
This will allow you to run the same function for all questions as shown in the demo below.
Update: Yes/No toggle
Demo
$(".MyToggle").click(function() {
$(this).val()=='yes'?$(this).closest('div').find('.Questions').show():$(this).closest('div').find('.Questions').hide();
});
.Questions{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Yes<button class="MyToggle" value="yes">Yes</button> <button class="MyToggle" value="no">No</button>
<div class="Questions">Questions?</div>
</div>
<div>
Yes<input type="radio" name="Q2" class="MyToggle" value="yes"/> No<input type="radio" name="Q2" class="MyToggle" value="no"/>
<div class="Questions">Questions?</div>
</div><div>
Yes<input type="radio" name="Q3" class="MyToggle" value="yes"/> No<input type="radio" name="Q3" class="MyToggle" value="no"/>
<div class="Questions">Questions?</div>
</div>
I hope this helps. Happy coding!
Looks like NewToJS beat me to the punch with the closest DIV, but instead we use a .each() to remove the active class from all buttons in the DIV before adding the active class only to the clicked button.
This example uses buttons instead of radio controls.
$('.yes-no').click(function(){
$(this).closest('div').find('.yes-no').each(function(){
$(this).removeClass('active');
});
$(this).addClass('active');
});
jsFiddle Demo
And when it comes time to sum up all the answers, you would do it this way:
$('#mybutt').click(function(){
var cnt = 0;
var obj = {};
$('.btn-group').each(function(){
cnt++;
obj[cnt] = $(this).find('.active').text();
});
alert( JSON.stringify(obj) );
});
jsFiddle Demo
You need to add a unique id or class for each button and link a click function for each button like this:
$('.btn-toggle').click(function() {
$(this).toggleClass('active');
console.log($(this));
});
$('.btn-toggle2').click(function() {
$(this).toggleClass('active');
console.log($(this));
});
$('.btn-toggle3').click(function() {
$(this).toggleClass('active');
console.log($(this));
});
$('.btn-toggle4').click(function() {
$(this).toggleClass('active');
console.log($(this));
});
Or you can group them together like this if they have a common function:
$('.btn-toggle', '.btn-toggle2', '.btn-toggle3', '.btn-toggle4') .click(function() {
$(this).toggleClass('active');
console.log($(this));
});