Bootstrap checkbox buttons not changing state - javascript

I used to have radio buttons, but I changed the script to use bootstrap checkboxes. But it is not changing the state when using bootstrap switches.
This is snippet of my code:
<div class="form-group">
<div class="radio-list">
<label class="radio-inline">
<input type="radio" name="upd_active" class="updactive" id="upd_yes" value="1" checked> Yes </label>
<label class="radio-inline">
<input type="radio" name="upd_active" class="updactive" id="upd_no" value="0"> No </label>
</div>
</div>
<script>
function action(){}
var parentflag = $('#upd_yes').parents('.form-group');
parentflag.find('span').removeClass('checked');
if(is_active == "1"){
$("#upd_no").attr('checked', false);
$("#upd_yes").attr('checked', true);
$('#upd_yes').parent().addClass('checked');
}
else{
$("#upd_yes").attr('checked', false);
$("#upd_no").attr('checked', true);
$('#upd_no').parent().addClass('checked');
}
}
</script>
<div class="form-group">
<label class="col-md-3 control-label">IsActive<span class="text-danger">*</span></label>
<div class="col-md-8">
<input type="checkbox" name="upd_active" class="make-switch updactive" id="upd_yes" value="1" checked>
</div>
</div>
<script>
function action(){
var parentflag = $('#upd_yes').parents('.form-group');
parentflag.find('span').removeClass('checked');
if(is_active == "1"){
$("#upd_yes").attr("checked",true);
$('#upd_yes').parent().addClass('checked');
}
else{
$("#upd_yes").attr("checked",false);
$('#upd_yes').parent().removeClass('checked');
}
}
</script>
How can I fix this?

