Need to correct this form validation - javascript

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>

Related

Script with querySelector works only once for class

The script below works fine for the first div with the .inp class, it doesn't work for the second block with the same class. I broke my head trying to figure out why this is happening and how to make it work, while NOT ADDING new classes or IDs to the second div.
document.querySelector("input").focus();
document.querySelector(".inp").addEventListener("input", function({ target, data }){
// Exclude non-numeric characters (if a value has been entered)
data && ( target.value = data.replace(/[^0-9]/g,'') );
const hasValue = target.value !== "";
const hasSibling = target.nextElementSibling;
const hasSiblingInput = hasSibling && target.nextElementSibling.nodeName === "INPUT";
if ( hasValue && hasSiblingInput ){
target.nextElementSibling.focus();
}
});
.inp input {
display: inline-block;
width: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="inp">
<input type="text" name="digit1" />
<input type="text" name="digit2" />
<input type="text" name="digit3" />
<input type="text" name="digit4" />
<input type="text" name="digit5" />
</div>
<div class="inp">
<input type="text" name="digit1" />
<input type="text" name="digit2" />
<input type="text" name="digit3" />
<input type="text" name="digit4" />
<input type="text" name="digit5" />
</div>
Using (document|element).querySelector will give the first element which matches the query.
You can user (document|element).querySelectorAll instead in this scenario.
document.querySelector("input").focus();
document.querySelectorAll(".inp").forEach(element=>element.addEventListener("input", function({ target, data }){
// Exclude non-numeric characters (if a value has been entered)
data && ( target.value = data.replace(/[^0-9]/g,'') );
const hasValue = target.value !== "";
const hasSibling = target.nextElementSibling;
const hasSiblingInput = hasSibling && target.nextElementSibling.nodeName === "INPUT";
if ( hasValue && hasSiblingInput ){
target.nextElementSibling.focus();
}
}))
.inp input {
display: inline-block;
width: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="inp">
<input type="text" name="digit1" />
<input type="text" name="digit2" />
<input type="text" name="digit3" />
<input type="text" name="digit4" />
<input type="text" name="digit5" />
</div>
<div class="inp">
<input type="text" name="digit1" />
<input type="text" name="digit2" />
<input type="text" name="digit3" />
<input type="text" name="digit4" />
<input type="text" name="digit5" />
</div>
Here you go:
document.querySelector("input").focus();
document.querySelectorAll(".inp").forEach(inp => {
inp.addEventListener("input", function({ target, data }){
// Exclude non-numeric characters (if a value has been entered)
data && ( target.value = data.replace(/[^0-9]/g,'') );
const hasValue = target.value !== "";
const hasSibling = target.nextElementSibling;
const hasSiblingInput = hasSibling && target.nextElementSibling.nodeName === "INPUT";
if ( hasValue && hasSiblingInput ){
target.nextElementSibling.focus();
}
});
})
.inp input {
display: inline-block;
width: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="inp">
<input type="text" name="digit1" />
<input type="text" name="digit2" />
<input type="text" name="digit3" />
<input type="text" name="digit4" />
<input type="text" name="digit5" />
</div>
<div class="inp">
<input type="text" name="digit1" />
<input type="text" name="digit2" />
<input type="text" name="digit3" />
<input type="text" name="digit4" />
<input type="text" name="digit5" />
</div>
As Pointy mentioned querySelector() method can only be used to access a single element while querySelectorAll() method can be used to access all elements which match with a specified CSS selector.
.querySelector will work only for the first element it finds, you should use .querySelectorAll instead. It will return a node list of all selectors with your class.
Then you can iterate with a loop through all of them and add the event listener.

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";
}

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

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