I have a radio form elements with other fields as well on a webpage, there have two types of form radio field, one is vegetable and other is meat. I want to select like these "If they select a meat they have to select a veggie but if they only select a veggie they don't have to select a meat" here is the screenshot of these radio fields http://prntscr.com/nhu6ao
jQuery('.radio').change(function() {
jQuery(this).parent().removeClass('error');
jQuery(this).parent().parent().removeClass('error');
if (jQuery(this).hasClass('box-input')) {
jQuery('#preseason-error').slideUp("slow");
jQuery('#preseason-title').css("color", "#444");
jQuery('.boxes-select').removeClass('error');
}
})
Results will be: If they select a meat they have to select a veggie but if they only select a veggie they don't have to select a meat
Voila!
I have prepped a simple example for you. Before we begin I would like to point out 2 things. It is very inefficient to create an event listener for every form element, as you did by calling the .on('.radio')
. Good practice here is to add event listener on the form ( or any other wrapping element - even body ), and than use the event.target
as your reference to the form element that was just clicked by the user.
Another thing is that from the UX perspective I would suggest moving the Meat dishes above the Veggies, as it does not make sense to show it as a first choice if Veggies are somehow dependant on Meats.
JSfiddle with working example: https://jsfiddle.net/mkbctrlll/7209ayr3/45/
const $meals = $('#meal-options')
$meals.on('change', function(event) {
if(event.target.name === 'meat') {
console.log('Meat selected!')
$('input[name="veggie"]').attr('required', 'true')
}
})
<form id="meal-options">
<h2>
Meat options
</h2>
<label for="radio-1">
<input id="radio-1" name="meat" type="radio">
Meat 1
</label>
<label for="radio-2">
<input id="radio-2" name="meat" type="radio">
Meat 2
</label>
<h2>
Veggie options
</h2>
<label for="radio-3">
<input id="radio-3" name="veggie" type="radio">
veggie 1
</label>
<label for="radio-4">
<input id="radio-4" name="veggie" type="radio">
veggie 2
</label>
<label for="radio-5">
<input id="radio-5" name="veggie" type="radio">
veggie 3
</label>
<input type="submit">
</form>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.