javascript conditional logic not working - javascript

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');
}
}

Related

Set a focus on input field after alert in JavaScript error

I want to set focus on a specific input field using JavaScript function.
Here is the coding:
function checknag() {
var x1 = document.getElementById('tsumnag').value;
var x2 = document.getElementById('salenugsum').value;
if (+x1 == +x2) {
// here the button key 'hey' will be used as the text.
$('#munshi_perc').focus();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input required class="urdu" onfocusout='checknag();' value="" type="text" />
<input required class="urdu" id="tsumnag" value="" type="text" />
<input required class="urdu" id="salenugsum" value="" type="text" />
<input required class="urdu" id="munshi_perc" value="" type="text" />
It just focuses, but I need alert and then focus on the input field.
Update
The code below does not work:
function checknag() {
var x1 = document.getElementById('tsumnag').value;
var x2 = document.getElementById('salenugsum').value;
if (+x1 == +x2) {
$.alert({
title: 'Alert!',
content: 'Please enter item name',
onDestroy: function() {
// here the button key 'hey' will be used as the text.
$('#munshi_perc').focus();
}
});
return false;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input required class="urdu" onfocusout='checknag();' value="" type="text" />
<input required class="urdu" id="tsumnag" value="" type="text" />
<input required class="urdu" id="salenugsum" value="" type="text" />
<input required class="urdu" id="munshi_perc" value="" type="text" />
From comments below your question:
no im not using any plugin
So that is the problem. I guess you just pasted some code from somewhere and did not look at the dependencies.
Your code works if the jQuery-Confirm plugin is loaded. So just add the CDNs used in the below snippet.
function checknag() {
var x1 = document.getElementById('tsumnag').value;
var x2 = document.getElementById('salenugsum').value;
if (+x1 == +x2) {
$.alert({
title: 'Alert!',
content: 'Please enter item name',
onDestroy: function() {
// here the button key 'hey' will be used as the text.
$('#munshi_perc').focus();
}
});
return false;
}
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.4/jquery-confirm.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.4/jquery-confirm.min.js"></script>
<input required class="urdu" onfocusout='checknag();' value="" type="text" />
<input required class="urdu" id="tsumnag" value="" type="text" />
<input required class="urdu" id="salenugsum" value="" type="text" />
<input required class="urdu" id="munshi_perc" value="" type="text" />

How to make user redirect only if you type in correct word <input>

I am making a website that has 3 inputs. Each input, i want a user to be redirected ONLY if they type in the correct word for all 3 inputs. If the user submits with none correct, do nothing. This is a similar post to my last one, but it only had 1 input which was very easy. I am not a master at this so any feedback or solutions would be great.
var slim = document.getElementById("slim");
var shady = document.getElementById("shady");
var standup = document.getElementById("standup");
function tree1() {
slim.value === "slim";
}
function tree2() {
shady.value === "shady";
}
function tree3() {
standup.value === "stand up";
}
if (tree1() + tree2() + tree3() === true) {
window.location = "https://example.com";
}
<form action="/eyerepeat" method="get">
<label for="fname">First name:</label>
<input type="text" id="slim" /><br /><br />
<label for="lname">Last name:</label>
<input type="text" id="shady" /><br /><br />
<label for="action">Action:</label>
<input type="text" id="standup" /><br /><br />
<input id="submit" type="submit" value="Submit" />
</form>
You have to attach event listener on form submit button, inside the event callback check for the values directly without using functions (its not needed in your context), note that using + sign is wrong inside the if statement you just use logical operator &&:
document.getElementById('redirect_form').addEventListener('submit', function(e) {
e.preventDefault();
var slim = document.getElementById("slim");
var shady = document.getElementById("shady");
var standup = document.getElementById("standup");
if ( standup.value === "stand up" &&
shady.value === "shady" &&
slim.value === "slim"
) {
console.log('All equal');
}
else {
console.log('Not All equal');
}
setTimeout(function(){
window.location = "https://example.com";
}, 1000)
})
<form id="redirect_form" action="/eyerepeat" method="get">
<label for="fname">First name:</label>
<input type="text" id="slim" /><br /><br />
<label for="lname">Last name:</label>
<input type="text" id="shady" /><br /><br />
<label for="action">Action:</label>
<input type="text" id="standup" /><br /><br />
<input id="submit" type="submit" value="Submit" />
</form>
Your functions need to return a value:
function tree1() {
return slim.value === "slim";
}
function tree2() {
return shady.value === "shady";
}
function tree3() {
return standup.value === "stand up";
}
To determine whether all three are true, use &&, not +:
if (tree1() && tree2() && tree3() ) {
window.location = "https://example.com";
}

Need to correct this form validation

I've this small form in which the 1st field(title) is required by default. The 2nd and the 3rd are required only in a specific condition.
Case-I: If tool name is filled out, both tool name & tool URL become required.
Case-II: If tool URL is filled out, both tool name & tool URL become required.
I'm not sure it is working as expected.
Could you please help me correct my code?
$(document).ready(function(){
articleTitle = $('#title').val();
toolName = $('#toolName').val().trim();
toolURL = $('#toolURL').val();
if(((toolName.length>0)&&(toolURL==="")) || ((toolName.length<=0)&&(toolURL!==""))){
$('#toolName').prop('required', true);
$('#toolURL').prop('required' , true);
} else {
$('#toolName').prop('required', false);
$('#toolURL').prop('required', false);
}
$("#myForm").submit(function(){
sayHello();
return false;
});
});
label {
float: left;
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<form id="myForm">
<label for="title">Title:</label> <input type="text" id="title" required> <br /><br />
<label for="toolName">Tool Name: </label><input type="text" id="toolName"> <br /> <br />
<label for="toolURL">Tool URL: </label><input type="url" id="toolURL"> <br /> <br />
<button>Submit</button>
</form>
You can simplify your code quite a bit, please see the comments for a description.
var $toolName = $('#toolName')
var $toolURL = $('#toolURL')
var $toolInputs = $($toolName).add($toolURL)
function sayHelloToMyLittleFriend() {
alert('sup! form was submitted')
}
$toolInputs.on('change', function(e) {
var toolName = $toolName.val()
var toolURL = $toolURL.val()
$toolInputs.prop('required', toolName || toolURL)
})
$('form').submit(function(e) {
var toolName = $toolName.val()
var toolURL = $toolURL.val()
var bothFilled = !!toolName && !!toolURL
var noneFilled = !toolName && !toolURL
if (bothFilled || noneFilled) {
sayHelloToMyLittleFriend()
return true
}
return false
})
label {
float: left;
width: 100px;
}
/* this will show what element has the required attribute */
[required] {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<form id="myForm">
<label for="title">Title:</label> <input type="text" id="title" required> <br /><br />
<label for="toolName">Tool Name: </label><input type="text" id="toolName"> <br /> <br />
<label for="toolURL">Tool URL: </label><input type="url" id="toolURL"> <br /> <br />
<button>Submit</button>
</form>
Here is a straightforward approach using library-less javascript (rather than jQuery).
(Albeit, you'll see that it's very similar to the jQuery).
Whenever data is entered into or removed from the form, the form inputs are checked and, as appropriate, the required attributes are added or removed.
var myForm = document.getElementById('myForm');
var toolName = document.getElementById('toolName');
var toolURL = document.getElementById('toolURL');
function checkInputs() {
if ((toolName.value !== '') || (toolURL.value !== '')) {
toolName.setAttribute('required','required');
toolURL.setAttribute('required','required');
}
if ((toolName.value === '') && (toolURL.value === '')) {
toolName.removeAttribute('required');
toolURL.removeAttribute('required');
}
}
myForm.addEventListener('keyup', checkInputs, false);
<form id="myForm">
<label for="title">Title:</label> <input type="text" id="title" required> <br /><br />
<label for="toolName">Tool Name: </label><input type="text" id="toolName"> <br /> <br />
<label for="toolURL">Tool URL: </label><input type="url" id="toolURL"> <br /> <br />
<input type="submit" value="Submit" />
</form>

My Jquery does not connect to my html

my jquery is not connecting and I cannot figure out why. I've been stumped on this for hours and I cannot figure it out.
this is my html code. The file name is exercise6.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Exercise 6</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="JS/exercise6.js"> </script>
</head>
<body>
<form id="email_form" name="email_form" action="exercise6.html" method="get">
<fieldset class="info">
<legend>Contact Information</legend>
<p>
<input type="text" name="Lname" id="name2" value="" required />
<label for="name2"> Last</label>
</p>
<p>
<input type="text" name="mailAddie" id="mail1" value="" required />
<label for="mail1"> Address</label>
</p>
<p>
<input type="text" name="City" id="city1" value="" />
<label for="city1"> City</label>
</p>
<p>
<input type="text" name="State" id="state1" value="" />
<label for="state1"> State</label>
</p>
<p>
<input type="number" name="Zip" id="zip1" value="" />
<label for="zip1"> Zip</label>
</p>
<p>
<input type="number" name="phoneNum" id="number" />
<label for="number"> Phone</label>
</p>
</fieldset>
<fieldset>
<legend>Sign up for our email list</legend>
<p>
<label for="email_address1"> Email Address</label>
<input type="text" name="email_address1" id="email_address1" value="" />
<span>*</span><br>
</p>
<p>
<label for="email_address2"> Confirm Email Address</label>
<input type="text" name="email_address2" id="email_address2" value="" />
<span>*</span><br>
</p>
<p>
<label for="first_name"> First</label>
<input type="text" name="first_name" id="first_name" value="" />
<span>*</span><br>
</p>
</fieldset>
<p>
<label> </label>
<input type="submit" value="Join Our List" id="join_list" >
</p>
</form>
</body>
</html>
and this is my javascript. The file name is exercise6.js and it is located in a file named JS. I do not know what I am doing wrong.
$(document).ready(function() {
$("#join_list").click(function() {
var emailAddress1 = $("#email_address1").val();
var emailAddress2 = $("#email_address2").val();
var isValid = true;
if (emailAddress1 == "") {
$("#email_address1").next().text("This field is required.");
isValid = false;
} else {
$("#email_address1").next().text("");
}
if (emailAddress2 == "") {
$("#email_address2").next().text("This field is required.");
isValid = false;
} else {
$("#email_address2").next().text("");
}
if ($("#first_name").val() == "") {
$("#first_name").next().text("This field is required.");
isValid = false
} else {
$("#first_name").next().text("");
}
if (isValid) {
$("#email_form").submit();
}
)};
)};
Can anyone help me?
The last two lines of exercise6.js both have a syntax error.
Change:
)};
)};
To:
});
});
To find this yourself next time, try using web development IDE like NetBeans with the help of right click with mouse to inspect in browser debug console, which would have even shown you where is this kind of error.
Your js code has some errors for close the function "});" try this
$(document).ready(function() {
$("#join_list").click(function() {
var emailAddress1 = $("#email_address1").val();
var emailAddress2 = $("#email_address2").val();
var isValid = true;
if (emailAddress1 == "") {
$("#email_address1").next().text("This field is required.");
isValid = false;
} else {
$("#email_address1").next().text("");
}
if (emailAddress2 == "") {
$("#email_address2").next().text("This field is required.");
isValid = false;
} else {
$("#email_address2").next().text("");
}
if ($("#first_name").val() == "") {
$("#first_name").next().text("This field is required.");
isValid = false
} else {
$("#first_name").next().text("");
}
if (isValid) {
$("#email_form").submit();
}
});
});