Am able to find 2 issues(actually not issues) as below
is_active is not declared so you cannot check it with if statement
Most importantly your action() function not at all initiated.
So i added below code and updated the snippet.
var is_active = 0;
action();
var is_active = 0;
action();
function action() {
var parentflag = $('#upd_yes').parents('.form-group');
parentflag.find('span').removeClass('checked');
if (is_active == "1") {
$("#upd_yes").attr("checked", true);
$('#upd_yes').parent().addClass('checked');
} else {
$("#upd_yes").attr("checked", false);
$('#upd_yes').parent().removeClass('checked');
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="col-md-3 control-label">IsActive<span class="text-danger">*</span></label>
<div class="col-md-8">
<input type="checkbox" name="upd_active" class="make-switch updactive" id="upd_yes" value="1" checked>
</div>
</div>

Related

Radio Button checked as default remains on true

Please help me try figure out why my radio button default checked remains to True.
Here is my js file:
$(document).ready(function () {
var is_display = $("#is_display_value").val();
if (is_display) {
$("#id_is_display_True").prop("checked", true);
$("#id_is_display_False").prop("checked", false);
} else {
$("#id_is_display_True").prop("checked", false);
$("#id_is_display_False").prop("checked", true);
}
});
html:
<div class="status">
<p>Status</p>
<input type="hidden" value="False" id="is_display_value"> <!-- Value of {{is_display}} is based on Database, True or False -->
</div>
<div class="status status-body">
<div class="status-choice">
<input type="radio" class="triple" name="is_display" value="True" id="id_is_display_True">
<label for="hide">Show</label>
</div>
<div class="status-choice">
<input type="radio" class="triple" name="is_display" value="False" id="id_is_display_False">
<label for="hide">Hide</label>
</div>
</div>
My JSFiddle
First you input value return a string (you case capitalized string )
first get the value string as
var is_display = $("#is_display_value").val().toLowerCase();
in your condition if (is_display) , it'll always return true because you check if the string "True" or "False" will always return true
you can fix that using one condition as :
//get value to lower case
var is_display = $("#is_display_value").val().toLowerCase();
$("#id_is_display_true").attr("checked", is_display == "true");
$("#id_is_display_false").attr("checked", is_display == "false");
See below snippet :
$(document).ready(function () {
var is_display = $("#is_display_value").val().toLowerCase();
$("#id_is_display_true").attr("checked", is_display == "true");
$("#id_is_display_false").attr("checked", is_display == "false");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="status">
<p>Status</p>
<input type="hidden" value="False" id="is_display_value">
</div>
<div class="status status-body">
<div class="status-choice">
<input type="radio" class="triple" name="is_display" id="id_is_display_true" value="true">
<label for="hide">Show</label>
</div>
<div class="status-choice">
<input type="radio" class="triple" name="is_display" id="id_is_display_false" value="false">
<label for="hide">Hide</label>
</div>
</div>

How to check/uncheck 3 secondary checkboxes according to 1 principal checkbox (19times)?

I have 19 cards of 4 checkboxes: 1 main checkbox (date) and 3 secondary checkboxes (options for that date). I would like the 3 secondary options to be checked when the main one is checked and conversely that they are unchecked when the main one is unchecked.
I would like to use a single function for all 19 cards. However, checkboxes have different ids.
When I click on a main checkbox
I get the id from the main checkbox.
I retrieve the number contained in the id.
I apply it to three values to create the id of 3 secondary checkboxes.
If the main checkbox is checked:
I check the secondary checkboxes.
If the main checkbox is unchecked:
I uncheck the secondary checkboxes.
I tried with "onclick" and "onchange".
function Autocheck(id) {
var clicked_id = id;
var StgNbr = clicked_id.substr(4);
var diner = "Dîner" + StgNbr;
var souper = "Souper" + StgNbr;
var logement = "Logement" + StgNbr;
if (clicked_id.checked = true) {
alert('je suis coché');
var items = document.getElementsByClassName('presence');
for (var i = 0; i < items.length; i++) {
if (items[i].id == diner)
items[i].checked = true;
if (items[i].id == souper)
items[i].checked = true;
if (items[i].id == logement)
items[i].checked = true;
}
} else {
alert('je suis décoché');
var items = document.getElementsByClassName('presence');
for (var i = 0; i < items.length; i++) {
if (items[i].id == diner)
items[i].checked = false;
if (items[i].id == souper)
items[i].checked = false;
if (items[i].id == logement)
items[i].checked = false;
}
}
}
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-3">
<div class="card">
<label for="date1"><div class="card-media"><input type="checkbox" id="date1" class="date presence" name="Dates" onclick="Autocheck(this.id)"> Mardi 23/07</div></label>
<div class="card-details">
<input type="checkbox" class="presence" name="Dîner" id="Dîner1">
<label for="Dîner1"> Dîner</label><br>
<input type="checkbox" class="presence" name="Souper" id="Souper1">
<label for="Souper"> Souper</label><br>
<input type="checkbox" class="presence" name="Logement" id="Logement1">
<label for="Logement"> Logement</label><br>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-3">
<div class="card">
<label for="date2"><div class="card-media"><input type="checkbox" id="date2" class="date presence" name="Dates" onchange="Autocheck(this.id)"> Mercredi 24/07</div></label>
<div class="card-details">
<input type="checkbox" class="presence" name="Dîner" id="Dîner2">
<label for="Dîner2"> Dîner</label><br>
<input type="checkbox" class="presence" name="Souper" id="Souper2">
<label for="Souper2"> Souper</label><br>
<input type="checkbox" class="presence" name="Logement" id="Logement2">
<label for="Logement2"> Logement</label><br>
</div>
</div>
</div>
My secondary checkboxes are well cheched but they don't uncheck.
Also : my 'test' alert is always saying that the principal checkbox is checked even if I uncheck it.
Thank you for your help.
Here is a click listener and on click of main checkbox we check/uncheck child check boxes. Is this what you are looking for?
const getParentCard = (e, classToMatch) => {
while( e.classList.contains(classToMatch) === false)
{
e = e.parentNode;
}
return e;
};
document.addEventListener('click', (e) => {
if(e.target.matches('input.date')){
getParentCard(e.target,'card').querySelectorAll('input[type="checkbox"]').forEach(chk => {
chk.checked = e.target.checked;
});
}
});
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-3">
<div class="card">
<label for="date1">
<div class="card-media">
<input type="checkbox" id="date1" class="date presence" name="Dates"> Mardi 23/07
</div>
</label>
<div class="card-details">
<input type="checkbox" class="presence" name="Dîner" id="Dîner1">
<label for="Dîner1"> Dîner</label><br>
<input type="checkbox" class="presence" name="Souper" id="Souper1">
<label for="Souper"> Souper</label><br>
<input type="checkbox" class="presence" name="Logement" id="Logement1">
<label for="Logement"> Logement</label><br>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-3">
<div class="card">
<label for="date2"><div class="card-media"><input type="checkbox" id="date2" class="date presence" name="Dates"> Mercredi 24/07</div></label>
<div class="card-details">
<input type="checkbox" class="presence" name="Dîner" id="Dîner2">
<label for="Dîner2"> Dîner</label><br>
<input type="checkbox" class="presence" name="Souper" id="Souper2">
<label for="Souper2"> Souper</label><br>
<input type="checkbox" class="presence" name="Logement" id="Logement2">
<label for="Logement2"> Logement</label><br>
</div>
</div>
</div>
There are two main problems in your code:
if (clicked_id.checked = true) {
performs an assignment instead of a comparison but more importantly, clicked_id is a string and string values don't have a checked property. You'd have to access the checked property of the actual element , by either passing the element as argument to the function (preferred) or do
var element = document.getElementById(clicked_id);
//...
if (element.checked) {
// ...
}
Having said that, a more flexible approach that works with any number of check boxes without having to update the code is as follows:
Find closest common ancestor
Find all check boxes within that ancestor
Example:
function Autocheck(element) {
var ancestor = element.closest('.card');
if (ancestor) {
Array.from(ancestor.querySelectorAll('.presence')).forEach(function(input) {
input.checked = element.checked;
});
}
}
and use it as
<input type="checkbox" id="date1" class="date presence" name="Dates" onclick="Autocheck(this)">

My select area validation is forcing my page to automatically reload instead of running the validation

I have all of my other fields validating as I expect, but when I add in my JS to validate the select options, my page then just reloads once I hit submit. I have tried multiple ways to get the select options to validate, but I am failing to find a solution. I MUST use plain JS to validate the entire form, as per project requirements, and I am displaying an error message below each field in a span that doesn't contain any user input. I will post my JS below, and I can post my HTML if needed. I added in some extra spaces between my select area code to hopefully help with readability.
document.addEventListener("DOMContentLoaded", function (event) {
alert("This page is best viewed with JavaScript enabled");
});
function validate() {
// NEW: move this way up here so all validations can affect its value:
var formValid = true;
// function to check if a name has been entered
var name = document.getElementById('name').value;
if (name == null || name.trim() == "") {
document.getElementById('nameerror').innerHTML = "Please enter your full name";
formValid = false;
} else {
document.getElementById('nameerror').innerHTML = "";
}
// function to check if an email has been entered
var email = document.getElementById('email').value;
if (email == null || email.trim() == "") {
document.getElementById('emailerror').innerHTML = "Please enter your email address";
formValid = false;
} else {
document.getElementById('emailerror').innerHTML = "";
}
// function to check if a telephone number has been provided
var phone = document.getElementById('phone').value;
if (phone == null || phone.trim() == "") {
document.getElementById('phoneerror').innerHTML = "Please enter your telephone number";
formValid = false;
} else {
document.getElementById('phoneerror').innerHTML = "";
}
//validate the select options
var select = document.getElementById('select').value;
if (select == '') {
document.getElementById('selecterror').innerHTML = "Please make a selection";
formValid = false;
} else {
document.getElementById('selecterror').innerHTML = "";
}
//function to validate the textarea field
var name = document.getElementById('textarea').value;
if (name == null || name.trim() == "") {
document.getElementById('textareaerror').innerHTML = "Please enter additional info";
formValid = false;
} else {
document.getElementById('textareaerror').innerHTML = "";
}
// function to validate if any radio button has been selected
var radios = document.getElementsByName('radio');
var radiosValid = false;
var i = 0;
while (!radiosValid && i < radios.length) {
if (radios[i].checked) radiosValid = true;
i++;
}
if (!radiosValid) {
document.getElementById('radioerror').innerHTML = "(Please check one)";
formValid = false;
} else {
document.getElementById('radioerror').innerHTML = "";
}
// function to confirm if any checkbox has been checked
var checkboxes = document.getElementsByName('checkbox');
var checkboxesValid = false;
var j = 0;
while (!checkboxesValid && j < checkboxes.length) {
if (checkboxes[j].checked) checkboxesValid = true;
j++;
}
if (!checkboxesValid) {
document.getElementById('checkboxerror').innerHTML = "(Please select at least one)";
formValid = false;
} else {
document.getElementById('checkboxerror').innerHTML = "";
}
// now that all validations have run, return the conclusion
alert("The form has been submitted!");
return formValid;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Contact Us</title>
<style>
.contact-header {
font-family: cursive;
text-align: center;
font-size: 50px;
color: darkred;
}
form {
font-weight: bold;
text-align: center;
}
.contact {
font-weight: normal;
}
.checkbox input {
margin: 0 10px 0;
}
textarea {
width: 20%;
height: 5rem;
}
.sendRequest {
text-align: center;
}
</style>
<!--link to bootstrap css-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<!--link for icons-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<!--link to external stylesheet-->
<link href="restaurantStyles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<header>
<div class="jumbotron name-font">
<h1 class="display-4">Dan's Cakes</h1>
<hr class="my-4">
<p class="lead">BIG NEWS!! Dan's Cakes will be opening a new restaurant VERY soon!!!!</p>
</div>
</header>
<hr />
<nav>
<!--home icon link-->
<i class="fas fa-home"></i>
Menu
Contact Us
</nav>
<hr />
<h2 class="contact-header">Contact Us</h2>
<hr />
<!--form for contact info-->
<form name="contactForm" method="post" id="contactForm" novalidate onsubmit="return validate()">
<div class="form-group col-form-label">
<label for="name">Name: </label>
<input type="text" class="form-control" id="name" placeholder="Please enter your full name.." required>
<span id="nameerror" class="hint"></span>
</div>
<div class="form-group">
<label for="email">Email: </label>
<i class="fas fa-envelope prefix"></i>
<input type="email" class="form-control" id="email" placeholder="Please enter your email address.." aria-describedby="email" required>
<span id="emailerror" class="hint"></span>
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="phone">Phone: </label>
<i class="fas fa-phone-square"></i>
<input type="tel" class="form-control" id="phone" required>
<span id="phoneerror" class="hint"></span>
</div>
<!--select menu-->
<label for="reason-select">Reason For Inquiry:</label>
<select id="select " name="reason" class="custom-select" required>
<option value="">--Please Choose an Option--</option>
<option value="catering">Catering</option>
<option value="private">Private Party</option>
<option value="feedback">Feedback</option>
<option value="other">Other</option>
</select>
<span id="selecterror" class="hint"></span>
<br />
<br />
<!--text area for additional info-->
<div class="form-group">
<label for="info">Additional Information: </label>
<textarea class="form-control" id="textarea" rows="5"></textarea>
<span id="textareaerror" class="hint"></span>
</div>
<!--radio buttons for visiting restaurant-->
<label for="radio">Have you been to the restaurant?</label>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="radio" id="no-radio" value="no">
<label class="form-check-label" for="no-radio">
No
</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="radio" id="yes-radio" value="yes">
<label class="form-check-label" for="yes-radio">
Yes
</label>
<span id="radioerror" class="hint"></span>
</div>
<br />
<!--checkboxes for contacting-->
<label for="checkboxes">Best days to contact you:</label>
<div id="checkboxlist">
<div class="form-check form-check-inline">
<input class="form-check-input" name="checkbox" type="checkbox" id="monday" value="monday">
<label class="form-check-label" for="monday">M</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" name="checkbox" type="checkbox" id="tuesday" value="tuesday">
<label class="form-check-label" for="tuesday">T</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" name="checkbox" type="checkbox" id="wednesday" value="wednesday">
<label class="form-check-label" for="wednesday">W</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" name="checkbox" type="checkbox" id="thursday" value="thursday">
<label class="form-check-label" for="thursday">Th</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" name="checkbox" type="checkbox" id="friday" value="friday">
<label class="form-check-label" for="friday">F</label>
</div>
<span id="checkboxerror" class="hint"></span>
</div>
<!--send request button-->
<div class="sendRequest" id="contact-submit">
<input type="submit" value="Send Request">
</div>
</form>
<br />
<br />
<footer>
<p>1123 Silk Way, Anchorage, AK, 99501</p>
<p>907-998-0122</p>
</footer>
</div>
<script>
document.contactForm.name.onfocus = function () {
document.getElementById('namehint').innerHTML = "(Enter full name)";
}
</script>
<!--scripts for jquery, popper, and bootstrap-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<!--javascript link to external sheet-->
<script src="validate.js"></script>
<!--<script>
document.contactForm.name.onfocus = function () {
document.getElementById('namehint').innerHTML = "(Enter full name)";
}
</script>
-->
</body>
</html>
When using a submit button the default of it is to refresh or direct you to your location specified in the action attribute when defining your form html tags. If your goal is to stop this refresh, you will need to place an onClick attribute to your button that holds a function to be performed (If you know any other ways to place event listeners on DOM elements you may take that route as well I am just using this as an example), you would then would pass a variable such as event to hold the event action into the parameter. Then within the function use event.preventDefault();, this stops the refresh. After that command you can do any other validations you need to do, then trigger a refresh or new window location, whichever is your goal.
The first problem you have is you are doing:
var select = document.getElementById('select').value;
but the select is declared this way:
<select id="select " name="reason" class="custom-select" required>
it has "select " as ID, so you will get a TypeError saying you cannot read value from undefined. Its just a typo but what a typo! Just remove such trailing space:
<select id="select" name="reason" class="custom-select" required>
I think this should fix your problem. In addition, if you want to prevent the page from reloading, whether or not the form is valid, you have to prevent the default behaviour of a submit action. You can do that by calling preventDefault on the submit event, that you will need to pass to your function. Bear in mind that in this way the form will never be submitted, you will have to do it by yourself.
Pass the event to your function validate this way:
HTML
<form name="contactForm" method="post" id="contactForm" novalidate onsubmit="return validate(event)">
...
</form>
And prevent the default behaviour:
Javascript
function validate(e) {
e.preventDefault();
... // The rest of your code
}
Here is the official documentation of preventDefault
Let me know if this helps you, otherwise, tell me what went wrong.

Javascript - If/Else If result

I have these blocks:
function generateEmail(){
if
(document.getElementById('emailOpt1').checked = "true") {
document.getElementById('generatedEmail').innerHTML = emailOpt1.value
}
else if
(document.getElementById('emailOpt2').checked = "true") {
document.getElementById('generatedEmail').innerHTML = emailOpt2.value
}
else if
(document.getElementById('emailOpt3').checked = "true") {
document.getElementById('generatedEmail').innerHTML = emailOpt3.value
}
else if
(document.getElementById('emailOpt4').checked = "true") {
document.getElementById('generatedEmail').innerHTML = emailOpt4.value
}
}
and this:
<div class="radioEmailType" id="emailClass">
<input type="radio" id="emailOpt1" name=emailType value="email_c1">
<label for="emailOpt1">class-one</label>
<input type="radio" id="emailOpt2" name=emailType value="email_c2">
<label for="emailOpt2">class-two</label>
<input type="radio" id="emailOpt3" name=emailType value="email_c3">
<label for="emailOpt3">class-three</label>
<input type="radio" id="emailOpt4" name=emailType value="email_c4">
<label for="emailOpt4">class-four</label>
</div>
<button type="button" class="gButton" onclick=generateEmail()">GENERATE EMAIL</button>
<textarea id=generatedEmail></textarea></td></tr>
when I hit the 'generate email' button after selecting one of the 'radios', the code seems to revert the selection back to the first option as I keep on getting the first option on the textarea.
any ideas and a possibly a simpler way to do this will be appreciated.
note: I had to go this route since the user wants the radios to be buttons.
I fix it :
Change :
.checked = "true"
to :
.checked == true
Final code :
<html>
<head>
</head>
<body>
<div class="radioEmailType" id="emailClass">
<input type="radio" id="emailOpt1" name=emailType value="email_c1">
<label for="emailOpt1">class-one</label>
<input type="radio" id="emailOpt2" name=emailType value="email_c2">
<label for="emailOpt2">class-two</label>
<input type="radio" id="emailOpt3" name=emailType value="email_c3">
<label for="emailOpt3">class-three</label>
<input type="radio" id="emailOpt4" name=emailType value="email_c4">
<label for="emailOpt4">class-four</label>
</div>
<button type="button" class="gButton" onclick="generateEmail()">GENERATE EMAIL</button>
<textarea id=generatedEmail></textarea>
<script>
function generateEmail(){
if (document.getElementById('emailOpt1').checked == true) {
document.getElementById('generatedEmail').innerHTML = emailOpt1.value
}
else if (document.getElementById('emailOpt2').checked == true) {
document.getElementById('generatedEmail').innerHTML = emailOpt2.value
}
else if (document.getElementById('emailOpt3').checked == true) {
document.getElementById('generatedEmail').innerHTML = emailOpt3.value
}
else if (document.getElementById('emailOpt4').checked == true) {
document.getElementById('generatedEmail').innerHTML = emailOpt4.value
}
}
</script>
</body>
</html>

Reveal div based on checked radio/checkbox, multiple instances

I have to add the class 'revealed' to a div, once the radio button with the label 'yes' has been selected. So far I have my code set up so that I apply a 'required' class to the input that will be revealed, but I need to have a way to add the class 'revealed' to the 'reveal-if-active' div. This entire HTML structure will repeat as there will be multiple yes/no questions after this first one. So each 'reveal-if-active' div must be unique.
Here's the HTML structure that I am required to use:
<div class="form-group two-column">
<input id="a1" type="radio" name="ayesno" value="1">
<label for="a1">yes</label>
</div>
<div class="form-group two-column">
<input id="a2" type="radio" name="ayesno" value="2">
<label for="a2">no</label>
</div>
<div class="reveal-if-active">
<label for="how-many-people">If <strong>yes</strong> how many people?</label>
<input type="text" name="a-how-many-people" class="require-if-active" data-require-pair="#a1" required="">
</div>
Here's the JS I have so far:
var FormStuff = {
init: function() {
this.applyConditionalRequired();
this.bindUIActions();
},
bindUIActions: function() {
$("input[type='radio'], input[type='checkbox']").on("change", this.applyConditionalRequired);
},
applyConditionalRequired: function() {
$(".require-if-active").each(function() {
var el = $(this);
if ($(el.data("require-pair")).is(":checked")) {
el.prop("required", true);
$('[data-id=' + $('input:checked').prop('id') + ']').addClass('reveal');
} else {
el.prop("required", false);
el.removeClass("revealed");
}
});
}
};
FormStuff.init();
You may use el.closest('div.reveal-if-active'):
var FormStuff = {
init: function () {
this.applyConditionalRequired();
this.bindUIActions();
},
bindUIActions: function () {
$("input[type='radio'], input[type='checkbox']").on("change", this.applyConditionalRequired);
},
applyConditionalRequired: function () {
$(".require-if-active").each(function () {
var el = $(this);
if ($(el.data("require-pair")).is(":checked")) {
el.prop("required", true);
el.closest('div.reveal-if-active').addClass("revealed");
} else {
el.prop("required", false);
el.closest('div.reveal-if-active').removeClass("revealed");
}
});
}
};
$(function () {
FormStuff.init();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group two-column">
<input id="a1" type="radio" name="ayesno" value="1">
<label for="a1">yes</label>
</div>
<div class="form-group two-column">
<input id="a2" type="radio" name="ayesno" value="2">
<label for="a2">no</label>
</div>
<div class="reveal-if-active">
<label for="i1">If <strong>yes</strong> how many people?</label>
<input id="i1" type="text" name="a-how-many-people" class="require-if-active" data-require-pair="#a1" required="">
</div>

Categories

Resources