Select Option Doesn't Set on Button Click with jQuery - javascript

I've tried following a couple of answers with no success. I am trying to get the select box to go back to the "Please Select One Option" when the Add Exercise button is clicked. I got it to work in a simple scenario like this:
<div id="retro_add_exercises">
<div class="row">
<div class="input-field col s12">
<div class="select-wrapper initialized">
<select class="initialized" id="exercise_category">
<option value="0" disabled="" selected="">Please Select One</option>
<option value="1">Cardio</option>
<option value="2">Weight Lifting</option>
<option value="3">Stretching</option>
</select>
</div>
</div>
</div>
<!-- CARDIO SELECT FIELD -->
<div class="row" id="select_cardio">
<form method="POST" id="cardio_form">
<div class="input-field col s12">
<button class="btn waves-effect waves-light" id="add_exercise_from_cardio" type="submit" name="action" value="ADD">Add Exercise from cardio</button>
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#add_exercise_from_cardio').click(function() {
$('#exercise_category').val('0').change();
});
});
</script>
But in my main project, it isn't working when I have the row show and hide on button click too. Any help would be appreciated.
$(document).ready(function() {
$('#retroactive_date_form').submit(function(e) {
e.preventDefault();
var date = $('#retroactive_date_picker');
var exercise_date = date.val();
if (exercise_date !== '') {
var exercise_category;
var weight_set_type;
console.log(exercise_date);
date.prop('disabled', true);
$('#retroactive_date_submit').addClass('disabled');
$('#retro_add_exercises').show();
//Exercise Category Function
$('#exercise_category').on('change', function() {
exercise_category = $('#exercise_category').val();
console.log(exercise_category);
if (this.value === '1')
{
$('#select_cardio').show();
$('#drop_or_reg_set_select_exercise').hide();
$('#super_set_select_exercises').hide();
$('#drop_and_regular_set_action_btn').hide();
$('#super_set_action_btn').hide();
$('#super_set_table_row').hide();
$('#drop_or_reg_set_table_row').hide();
}
else
$('#select_cardio').hide();
if (this.value === '2')
{
$('#select_weight').show()
}
else
$('#select_weight').hide();
if (this.value === '3')
{
$('#select_stretch_fields').show();
$('#select_cardio').hide();
$('#drop_or_reg_set_select_exercise').hide();
$('#super_set_select_exercises').hide();
$('#drop_and_regular_set_action_btn').hide();
$('#super_set_action_btn').hide();
$('#super_set_table_row').hide();
$('#select_weight').hide();
$('#drop_or_reg_set_table_row').hide();
}
else
$('#select_stretch_fields').hide();
return exercise_category;
});
///////////Cardio Training Functions///////////////
//Selecting Cardio Exercise
$('#cardio_exercise').on('change', function (e) {
var cardio_exercise;
cardio_exercise = $('#cardio_exercise').val();
console.log(cardio_exercise);
});
//Adding Another Exercise After Done Adding Current Cardio Exercise
$('#add_exercise_from_cardio').on('click', function(e) {
e.preventDefault();
$('#exercise_category option[value="0"]').attr('selected', true);
$('#select_cardio').hide();
$('#drop_or_reg_set_select_exercise').hide();
$('#super_set_select_exercises').hide();
$('#drop_and_regular_set_action_btn').hide();
$('#super_set_action_btn').hide();
$('#super_set_table_row').hide();
$('#drop_or_reg_set_table_row').hide();
});
//Error Handling If No Date is Selected Before Starting
else {
alert('Please select date')
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="retro_add_exercises" style="display:none">
<div class="row">
<div class="input-field col s12">
<div class="select-wrapper initialized"><span class="caret">▼</span>
<select class="initialized" id="exercise_category">
<option value="0" disabled="" selected="">Please Select One</option>
<option value="1">Cardio</option>
<option value="2">Weight Lifting</option>
<option value="3">Stretching</option>
</select>
</div>
<label>Choose Exercise Type</label>
</div>
</div>
<!-- CARDIO SELECT FIELD -->
<div class="row" style="display:none" id="select_cardio">
<form method="POST" id="cardio_form">
<div class="input-field col s12">
<div class="select-wrapper initialized"><span class="caret">▼</span>
<select id="cardio_exercise" name="cardio_exercise" class="initialized">
<option value="0" disabled selected>Choose Cardio Exercise</option>
<option value="1">Jumping Jacks</option>
<option value="2">Jump Rope</option>
<option value="3">Precor</option>
<option value="4">Running (outside)</option>
<option value="5">Swimming</option>
<option value="6">Treadmill</option>
</select>
</div>
<input type="date" style="display:none" id="cardio_exercise_date" name="cardio_exercise_date">
<input placeholder="Duration (minutes)" name="cardio_duration" id="cardio_duration" type="number" class="validate">
<input placeholder="Distance (optional)" name="cardio_distance" id="cardio_distance" type="number" class="validate">
<button class="btn waves-effect waves-light" id="add_exercise_from_cardio" type="submit" name="action" value="ADD">Add Exercise</button>
<button class="btn waves-effect waves-light" id="finish_tracking" type="submit" name="action" value="FINISH">Finish Workout</button>
<label for="cardio_exercise">Choose Exercise</label>
</div>
</form>
</div>

The jQuery documentation dictates that since jQuery 1.6, attr will not update the dynamic state of a DOM element. In addition, it appears your select is disabled after being selected. Try:
$('#exercise_category option[value="0"]').prop('disabled', false);
$('#exercise_category option[value="0"]').prop('selected', true);

There is probably a better and more efficient way to solve it, but I figured it out. I wrapped the select option in form wrappers and gave the form an ID. Then on the button click I triggered reset of the form using
$('#button_id').on('click', function(e) {
e.preventDefault();
$('#form_id').trigger('reset');
});
Although I'm sure there is a better way, this method worked for me and hopefully it works for someone else too.

Related

Issue hiding fields on multiple rendered form

I am trying to render a form for each person that I get based on a specific input from the database.
#forelse($driverNames as $driver)
<form id="inspection_report_form" enctype="multipart/form-data" action="/inspection-report/store" method="POST">
#csrf
I am trying to hide some fileds if no is selected from dropdown.
<div class="row">
<div class="col-lg-2">
<div class="form-group">
<label>Equipment</label>
<div class="input-group mb-3">
<select class="custom-select" id="branded_equipment" name="branded_equipment" required>
<option value="">Select</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
</div>
</div>
<script>
let branded_equipment = document.getElementById('branded_equipment');
branded_equipment.addEventListener('change', function () {
if (branded_equipment.value === 'no') {
document.getElementById('branded_equipment_picture').required = false;
document.getElementById('branded_equipment_picture').disabled = true;
document.getElementById('branded_equipment_picture').style.display = 'none';
document.getElementById('branded_equipment_picture_label').style.display = 'none';
} else {
document.getElementById('branded_equipment_picture').required = true;
document.getElementById('branded_equipment_picture').disabled = false;
document.getElementById('branded_equipment_picture').style.display = 'block';
document.getElementById('branded_equipment_picture_label').style.display = 'block';
}
});
</script>
The problem that I am facing is that it works only for the first form in the list , if i am clicking on the next person form on the same dropdown id does nothing.
Same with the spinner
>! html
<div class="float-right">
{{--loader--}}
<button class="btn btn-primary" type="button" style="display: none" disabled id="spinner">
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
Loading ...
</button>
<button class="btn btn-success" id="report_submit_btn">Save</button>
</div>
>! javascript
let report_submit_btn = document.getElementById('report_submit_btn');
report_submit_btn.addEventListener('click', function () {
report_submit_btn.style.display = 'none';
document.getElementById('spinner').style.display = 'block';
});
I am assuming that because of the form is generated multiple times and the dropdown is having the same id for each iteration it does not know how to make the difference after the first form.
Much appreciated if anyone can help.
I have tryied using multiple selectors or techniques but nothing works. I am wondering if is achievable what I am trying to do or I should try something different.

change jquery step validation-wizard finish button into a submit button

i am using jquery-steps, i would like to change the finish button from a
to a proper submit button. Where do i change that.
i have tried doing it this way, but the css is then getting broken.
<form action="admin/practitioners" class="validation-wizard wizard-circle">
{{csrf_field()}}
<!-- Step 1 -->
<h6>Step 1</h6>
<hr/>
<section>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="wlocation2"> Title : <span
class="danger">*</span>
</label>
<select class="custom-select form-control required"
id="wlocation2" name="title_id">
<option value="">Select Title</option>
#foreach($titles as $title)
<option value="{{$title->id}}">{{$title->name}}
</option>
#endforeach
</select>
</div>
</div>
</div>
</section>
here is my jquery
<script>
$('.validation-wizard').steps({
headerTag: "h6",
bodyTag: "section",
transitionEffect: "slideLeft",
enableFinishButton: !1,
onStepChanged: function (event, currentIndex, priorIndex) {
if (currentIndex == 3) {
var $input = $('<input type="submit" class="btn btn-success btn-lg" value="Submit Data"/>');
$input.appendTo($('ul[aria-label=Pagination]'));
} else {
$('ul[aria-label=Pagination] input[value="Submit"]').remove();
}
}
});
</script>
I expect that when i get to the last step it display a submit button on finish not a link. Right now its still displaying the finish button with broken css

JavaScript form onchange getting Nan

I am calling onchange event on form but when I checked in console values are coming in Nan
HTML
<form onchange="calculateHSA(event)">
<div class="col-sm-4">
<input type="number" name="claim-amnt" id="claim-amnt" required="">
</div>
<div class="col-sm-4">
<input type="number" name="admin-percent" id="admin-percent" required="">
</div>
<div class="col-sm-4">
<span class="dataText">Select your province
</span><br>
<select name="province" id="province">
<option value="abc">ABC</option>
</select>
</div>
</form>
JavaScript
function calculateHSA(e) {
e.preventDefault();
const claimAmount = parseInt($(e.target).find('#claim-amnt').val());
console.log(claimAmount);
const adminPercent = parseInt($(e.target).find('#admin-percent').val());
console.log(adminPercent);
const province = $(e.target).find('#province').val();
console.log(province);
displayTaxDetails(claimAmount, adminPercent, province);
}
Where I did wrong code?
Please use e.currentTarget instead of e.target because e.target can be your text fields but e.currentTarget will always be your form. This code is working fine.
<form onchange="calculateHSA(event)">
<div class="col-sm-4">
<input type="number" name="claim-amnt" id="claim-amnt" required="">
</div>
<div class="col-sm-4">
<input type="number" name="admin-percent" id="admin-percent" required="">
</div>
<div class="col-sm-4">
<span class="dataText">Select your province
</span><br>
<select name="province" id="province">
<option value="abc">ABC</option>
</select>
</div>
</form>
<script>
function calculateHSA(e) {
e.preventDefault();
const claimAmount = parseInt($(e.currentTarget).find('#claim-amnt').val());
console.log(claimAmount);
const adminPercent = parseInt($(e.currentTarget).find('#admin-percent').val());
console.log(adminPercent);
const province = $(e.currentTarget).find('#province').val();
console.log(province);
displayTaxDetails(claimAmount, adminPercent, province);
}
</script>
There's no need to use e.target in your example. You can just access the values from the selectors directly:
function calculateHSA(e) {
e.preventDefault();
const claimAmount = parseInt($('#claim-amnt').val());
console.log(claimAmount);
const adminPercent = parseInt($('#admin-percent').val());
console.log(adminPercent);
const province = parseInt($('#province').val());
console.log(province);
displayTaxDetails(claimAmount, adminPercent, province);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onchange="calculateHSA(event)">
<div class="col-sm-4">
<input type="number" name="claim-amnt" id="claim-amnt" required="">
</div>
<div class="col-sm-4">
<input type="number" name="admin-percent" id="admin-percent" required="">
</div>
<div class="col-sm-4">
<span class="dataText">Select your province
</span><br>
<select name="province" id="province">
<option value="abc">ABC</option>
</select>
</div>
</form>
Note that you will get NaN in the console for any field that doesn't have a value that can be parsed as an integer. So if you leave the field blank, you're still going to get NaN in the console.
You are getting NaN because your target element is pointing to the input tag instead of form element
I have made some changes in the function and added new line in the code
function calculateHSA(e) {
e.preventDefault();
var form = $(e.target).parent().parent(); // <-- get the form element
const claimAmount = form.find('#claim-amnt').val();
console.log(claimAmount);
const adminPercent = form.find('#admin-percent').val();
console.log(adminPercent);
const province = form.find('#province').val();
console.log(province);
displayTaxDetails(claimAmount, adminPercent, province);
}
have a look at this plunker https://plnkr.co/edit/BQ538zbYBk857zT1wAgT

Bootstrap website payments with Stripe

I'm completely new to using Stripe for payments, and as it's a Bootstrap site & I'm using Stripe.js v2.
From my understanding of how Stripe works, my HTML form needs to initially communicate with Stripe with the credit card num, cvc & expirary using Javascript, which will return a token (or an error) - and I then submit this token, and other payment information like the amount etc.. to the PHP script on my Server (which then sends this Stripe).
My problem is, my JavaScript is never executed first - and instead my page tries to run submit.php first.
What should I do to correct this - and have my JavaScript create the token, and then have the token passed to my submit.php code?
*Note - my HTML form does contain more than what's listed here (such as asking the user for Name, Address, State, Phone, Amount etc), but i shortened it, so it was easier to read.
HTML Code:
<form action="/PHP/submit.php" method="POST" class="contact-form" id="payment-form">
<div id="creditcard">
<span class="payment-errors"></span>
<div class="form-group has-feedback row">
<label for="cardnumber" class="col-sm-2 form-control-sm">Card Number:</label>
<div class="col-sm-5">
<!--<input type="text" autocomplete="off" class="form-control form-control-sm card-number" value="" pattern="[0-9]{10}" data-stripe="number">-->
<input type="text" autocomplete="off" class="form-control form-control-sm card-number" data-stripe="number">
</div>
<label for="cvc" class="col-sm-1 form-control-sm">CVC:</label>
<div class="col-sm-4">
<!--<input type="text" autocomplete="off" class="form-control form-control-sm card-cvc" maxlength="3" value="" pattern="[0-9]{3}" data-stripe="cvc">-->
<input type="text" autocomplete="off" class="form-control form-control-sm card-cvc" data-stripe="cvc">
</div>
</div>
<div class="form-group has-feedback row">
<label for="expiration" class="col-sm-2 form-control-sm">Expiration Date </label>
<div class="col-sm-2">
<select class="card-expiry-month form-control form-control-sm" data-stripe="exp-month">
<option value="01" selected>01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
</div>
<div class="col-sm-2">
<select class="card-expiry-year form-control form-control-sm" data-stripe="exp-year">
<option value="2018" selected>2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
<option value="2022">2022</option>
<option value="2023">2023</option>
<option value="2024">2024</option>
<option value="2025">2025</option>
</select>
</div>
</div>
<div class="form-group row">
<label for="cardname" class="col-sm-2 form-control-sm">Name on Card:</label>
<div class="col-sm-10">
<input type="text" class="form-control form-control-sm" autocomplete="off" name="cardname" id="cardname">
</div>
</div>
<div class="form-row form-submit">
<button type="submit" class="btn btn-default submit-button">Submit Donation</button>
</div>
</div>
</form>
And my Javascript:
<script src="https://js.stripe.com/v2/"></script>
<script>
(function() {
Stripe.setPublishableKey('pk_test_xxxxx');
})();
</script>
<script>
$(document).ready(function() {
$('#payment-form').on('submit', generateToken);
var generateToken = function(e) {
var form = $(this);
//No pressing the buy now button more than Once
form.find('button').prop('disabled', true);
//Create the token, based on the form object
Stripe.create(form, stripeResponseHandler);
//Prevent the form from submitting
e.preventDefault();
});
});
var stripeResponseHandler = function(status, response) {
var form = $('#payment-form');
//Any validation errors?
if (response.error) {
form.find('.payment-errors').text(response.error.message);
alert(result.error.message);
//Make the submit button clickable again
form.find('button').prop('disabled', false);
} else {
//Otherwise, we're good to go! Submit the form.
//Insert the unique token into the form
$('<input>', {
'type': 'hidden',
'name': 'stripeToken',
'value': response.id
}).appendTo(form);
alert(result.token.id);
//Call tge native submit method on the form
//to keep the submission from being cancelled
form.get(0).submit();
}
};
</script>
You should define the generateToken function before the $('#payment-form').on('submit', generateToken);. Otherwise the submit event has no handler, and e.preventDefault(); is never reached.
$(document).ready(function() {
$('#payment-form').on('submit', generateToken);
var generateToken = function(e) {
var form = $(this);
//No pressing the buy now button more than Once
form.find('button').prop('disabled', true);
//Create the token, based on the form object
Stripe.create(form, stripeResponseHandler);
//Prevent the form from submitting
e.preventDefault();
});
});
Demo: https://www.codeply.com/go/wRcqjxfVmf
I ended up going a slightly different direction, using an 'onsubmit' event on the form, to trigger the javascript before the PHP;
<form action="/PHP/submit.php" method="POST" class="contact-form" id="payment-form" onsubmit="return onSubmitDo()">
I also completely changed the Javascript so it looked like this:
Stripe.setPublishableKey('pk_test_******');
function onSubmitDo () {
Stripe.card.createToken( document.getElementById('payment-form'), myStripeResponseHandler );
return false;
};
function myStripeResponseHandler ( status, response ) {
console.log( status );
console.log( response );
if ( response.error ) {
document.getElementById('payment-error').innerHTML = response.error.message;
} else {
var tokenInput = document.createElement("input");
tokenInput.type = "hidden";
tokenInput.name = "stripeToken";
tokenInput.value = response.id;
var paymentForm = document.getElementById('payment-form');
paymentForm.appendChild(tokenInput);
paymentForm.submit();
}
};
The actual javascript code I used here, i found on this github account which has some Stripe payment samples;
https://github.com/wsmoak/stripe/blob/master/php/test-custom-form.html
Now the form just needs to integrate jquery.payment (to format & validate card details), and it should all be complete.
https://github.com/stripe/jquery.payment

How to only validate a form when toggled

I have a form with bootstrap toggles for each day of the week. When toggled "yes", a div with two select boxes appears. When toggled "no", the div disappears. This is functioning perfectly, but I want to use JavaScript to validate the form.
However, if one or more of the days are toggled "no", I don't want to validate that section of the form.
$('#mycheckbox').change(function() {
$('#mycheckboxdiv').toggle("fast");
});
I have tried multiple suggestions from online mostly using :visible, but I still cant get it to work.
I'm still new to JavaScript.
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<input name="everyday" name="mycheckbox" id="mycheckbox" type="checkbox" data-toggle="toggle" data-on="Yes" data-off="No" data-onstyle="success" data-offstyle="danger" value="0">
<div id="mycheckboxdiv" style="display:none">
<select class="btn btn-default" name="ed_from" id="ed_from" method="post">
<option disabled selected>From</option>
<?php for($i = 1; $i < 25; $i++): ?>
<option value="<?= $i; ?>"><?= $i % 12 ? $i % 12 : 12 ?>:00 <?= $i >= 12 ? 'pm' : 'am' ?></option>
<?php endfor ?>
</select>
<select class="btn btn-default" name="ed_to" method="post">
<option disabled selected>Until</option>
<?php for($i = 1; $i < 25; $i++): ?>
<option value="<?= $i; ?>"><?= $i % 12 ? $i % 12 : 12 ?>:00 <?= $i >= 12 ? 'pm' : 'am' ?></option>
<?php endfor ?>
</select>
<div><label class=" err2 err" id="ed_from_error">Please select your availability</label></div>
<br><br>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary btn-lg btn-block" id="submit" method="post" value="next">
</div>
There are many errors in the HTML. method="post" attribute not available for select DOM. Use <form method="POST"></form> element to submit your data. Here is the example but I not used the <form> tag.
HTML Code
<input name="everyday" id="mycheckbox" type="checkbox" value="1" >
<div id="mycheckboxdiv" style="display:none">
<select class="btn btn-default" name="ed_from" id="ed_from">
<option disabled selected value="">From</option>
<option value="1">1:00 AM</option>
</select>
<select class="btn btn-default" name="ed_to" id="ed_to">
<option disabled selected value="">Until</option>
<option value="1">1:00 AM</option>
</select>
<div><label class=" err2 err" id="ed_from_error">Please select your availability</label></div>
<br><br>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary btn-lg btn-block" id="submit" method="post" value="next">
</div>
jQuery Code
$('#mycheckbox').change(function() {
$('#mycheckboxdiv').toggle("fast");
});
$('#submit').click(function() {
if($('#mycheckbox').val()){
if($('#ed_from option:selected').val() == '' || $('#ed_to option:selected').val() == ''){
$('#ed_from_error').show();
}else
$('#ed_from_error').hide();
}
});
https://fiddle.jshell.net/LLayz0k3/
If you want to try with <form> tag
$( "#target" ).submit(function( event ) {
event.preventDefault();
// Add your validation here
....
....
});
You might try to use one of the solutions for checking for visibility from this question.
This is only if you are doing manual validation of some kind. If you are using some library you will need to provide more specifics if you need more help on how to unregister the validation when your submit is pressed.
Edit: More closely match posted snippet.
// unhide if checkbox is checked on page load (probably not needed)
if ($("#mycheckbox")[0].checked) {
$("#mycheckboxdiv").show("fast")
}
// toggle when checkbox changes
$("#mycheckbox").change(function() {
$("#mycheckboxdiv").toggle("fast");
});
// validation
$("#submit").click(function() {
if ($("#mycheckboxdiv").is(":visible")) { // jquery
//if ($("#mycheckboxdiv")[0].offsetParent != null) { // non jquery
// do validation here
if ($("#ed_to").val() == null || $("#ed_from").val() == null) {
$("#ed_from_error_1").show("fast");
return false;
} else {
$("#ed_from_error_1").hide("fast");
}
if ($("#ed_to").val() <= $("#ed_from").val()) {
$("#ed_from_error_2").show("fast");
return false;
} else {
$("#ed_from_error_2").hide("fast");
}
}
// alter just for snippet
alert("All good");
return true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<input name="everyday" name="mycheckbox" id="mycheckbox" type="checkbox" data-toggle="toggle" data-on="Yes" data-off="No" data-onstyle="success" data-offstyle="danger" value="0">
<div id="mycheckboxdiv" style="display:none">
<select class="btn btn-default" name="ed_from" id="ed_from" method="post">
<option disabled selected>From</option>
<option value="1">01:00</option>
<option value="2">02:00</option>
<option value="3">03:00</option>
<option value="4">04:00</option>
</select>
<select class="btn btn-default" name="ed_to" id="ed_to" method="post">
<option disabled selected>Until</option>
<option value="1">01:00</option>
<option value="2">02:00</option>
<option value="3">03:00</option>
<option value="4">04:00</option>
</select>
<div>
<label class="err2 err" id="ed_from_error_1" style="display:none">Please select your availability</label>
<label class="err2 err" id="ed_from_error_2" style="display:none">Until must be later than from</label>
</div>
<br><br>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary btn-lg btn-block" id="submit" method="post" value="next">
</div>
Ok after plenty of research I've figured out what I was missing. A lot of the different JavaScript I was trying out was actually perfectly valid and would have worked fine however I discovered the underlying issue was actually with not initializing the bootstrap toggle before running any other JavaScript.
$('#mycheckbox').bootstrapToggle('off');
http://www.bootstraptoggle.com/
I now have a code that displays the selects and validates them when toggle is on, or hides and does not validate them when the toggle is off.
//initialize bootstrap.
$('#mycheckbox').bootstrapToggle('off');
//Show/Hide div when toggled.
$('#mycheckbox').change(function() {
$('#mycheckboxdiv').toggle("fast");
});
$(function availability(){
$('.err').hide();
$("#submit").click(function() {
//If toggle is checked:
if ($('#mycheckbox').prop("checked")){
//validate.
var ed_from = $("#ed_from").val();
if (ed_from == null) {
$("label#ed_from_error").show();
$("#ed_from").focus();
document.getElementById('ed_from').style.borderColor = "red";
return false;
}else{
if (ed_from != null) {
document.getElementById('ed_from').style.borderColor = "green";
}
}
}
});
});

Categories

Resources