Comparing 2 inputs with jquery - javascript

hello im trying to just compare what is inside of 2 different inputs.
$(document).ready(function() {
$('#pc').keydown(function() {
if ($('#ps').val() == $('#pc').val()) {
alert("it worked ");
}
});
});
<form id="identicalForm" class="form-horizontal" action="userSignup.php" method="post">
<fieldset>
<div id="legend">
<legend class="">Register</legend>
</div>
<div class="control-group">
<label class="control-label" for="email">E-mail</label>
<div class="control-group">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input id="ps" name="password" placeholder="" class="form-control input-lg" type="password">
<p class="help-block">Password should be at least 6 characters</p>
</div>
</div>
<div class="control-group ">
<label class="control-label" for="password_confirm">Password (Confirm)</label>
<div class="controls">
<input id="pc" name="password_confirm" placeholder="" class="form-control input-lg" type="password">
<p class="help-block">Please confirm password</p>
</div>
</div>
</fieldset>
</form>
This is a semi condensed version of the web page. the inclusion is at the top of the page. if i put the alert outside of the if, it will do a pop up every time i type in that input box. but if i try to compare the two input fields nothing pops up when they both have the same password entered. from what ive seen from other SO post like this, it should work! I am still a novice with js, so i may just be over thinking this entirely.

The reason it wasn't working with the keydown event is because the event is only fired when the key is down. In other words, the event was being fired before the value was updated. You would be comparing 12345 with 1234 and even though the values would be the same, it wasn't recording the last character that was pressed.
Rather than using the keydown event, use the input or keyup event:
$('#pc').on('input', function() {
if ($('#ps').val() === $('#pc').val()) {
console.log("it worked ");
}
});
The keyup event is fired when the key is up, which means that the value of the element is actually updated. Similarly, the input event will behave the same way since it will be fired when the value changes. In addition, the input event will also catch paste events (which may be useful).

Instead of keydown, which actually executes before you press the key, use either blur or keyup:
$('#pc').on('blur', function() {
if ($('#ps').val() == $('#pc').val()) {
console.log("it worked ");
}
});

Use the keyup event. Also try to use === for comparing the values as we know the values are going to be both text type and do not need an explicit conversion before comparing.
$(document).ready(function () {
$('#pc').keyup(function () {
if ($('#ps').val() === $('#pc').val()) {
alert("it worked ");
}
});
});
The keyup event is sent to an element when the user releases a key on the keyboard.
Here is a working sample

Related

How to hide those two <span> elements specifically for each input in jquery or javascript? Seeking a generic solution

I am doing this for validating multiple input fields with different data intake using a generic function to which I can pass RegExp output and display the validation message or icon.
This is my HTML code
<div class="form-group">
<label for="fname" class="form-lable">First name</label>
<input type="text" id="fname" name="fname" class="form-input" required>
<div for="fname">
<span class="validation-container success"><i class="bi bi-check2"></i></span>
<span class="validation-container error"><i class="bi bi-x"></i></span>
</div>
</div>
<div class="form-group">
<label for="lname" class="form-lable">First name</label>
<input type="text" id="lname" name="lname" class="form-input" required>
<div for="lname">
<span class="validation-container success"><i class="bi bi-check2"></i></span>
<span class="validation-container error"><i class="bi bi-x"></i></span>
</div>
</div>
This is what I am doing
$('#fname').on('keyup', function () {
$('.validation-container').hide();
});
$('#lname').on('keyup', function () {
$('.validation-container').hide();
});
What it does:
It's doing that thing for both of the inputs.
$('#fname').on('keyup', function () {
$(this).parent().find('.validation-container').hide();
let check = fnameRegExp.test($(this).val());
let success = ".validation-container.success";
let wrong = ".validation-container.error";
validateInput(check, success, wrong);
});
What I am doing here is sending regex match, success as well as wrong classes to the function. If the input is not matched with the regex then it will display the div having that wrong class.
function validateInput(check, success, wrong) {
if (check) {
$(success).show();
checkAll();
} else {
$(wrong).show();
}
}
And I am calling that function on keyup for each input. what it does is, it shows validation signs (✅, ❎) for every input.
change this
<div for="fname" id="fnameValidators">
<span class="validation-container success"><i class="bi bi-check2"></i></span>
<span class="validation-container error"><i class="bi bi-x"></i></span>
</div>
$('#fname').on('keyup', function () {
$('#fnameValidators').hide();
});
Similarly make changes for last name.
TL;DR
Use
$(this).parent().find('.validation-container').hide();
To hide only the element with that class within the same container.
Longer version
$('.validation-container') searches in the whole DOM. To restrict it, you can use this selector within another element. Since you're reading the keyup event on the input, you can simply use $(this) to obtain the input object. Then go over 1 level with .parent() to select the <div class="form-group"> containing it and finally use find('.validation-container') to select the correct span you want to hide.
As one-liner:
$(this).parent().find('.validation-container').hide();
Even more dynamic
If you want to make this even more dynamic, you can avoid calling a keyup event for each separate input, and create a single function that manages all your inputs correctly.
$('.form-lable').on('keyup', function () {
var type = $(this).attr('id')
// You can use the variable type to distinguish between the two inputs
$(this).parent().find('.validation-container').hide();
});
Try this
$('#fname').on('keyup', function () {
$("div[for='fname']").find('.validation-container').hide();
});
$('#lname').on('keyup', function () {
$("div[for='lname']").find('.validation-container').hide();
});