How to count the number of selected elements?

I have a lot of elements which are used identical class-name. Now I need to calculate the number of selected items.
For e.g. something like this: (however this example doesn't work correctly)
$("#btn").click(function(){
if($(".necessarily").val() == ''){
$(".necessarily").css('border','1px solid red');
}
// also I want the number of input.necessarily which are empty
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<form name="frm" action="#">
<input name="first-name" class="necessarily" type="text" /><br><br>
<input name="last-name" class="necessarily" type="text" /><br><br>
<input name="email" class="necessarily" type="email" /><br><br>
<input name="password" class="necessarily" type="password" /><br><br>
<input name="address" class="anything" type="text" /><br><br>
<input name="btn" id="btn" type="submit" value="Register" />
</form>
Now I want the number of those inputs which are empty ..., How can I calculate that?
.val() method returns .value property of the first element in the collection. You can filter the empty inputs using the .filter() method and read the .length property of the filtered collection:
var $empty = $(".necessarily").filter(function() {
// you can use the `$.trim` method for trimming whitespaces
// return $.trim(this.value).length === 0;
return this.value.length === 0;
});
if ( $empty.length > 0 ) {
}
If you want to add a border to the empty fields you can declare a CSS class and use the .removeClass and .addClass methods:
CSS:
.red_border {
border: 1px solid red;
}
JavaScript:
var $empty = $(".necessarily").removeClass('red_border').filter(function() {
return this.value.length === 0;
}).addClass('red_border');
You'd do better looking at the HTML5 Contraint API rather than doing what you're currently doing, which is a more manual and time-consuming way.
Instead of giving each field a class 'necessarily' (sidenote: the word you need is 'necessary', not 'necessarily', or, better still, 'required') use the required attribute. So:
<input name="last-name" required type="text" />
Then in your jQuery you can target empty fields with:
$('input:invalid').css('border', 'solid 1px red');
If all you're doing is highlighting bad fields, you don't even need JavaScript for this. You can do the same thing via CSS:
input:invalid { border: solid 1px red; }
The only problem with that is the styling will be showed even before the user has filled out the form, which is almost never desirable. You could get round this by logging, via JS, when the form is submitted, and only then activating the styles:
JS:
$('form').on('submit', function() { $(this).addClass('show-errors'); });
CSS:
.show-errors input:invalid { border: solid 1px red; }
Try this code:
$("#btn").click(function(){
var selectedcount = $(".necessarily").length; //no. of elements with necessarily class name
var emptyInputCount=0;
$(".necessarily").each(function(){
if($(this).val() == ''){
emptyInputCount++;
}
});
Try with each loop on the target elements.
$(function() {
$("#btn").click(function() {
var i = 0;
$(".necessarily").each(function() {
if ($(this).val() == "") {
$(this).css('border', '1px solid red');
i++;
}
});
alert(i); //Number of input element with no value
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form name="frm" action="#">
<input name="first-name" class="necessarily" type="text" />
<br>
<br>
<input name="last-name" class="necessarily" type="text" />
<br>
<br>
<input name="email" class="necessarily" type="email" />
<br>
<br>
<input name="password" class="necessarily" type="password" />
<br>
<br>
<input name="address" class="anything" type="text" />
<br>
<br>
<input name="btn" id="btn" type="submit" value="Register" />
</form>
Hope this helps!
You can use filter() like following example bellow.
var empty_inputs = $('.necessarily').filter(function(){
return $(this).val()=='';
});
empty_inputs.length will return 3 in my example.
Hope this helps.
var empty_inputs = $('.necessarily').filter(function(){
return $(this).val()=='';
});
console.log(empty_inputs.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="first-name" class="necessarily" type="text" /><br><br>
<input name="last-name" class="necessarily" type="text" /><br><br>
<input name="email" class="necessarily" type="email" value="Register"/><br><br>
<input name="password" class="necessarily" type="password" /><br><br>
<input name="address" class="anything" type="text" value="Register"/><br><br>
<input name="btn" id="btn" type="submit" value="Register" />
Hope this helps.
You need to:
query all elements by className
filter the jQuery Collection in order to keep only the elements that have no value
doSomethingElse
so, this maybe could help you:
function CheckEmptyCtrl($) {
'use strict';
var self = this;
self.target = $('.necessarily');
self.empty = self.target.filter(function(index, item) {
return !($(item).val().trim());
});
$('#result').append(self.empty.length + ' elements have no values.');
console.log(self.empty.length, self.empty);
}
jQuery(document).ready(CheckEmptyCtrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div id="result"></div>
<form name="frm" action="#">
<input name="first-name" class="necessarily" type="text" value="notEmpty" /><br><br>
<input name="last-name" class="necessarily" type="text" /><br><br>
<input name="email" class="necessarily" type="email" /><br><br>
<input name="password" class="necessarily" type="password" /><br><br>
<input name="address" class="anything" type="text" /><br><br>
<input name="btn" id="btn" type="submit" value="Register" />
</form>
You need to loop over the all of the inputs and count how many are empty. In the same loop you can also count the number of .necessarily inputs which are empty.
This example will output the result to the .result span.
$("#btn").click(function() {
var inputs = $("form input");
var emptyNecessarilyCount = 0;
var totalEmpty = 0
inputs.each(function() {
if ($(this).val() == "") {
totalEmpty++;
if ($(this).hasClass('necessarily')) {
emptyNecessarilyCount++;
}
}
});
$('.result').append("Total: " + totalEmpty);
$('.result2').append("Necessarily: " + emptyNecessarilyCount);
});
span {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="frm" action="#">
<input name="first-name" class="necessarily" type="text" />
<br>
<input name="last-name" class="necessarily" type="text" />
<br>
<input name="email" class="necessarily" type="email" />
<br>
<input name="password" class="necessarily" type="password" />
<br>
<input name="address" class="anything" type="text" />
<br>
<input name="btn" id="btn" type="submit" value="Register" />
<span class="result"></span>
<span class="result2"></span>
</form>

Categories

Resources