Jquery change function is not working? - javascript

I am trying to change css of two divs on a change in a select tag when specific value is selected so can you please take a look over my code that what am I doing wrong?
$(document).ready(function() {
$('#ads_site').change(function() {
if ($(this).val() == 'boss.az') {
$("#boss.az").css("display", "block");
}
elseif($(this).val() == 'jobsearch.az') {
$("#jobsearch.az").css("display", "block");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="process.php">
<select name="ads_site" id="ads_site">
<option value="boss.az">boss.az</option>
<option value="jobsearch.az">jobsearch.az</option>
</select>
<div id="boss.az" style="display:none;">
<center>
<h3>::Ads To Be Added::</h3>
</center>
<br>
<input type="text" class="from_page" name="from_page" placeholder="From Page No">
<input type="text" class="to_page" name="to_page" placeholder="To Page No">
</div>
<div id="jobsearch.az" style="display:none;">
<center>
<h3>::Ads To Be Added::</h3>
</center>
<br>
<input type="text" class="from_ad" name="from_page" placeholder="From Ad No">
<input type="text" class="to_ad" name="to_page" placeholder="To Ad No">
</div>
<input type="submit" name="submit" class="login login-submit" value="Submit">
</form>

There are 2 problems:
There is no elseif in JavaScript, you should use else if instead.
Since your IDs contain . you should escape them, otherwise jQuery tries to select an element that has boss ID and az class name.
$(document).ready(function () {
$('#ads_site').change(function () {
if ( this.value === 'boss.az' ) {
$("#boss\\.az").show();
// in case that you want to hide the other element
// $("#jobsearch\\.az").hide();
}
else if ( this.value === 'jobsearch.az' ) {
$("#jobsearch\\.az").show();
}
});
});

Related

dynamically add and removing div with javascript

presently stuck in situation. trying to create a form where one can dynamically add and remove div elements where necessary,so far have been a to DYNAMICALLY ADD, problem is if i try to REMOVE div,only the last created gets to delete whilst others remain(excluding the parent div)KINDLY ASSIST.
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<div id="box">
<div id='div' style="background: #99CCFF; height: 100px; width:300px" >
<p>Degree Level: <select id="dropdown">
<option value="Doctorate Degree">Doctorate Degree</option>
<option value="Masters">Masters</option>
<option value="Bachelors Degree">Bachelors Degree</option>
<option value="SSCE">SSCE</option>
</select></p>
<label for="firstname">School Name</label>
<input type="text" placeholder="Your Role"">
<label for="from">From</label>
<input type="text" id="from" name="from">
<br>
<label for="to">to</label>
<input type="text" id="to" name="to">
</div>
</div>
<div>
<button id="submit1">Add new div</button>
<input type="button" value="Remove Element"
onClick="removeElement('box','div');">
</div>
</body>
<script>
var box = document.getElementById('box'),
template = box.getElementsByTagName('div'),
template = template[0];
var counter = 1;
submit1.onclick = function () {
var new_field = template.cloneNode(true);
new_field.id = new_field.id + counter++
console.log(new_field.id)
box.appendChild(new_field);
return false;
};
</script>
<script>
function removeElement(boxDiv, divDiv){
if (divDiv == boxDiv) {
alert("The parent div cannot be removed.");
}
else if (document.getElementById(divDiv)) {
var div = document.getElementById(divDiv);
var box = document.getElementById(boxDiv);
box.removeChild(div);
}
else {
alert("Child div has already been removed or does not exist.");
return false;
}
}
You are passing the string div to your remove element function which will only remove the first div.
You can find all the children elements and then remove the last child
Building on your previous code, see the snippet below
var box = document.getElementById('box'),
template = box.getElementsByTagName('div'),
template = template[0];
console.log(template);
var counter = 1;
submit1=document.getElementById("submit1");
submit1.onclick = function () {
var new_field = template.cloneNode(true);
new_field.id = new_field.id + counter++
console.log(new_field.id)
box.appendChild(new_field);
return false;
};
function removeElement(boxDiv){
var box = document.getElementById(boxDiv);
if(box.children){
console.log(box.children);
box.children[box.children.length-1].outerHTML="";
}
}
<div id="box">
<div id='div' style="background: #99CCFF; height: 100px; width:300px" >
<p>Degree Level: <select id="dropdown">
<option value="Doctorate Degree">Doctorate Degree</option>
<option value="Masters">Masters</option>
<option value="Bachelors Degree">Bachelors Degree</option>
<option value="SSCE">SSCE</option>
</select></p>
<label for="firstname">School Name</label>
<input type="text" placeholder="Your Role"">
<label for="from">From</label>
<input type="text" id="from" name="from">
<br>
<label for="to">to</label>
<input type="text" id="to" name="to">
</div>
</div>
<div>
<button id="submit1">Add new div</button>
<input type="button" value="Remove Element"
onClick="removeElement('box');">
</div>
It might be because js thinks you're only selecting the last one when doing
var div = document.getElementById(divDiv);
Try doing a loop until document.getElementById(divDiv) is undefined

How do I enable my form's submit button using jquery?

I have a basic form with some input fields and a dropdown(select field).
Almost all fields have a form of validation. When a field has an error, an error message with the CSS class 'errorText' is displayed next to the field.
By default, my submit button is 'disabled'. I want to remove the 'disabled' attribute from my submit button once all tags with 'errorText' CSS classes are hidden/removed.
my current script just hides all tags with 'errorText' when an error occurs. how do I stop it from doing that and how can I enable my submit button once all fields have been properly enter/validated? Thanks.
EDIT: SOLVED. CODE UPDATED.
// Field Validations
$('#firstName')
.on('blur', function() {
var $this = $(this);
if ($this.val() == '') {
$('label[for="firstName"]').addClass('errorText');
$('#errorFName').show();
} else {
$('label[for="firstName"]').removeClass('errorText');
$('#errorFName').hide();
}
});
$('#lastName')
.on('blur', function() {
var $this = $(this);
if ($this.val() == '') {
$('label[for="lastName"]').addClass('errorText');
$('#errorLName').show();
} else {
$('label[for="lastName"]').removeClass('errorText');
$('#errorLName').hide();
}
});
$('#state')
.on('blur', function() {
var $this = $(this);
if ($('#state').val() == "") {
$('label[for="state"]').addClass('errorText');
$('#errorState').show();
} else {
$('label[for="state"]').removeClass('errorText');
$('#errorState').hide();
}
});
// Submit Button validation
$('input, select').on('keyup, blur', function() {
if ($('.errorText:visible').length ||
$('#firstName' || '#lastName' || '#state').val() == '' ) {
$('input[type="submit"]').prop('disabled', true);
} else if ($('#firstName').val() != '' &&
$('#lastName').val() != '' &&
$('#state').val() != '' ) {
$('input[type="submit"]').prop('disabled', false);
}
});
.errorText {
color: #c4161c;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div>
<label for="firstName" class="required">First Name</label>
</div>
<div>
<input type="text" name="firstName" id="firstName" />
</div>
<div class="errorText" id="errorFName" style="display:none;">Please enter a First Name</div>
<br />
<div>
<label for="lastName" class="required">Last Name</label>
</div>
<div>
<input type="text" name="lastName" id="lastName" />
</div>
<div class="errorText" id="errorLName" style="display:none;">Please enter a Last Name</div>
<br />
<div>
<label for="state" class="required">State</label>
</div>
<div>
<select name="state" id="state">
<option value="">Select State</option>
<option value="alabama">Alabama</option>
<option value="alaska">Alaska</option>
<option value="arizona">Arizona</option>
<option value="arkansas">Arkansas</option>
<option value="california">California</option>
<option value="etc">etc..</option>
</select>
</div>
<div class="errorText" id="errorState" style="display:none;">Please select a State</div>
<br />
<input type="submit" class="LargeButton" value="Submit Referral" disabled />
If it helps, check this update using data-attribute. We group the label,input,error in a div and handle error message. Also simplified the check valid on input and select element but can be modified.
html
<div>
<label for="firstName" class="required">First Name</label>
<input type="text" name="firstName" id="firstName" />
<span class="errorText" style="display:none;">Please enter a First Name</span>
</div>
<br />
<div>
<label for="lastName" class="required">Last Name</label>
<input type="text" name="lastName" id="lastName" />
<span class="errorText" style="display:none;">Please enter a Last Name</span>
</div>
<br />
<div>
<label for="state" class="required">State</label>
<select name="state" id="state" data-valid="">
<option value="">Select State</option>
<option value="alabama">Alabama</option>
<option value="alaska">Alaska</option>
<option value="arizona">Arizona</option>
<option value="arkansas">Arkansas</option>
<option value="california">California</option>
<option value="etc">etc..</option>
</select>
<span class="errorText" style="display:none;">Please select a State</span>
</div>
<br />
<input type="submit" id="submit" class="LargeButton" value="Submit Referral" disabled />
script
$(function() {
$('input,select')
.on('blur', function() {
var $this = $(this);
if ($this.val() == '') {
$this.data("valid", 'false');
//find the immediate span with errorText and show it
$this.next("span.errorText").show();
} else {
$this.data("valid", 'true');
$this.next("span.errorText").hide();
}
checkInputs();
});
});
function checkInputs() {
//find all the input and select items where the data attribute valid is present and make an array
var array = $('input,select').map(function() {
return $(this).data("valid");
}).get();
//if there are not empty or false indicating invalid value set submit property to true
if (array.indexOf("") == -1 && array.indexOf("false") == -1) {
$("#submit").prop("disabled", false);
} else {
$("#submit").prop("disabled", true);
}
}
css
.errorText {
color: #c4161c;
display: block;
}

Toggle sub-category divs based on radio button selection

I used the top answer to this question to build a form that feeds into a sheet along with file upload. Now I've hit another wall.
I have categories, and sub-categories. I'd like the sub-categories to only show up IF their parent category has been selected. I just can't figure out A) where I need to put the code (on our website it's right in with the HTML), I've tried putting it in the HTML file and the Code.gs file, or B) if the code I'm using is even right.
Here's the form - the "Co-Op Category" is the parent categories, I have hidden divs for each category that would hold the 'child categories'
HTML:
<script>
// Javascript function called by "submit" button handler,
// to show results.
function updateOutput(resultHtml) {
toggle_visibility('inProgress');
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = resultHtml;
}
// From blog.movalog.com/a/javascript-toggle-visibility/
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
<div id="formDiv">
<!-- Form div will be hidden after form submission -->
<form id="myForm">
Name: <input name="name" type="text" /><br/>
Co-Op Amount: <input name="amount" type="text" /><br/>
Co-Op Split:<br />
<input type="radio" name="split" value="100%">100%<br>
<input type="radio" name="split" value="50/50">50/50<br>
<input type="radio" name="split" value="75/25">75/25<br>
Other: <input type="text" name="split" /><br />
Reason for Co-Op: <input name="reason" type="text" cols="20" rows="5" /><br />
Brand:
<select name="brand">
<option>Select Option</option>
<option>Bluebird</option>
<option>Brown</option>
<option>Ferris</option>
<option>Giant Vac</option>
<option>Honda</option>
<option>Hurricane</option>
<option>Little Wonder</option>
<option>RedMax</option>
<option>SCAG</option>
<option>Snapper Pro</option>
<option>Sno-Way</option>
<option>SnowEx</option>
<option>Wright</option>
<option>Ybravo</option>
</select><br/>
Co-Op Category:<br />
<input type="radio" name="category" id="dealer" value="Dealer Advertising">Dealer Advertising<br />
<input type="radio" name="category" id="online" value="Digital/Online Marketing">Digital/Online Advertising<br />
<input type="radio" name="category" id="meetings" value="Meetings and Schools">Meetings and Schools<br />
<input type="radio" name="category" id="advertising" value="PACE Advertising">PACE Advertising<br />
<input type="radio" name="category" id="pricing" value="Program Pricing Promotions">Program Pricing Promotions<br />
<input type="radio" name="category" id="correspondence" value="PACE-to-Dealer Correspondence">PACE-to-Dealer Correspondence<br />
Other: <input type="text" id="other" name="category" /><br />
<div class="dealer box" style="display: none;">DEALER</div>
<div class="online box" style="display: none;">ONLINE</div>
<div class="meetings box" style="display: none;">MEETINGS</div>
<div class="advertising box" style="display: none;">ADVERTISING</div>
<div class="pricing box" style="display: none;">PRICING</div>
<div class="correspondence box" style="display: none;">CORRESPONDENCE</div>
Email: <input name="email" type="text" /><br/>
Message: <textarea name="message" style="margin: 2px; height: 148px; width: 354px;"></textarea><br/>
School Schedule (Image Files Only): <input name="myFile" type="file" /><br/>
<input type="button" value="Submit"
onclick="toggle_visibility('formDiv'); toggle_visibility('inProgress');
google.script.run
.withSuccessHandler(updateOutput)
.processForm(this.parentNode)" />
</form>
</div>
<div id="inProgress" style="display: none;">
<!-- Progress starts hidden, but will be shown after form submission. -->
Uploading. Please wait...
</div>
<div id="output">
<!-- Blank div will be filled with "Thanks.html" after form submission. -->
</div>
Code.gs:
var submissionSSKey = '1zzRQwgXb0EN-gkCtpMHvMTGyhqrx1idXFXmvhj4MLsk';
var folderId = "0B2bXWWj3Z_tzTnNOSFRuVFk2bnc";
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Form.html');
template.action = ScriptApp.getService().getUrl();
return template.evaluate();
}
function processForm(theForm) {
var fileBlob = theForm.myFile;
var folder = DriveApp.getFolderById(folderId);
var doc = folder.createFile(fileBlob);
// Fill in response template
var template = HtmlService.createTemplateFromFile('Thanks.html');
var name = template.name = theForm.name;
var amount = template.amount = theForm.amount;
var split = template.split = theForm.split;
var reason = template.reason = theForm.split;
var brand = template.brand = theForm.brand;
var category = template.category = theForm.category;
var message = template.message = theForm.message;
var email = template.email = theForm.email;
var fileUrl = template.fileUrl = doc.getUrl();
// Record submission in spreadsheet
var sheet = SpreadsheetApp.openById(submissionSSKey).getSheets()[0];
var lastRow = sheet.getLastRow();
var targetRange = sheet.getRange(lastRow+1, 1, 1, 9).setValues([[name,amount,split,reason,category,brand,message,email,fileUrl]]);
// Return HTML text for display in page.
return template.evaluate().getContent();
}
//Toggle Secondary Categories
function(){
$('input[type="radio"]').click(function(){
if($(this).attr("id")=="dealer"){
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if($(this).attr("id")=="online"){
$(".box").not(".online").hide();
$(".online").show();
}
if($(this).attr("id")=="advertising"){
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if($(this).attr("id")=="pricing"){
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if($(this).attr("id")=="correspondence"){
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if($(this).attr("id")=="meetings"){
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if($(this).attr("id")=="other"){
$(".box").not(".other").hide();
$(".other").show();
}
});
};
This bit specifically is where I'm having trouble:
//Toggle Secondary Categories
function(){
$('input[type="radio"]').click(function(){
if($(this).attr("id")=="dealer"){
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if($(this).attr("id")=="online"){
$(".box").not(".online").hide();
$(".online").show();
}
if($(this).attr("id")=="advertising"){
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if($(this).attr("id")=="pricing"){
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if($(this).attr("id")=="correspondence"){
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if($(this).attr("id")=="meetings"){
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if($(this).attr("id")=="other"){
$(".box").not(".other").hide();
$(".other").show();
}
});
};
The unexpected token is due to the function(){ line, which is invalid syntax for the jQuery document ready function. You should have:
$(function(){
$('input[type="radio"]').click(function(){
...
});
});
With that fixed, your next error will be:
Uncaught ReferenceError: $ is not defined
That's because you haven't included jQuery, which is what the $ symbol is referring to in statements like $(this). You'll want to read this for more tips about using jQuery in Google Apps Script. The short story, though: You need to add the following, adjusted for whatever version of jQuery you intend to use:
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
Updated Form.html, which shows the appropriate <div> as you intended. It also includes the recommended doctype, html, head and body tags:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
// Javascript function called by "submit" button handler,
// to show results.
function updateOutput(resultHtml) {
toggle_visibility('inProgress');
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = resultHtml;
}
// From blog.movalog.com/a/javascript-toggle-visibility/
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//Toggle Secondary Categories
$(function() {
$('input[type="radio"]').click(function() {
if ($(this).attr("id") == "dealer") {
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if ($(this).attr("id") == "online") {
$(".box").not(".online").hide();
$(".online").show();
}
if ($(this).attr("id") == "advertising") {
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if ($(this).attr("id") == "pricing") {
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if ($(this).attr("id") == "correspondence") {
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if ($(this).attr("id") == "meetings") {
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if ($(this).attr("id") == "other") {
$(".box").not(".other").hide();
$(".other").show();
}
});
});
</script>
<div id="formDiv">
<!-- Form div will be hidden after form submission -->
<form id="myForm">
Name:
<input name="name" type="text" /><br/>
Co-Op Amount: <input name="amount" type="text" /><br/>
Co-Op Split:<br />
<input type="radio" name="split" value="100%">100%<br>
<input type="radio" name="split" value="50/50">50/50<br>
<input type="radio" name="split" value="75/25">75/25<br> Other: <input type="text" name="split" /><br /> Reason for Co-Op: <input name="reason" type="text" cols="20" rows="5" /><br />
Brand:
<select name="brand">
<option>Select Option</option>
<option>Bluebird</option>
<option>Brown</option>
<option>Ferris</option>
<option>Giant Vac</option>
<option>Honda</option>
<option>Hurricane</option>
<option>Little Wonder</option>
<option>RedMax</option>
<option>SCAG</option>
<option>Snapper Pro</option>
<option>Sno-Way</option>
<option>SnowEx</option>
<option>Wright</option>
<option>Ybravo</option>
</select><br/>
Co-Op Category:<br />
<input type="radio" name="category" id="dealer" value="Dealer Advertising">Dealer Advertising<br />
<input type="radio" name="category" id="online" value="Digital/Online Marketing">Digital/Online Advertising<br />
<input type="radio" name="category" id="meetings" value="Meetings and Schools">Meetings and Schools<br />
<input type="radio" name="category" id="advertising" value="PACE Advertising">PACE Advertising<br />
<input type="radio" name="category" id="pricing" value="Program Pricing Promotions">Program Pricing Promotions<br />
<input type="radio" name="category" id="correspondence" value="PACE-to-Dealer Correspondence">PACE-to-Dealer Correspondence<br />
Other: <input type="text" id="other" name="category" /><br />
<div class="dealer box" style="display: none;">DEALER</div>
<div class="online box" style="display: none;">ONLINE</div>
<div class="meetings box" style="display: none;">MEETINGS</div>
<div class="advertising box" style="display: none;">ADVERTISING</div>
<div class="pricing box" style="display: none;">PRICING</div>
<div class="correspondence box" style="display: none;">CORRESPONDENCE</div>
Email: <input name="email" type="text" /><br/>
Message: <textarea name="message" style="margin: 2px; height: 148px; width: 354px;"></textarea><br/>
School Schedule (Image Files Only): <input name="myFile" type="file" /><br/>
<input type="button" value="Submit" onclick="toggle_visibility('formDiv'); toggle_visibility('inProgress');
google.script.run
.withSuccessHandler(updateOutput)
.processForm(this.parentNode)" />
</form>
</div>
<div id="inProgress" style="display: none;">
<!-- Progress starts hidden, but will be shown after form submission. -->
Uploading. Please wait...
</div>
<div id="output">
<!-- Blank div will be filled with "Thanks.html" after form submission. -->
</div>
</body>
</html>

jquery validation to check status of 3 checkboxes are all checked then enable button

I have a form with some text fields, three checkboxes and a submit button.
Currently I have the submit button disabled and it should enable only if ALL three checkboxes are checked.
I have only been able to work out how to enable it with only one checkbox being checked.
How can I make sure all three are checked before enabling the button?
End of form
<input name="list1" id="list1" type="checkbox" value="" >
<input name="list2" id="list2" type="checkbox" value="" >
<input name="list3" id="list3" type="checkbox" value="" >
<input id="pay-button" type="image" disabled="disabled" src="paypal.gif" value="" name="save">
Script
<script type="text/javascript">
$(function() {
$('#list1').click(function() {
if ($(this).is(':checked')) {
$('#pay-button').removeAttr('disabled');
} else {
$('#pay-button').attr('disabled', 'disabled');
}
});
});
</script>
Try
$(function () {
var $checks = $('#list1, #list2, #list3').change(function () {
$('#pay-button').prop('disabled', $checks.is(':not(:checked)'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input name="list1" id="list1" type="checkbox" value="" >
<input name="list2" id="list2" type="checkbox" value="" >
<input name="list3" id="list3" type="checkbox" value="" >
<input id="pay-button" type="image" disabled="disabled" src="//placehold.it/32/fff000" value="" name="save">
you can simplify the selector #list1, #list2, #list3 by adding a common class to those elements and then by using a class selector
You could try to compare the count of checked checkboxes and the total amount:
<div id="wrapper">
<input name="list1" id="list1" type="checkbox" value="" >
<input name="list2" id="list2" type="checkbox" value="" >
<input name="list3" id="list3" type="checkbox" value="" >
</div>
<input id="pay-button" type="image" disabled="disabled" src="paypal.gif" value="" name="save">
Script
<script type="text/javascript">
$(function() {
$('#wrapper').on('click', 'input[type="checkbox"]', function() {
if ($('#wrapper').find(':checked').size() === $('#wrapper').find(':checkbox').size()) {
$('#pay-button').removeAttr('disabled');
} else {
$('#pay-button').attr('disabled', 'disabled');
}
});
});
</script>
edit code like below and try again:
HTML :
<input class="chck" name="list1" id="list1" type="checkbox" value="" >
<input class="chck" name="list2" id="list2" type="checkbox" value="" >
<input class="chck" name="list3" id="list3" type="checkbox" value="" >
<input id="pay-button" type="image" disabled="disabled" src="paypal.gif" value="" name="save">
JS :
<script type="text/javascript">
$(function() {
$('.chck').click(function() {
var isAllChecked = true;
for(var i = 0; i < $('.chck').length; i++)
{
if(!$('.chck')[i].is(':checked'))
isAllChecked = false;
}
if (isAllChecked) {
$('#pay-button').removeAttr('disabled');
} else {
$('#pay-button').attr('disabled', 'disabled');
}
});
});
</script>
Add a class name to your checkboxes i.e .checkboxes
$(".checkboxes").click(function () {
var blnEnableBtn = false;
var count = 0;
$('input:checked').each(function (index, element) {
count++;
});
if (count == 3)
$("#pay-button").removeAttr('disabled');
else
$("#pay-button").attr('disabled', 'disabled');
});
Hope it helps .

javascript conditional logic not working

When I try to run the code below, and step into it in the browser debugger, the length it's showing me is 1 or higher, yet it still drops into this block as if it were evaluated as true...am I missing something here?
function checkEmpty() {
var empty = false;
$('form input:text').each(function () {
console.log($(this).val())
if ($(this).val().length === 0) {
empty = true;
}
});
if (empty) {
$('#btnContinueCheckout1').attr('disabled', 'disabled');
$('#btnContinueCheckout2').attr('disabled', 'disabled');
} else {
$('#btnContinueCheckout1').removeAttr('disabled');
$('#btnContinueCheckout2').removeAttr('disabled');
}
}
HTML: (these are the input fields, and they are wrapped around a form, and have 2 checkout buttons that are not shown)
<br />
<br />
<label><strong>Full Name: </strong></label>
<input type="text" required="required" onkeyup="checkEmpty()" name="FullName" style="width: 235px;" /><br />
<br />
<label><strong>Mailing Address: </strong></label>
<input type="text" required="required" name="Address" onkeyup="checkEmpty()" style="width: 235px;" /><br />
<br />
<label><strong>Email: </strong></label>
<input type="text" required="required" style="width: 235px;" name="Email" onkeyup="checkEmpty()" /><br />
<br />
<label><strong>Phone Number: </strong></label>
<input type="text" required="required" name="Phone" onkeyup="checkEmpty()" />
Try this example code in a blank html page with jQuery linked:
<html>
<head>
<title>Example</title>
<script type="text/javascript" src="jquery.min.js"></script>
</head>
<body>
<form>
<label><strong>Full Name: </strong></label>
<input type="text" required="required" onkeyup="checkEmpty()" name="FullName" style="width: 235px;" /><br />
<br />
<label><strong>Mailing Address: </strong></label>
<input type="text" required="required" name="Address" onkeyup="checkEmpty()" style="width: 235px;" /><br />
<br />
<label><strong>Email: </strong></label>
<input type="text" required="required" style="width: 235px;" name="Email" onkeyup="checkEmpty()" /><br />
<br />
<label><strong>Phone Number: </strong></label>
<input type="text" required="required" name="Phone" onkeyup="checkEmpty()" />
<input type="button" id="checkbutton" value="deactivated" disabled/>
</form>
</body>
<script type="text/javascript">
function checkEmpty() {
var empty = false;
$('form input:text').each(function () {
console.log($(this).val());
if ($(this).val().length === 0) {
empty = true;
}
});
if (empty) {
$('#checkbutton').prop('disabled', 'disabled');
} else {
$('#checkbutton').prop('disabled', '');
}
console.log('count of textfields: ' + $('form input:text').length);
}
</script>
</html>
It works 100% for me. Look at the console to check the count for the textfields. If it's more then you expect, check your html if you have missed one. If all fields are filled, the button will be activated.
The problem is that you're assigning empty=true; when you read one input field, but then the loop will keep going and check further input fields. This means that if the first field is empty, but the second one isn't empty, your loop will not work. Try to break out of the .each() loop as soon as you find the first empty input.
function checkEmpty() {
var empty = false;
$('form input:text').each(function () {
console.log($(this).val()); // Also, you forgot the ; here
if ($(this).val().length === 0) {
empty = true;
return false; // Will break out of the .each() loop
}
});
if (empty) {
$('#btnContinueCheckout1').attr('disabled', 'disabled');
$('#btnContinueCheckout2').attr('disabled', 'disabled');
} else {
$('#btnContinueCheckout1').removeAttr('disabled');
$('#btnContinueCheckout2').removeAttr('disabled');
}
}

Categories

Resources