Event will not trigger

I have a form that has multiple inputs. One input is where user can input an ID. I need to verify the ID is unique. I want to call a JavaScript function for a onchange event. However, I can't get it to trigger. I have a console.log but it never hits when I make a change in the input so I am doing something wrong.
This is the function I am trying to call on the on change
function checkUniqueID() {
console.log("here");
var $counter = 0;
var tag = document.forms["userform"]["new_id"].value;
while ($counter < $totalItems) {
}
};
<div class="six wide field">
<label for="ID">ID</label>
<input type="text" id="new" name="new_id" placeholder="ID" onchange="checkUniqueID()">
</div>
I can't even get the console.log ("here") to trigger
The onchange HTML attribute triggers when the input loses focus.
So, if you correctly have your input#new_id inside a form like this:
<form name="userform">
<div class="six wide field">
<label for="ID">ID</label>
<input type="text" id="new" name="new" placeholder="ID">
</div>
</form>
Adding an eventListener in your script file would be enough.
document.userform.new_id.onchange=function(){
alert("ID changed to: "+this.value);
};
With jQuery would be as easy as:
$("#new").change(function(){
alert("ID changed to: "+$(this).value;
}
Here is a working fiddle:
https://jsfiddle.net/edbL3kgp/

OnInvalid html event triggering after Required modifier removed through JS

I have three input fields I am attempting to enforce validity on. Currently, I have them all set as required, but removing the modifier with Javascript on submit if one of them is filled out; essentially, one must fill out at least one, but not none of these fields.
Here is an example of the fields:
jQuery(function ($) {
var $inputs = $('input[name=Input1],input[name=Input2], input[name=Input3]');
$inputs.on('input', function () {
// Set the required property of the other input to false if this input is not empty.
$inputs.not(this).prop('required', $(this).val().length > 0 && $(this).val() != 0)
});
});
jQuery(function ($) {
$("#Input1, #Input2").oninvalid = (function() {
$(this).setCustomValidity("Please enter a valid Input1, Input2, or Input3")
});
});
var Input3default = document.getElementById('Input3')
if (Input3.value.length == 0) Input3.value = "0";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="input-group mb-3">
<form action="" method="get" autocomplete="off">
<div class="row" style="text-align:justify; width: 100%; display:inline">
<div class="">
<label for="text3">Input1:</label>
<input type="text" id="Input1" name="Input1" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')" />
</div>
<div class="">
<label for="text4">Input2:</label>
<input type="text" id="Input2" name="Input2" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')"/>
</div>
<div class="">
<label for="text5">Input3:</label>
<input type="text" id="Input3" name="Input3" required placeholder="0" pattern="[0-9]*" onsubmit="Input3default" oninvalid="this.setCustomValidity('Please enter a valid Input3')"/>
</div>
</div>
<p>
<input type="submit" value=" Submit " />
</p>
</form>
</div>
</div>
This seems to work fine if I leave it default; I have Input1 and Input2 empty by default, and Input3 has a value of "0" by default. If I enter Input1 or Input2, my submission goes through just fine. However, the problems begin if I alter Input3.
Problem 1: Any time I enter Inputs 1 and 2 but leave 3 blank, it triggers invalidity; my Input3default never seems to trigger, and it is passed blank and caught by the oninvalid tag.
Problem 2: Along with that, if I do not specify an Input2 along with my Input1 while Input3 is blank, it triggers invalidity on Input2. Using Chrome Debugger, I can see that the Required tag is removed, but my OnInvalid pop-up still comes up no matter what is remedied.
Essentially, I am trying to solve the second problem: When I remove the required html tag from my input, after invalidating another input with a Javascript-enforced default, my inputs refuse to validate on the front end.
I appreciate any advice and conjecture as to why this may be the case, and believe that the two problems are connected.
EDIT: Upon adding an = to my original oninvalid JQuery function, I removed a JS error. It appears that my Input3 default function triggers on pageload, but not on submit; I added an onsubmit function to input3, but am still receiving oninvalid events for input2.
I was able to fix this issue on my own, using the OnInput event.
The setCustomValidity function, when triggered, does not allow a submission while a CustomValidity is set. In order to fix this, I edited my inputs as so:
<input type="text" id="Input1" name="Input1" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')" oninput="this.setCustomValidity('')"/>
I still have a few kinks to iron out, but this fixed my main problem in that the validity of an input was not being reset.
I'll leave this answer unaccepted at first to allow others to pitch in.

blur/focusout doesn't work

I have multiple divs with the same class-'.new-contact.clearfix.invite'. The divs contain some inputs.
I want to perform validation on the form (which its class is 'invitePartners) only when I click/enter some input in different line (each div is a different line).
I tried the following, but the event is not triggered:
$('.invite').on('blur','.new-contact.clearfix.invite', function () {
$('.invitePartners').valid()
})
Example of the div's HTML:
<div class="row">
<div class="new-contact clearfix invite">
<div class="first-name invite">
<input type="text" id="firstName1" class="signup-input firstName required" name="first[1]" placeholder="">
</div>
<div class="last-name">
<input type="text" id="lastName1" class="signup-input lastName" name="last[1]" placeholder="optional">
</div>
<input type="text" data-index="1" id="inputMail1" class="signup-input mail" name="email[1]" placeholder="e.g. example#url.com" aria-invalid="true">
<span class="common-sprite sign-up-cross first clone"></span>
</div>
</div>
</div>
Quote from JQuery on help page :
The focus and blur events are specified by the W3C to not bubble, but jQuery defines cross-browser focusin and focusout events that do bubble.
This mean that your blur event don't go up the DOM when fired from .new-contact.clearfix.invite and so cannot be catch up by .invite
$('body').on('blur','.new-contact.clearfix.invite input', function () {
$('.invitePartners').valid()
});
Try .focusout() ...
$('.new-contact.clearfix.invite').focusout(function () {
$('.invitePartners').valid();
});
It's not really clear what your elements are, you should post your HTML in your question. If you are just trying to use elements that are related to the element blurred, you may need to use something like ...
$('.invitePartners', this).valid();

Validating Form with Javascript (Simple Test)

var name = document.getElementById('contact-name'),
email = document.getElementById('contact-email'),
phone = document.getElementById('contact-phone'),
message = document.getElementById('contact-message');
function checkForm() {
if (name.value == '') {
alert('test');
}
}
I was simply trying to make sure everything was working before I began learning actual client-side validation.
Here is the HTML
<form role='form' name='contactForm' action='#' method="POST" id='contact-form'>
<div class="form-group">
<label for="contact-name">First and Last Name</label>
<input type="text" class="form-control" id="contact-name" name="contactName" placeholder="Enter your name.." pattern="[A-Za-z]+\s[A-Za-z]+">
</div>
<div class="form-group">
<label for="contact-email">Email address</label>
<input type="email" class="form-control" id="contactEmail" name="contactEmail" placeholder="Enter Email" required>
</div>
<div class="form-group">
<label for="contact-phone">Phone Number</label>
<input type="number" class="form-control" id="contactPhone" name="contactPhone" placeholder="Enter Phone Number" required'>
</div>
<div class="form-group">
<label for='contactMessage'>Your Message</label>
<textarea class="form-control" rows="5" placeholder="Enter a brief message" name='contactMessage' id='contact-message' required></textarea>
</div>
<input type="submit" class="btn btn-default" value='Submit' onclick='checkForm()'>
</fieldset>
</form>
I took the required attribute off, and if I leave the name field empty it goes right to the other one when i click submit. To check whether javascript was working at all, i did an basic onclick function that worked.
Maybe someone can explain to me what is wrong with the checkForm function. Thanks in advance.
P.S The form-group and form-control classes belong to bootstrap
Change your javascript to this:
var contactName = document.getElementById('contact-name'),
email = document.getElementById('contact-email'),
phone = document.getElementById('contact-phone'),
message = document.getElementById('contact-message');
function checkForm() {
if (contactName.value === '') {
alert('test');
}
}
Okay, Hobbes, thank you for editing your question, now I can understand your problem.
Your code faces three two issues.
Your control flow. If you want to validate your field, you have to obtain its value upon validation. You instead populate variable name when the page loads, but the user will enter the text only after that. Hence you need to add var someVariableName = document.getElementById(...); to the beginning of the checkForm() function.
global variables. Please do not use them like that, it is a good design to avoid global variables as much as possible, otherwise you bring upon yourself the danger of introducing side effects (or suffering their impact, which happens in your situation). The global context window already contains a variable name and you cannot override that. See window.name in your console. You can of course use var name = ... inside the function or a block.
Even if you fix the above, you will still submit the form. You can prevent the form submission if you end your checkForm() function with return false;
For clarity I append the partial javascript that should work for you:
function checkForm() {
var name = document.getElementById('contact-name');
if (name.value == '') {
alert('test');
return false;
}
}
EDIT: As Eman Z pointed out, the part 1 of the problem does not really prevent the code from working as there's being retrieved an address of an object (thanks, Eman Z!),

Categories

Resources