jQuery if multiple objects equal same value - javascript

I have multple objects. Before submitting a form, I want to check to be sure all of the object values are "ok".
$("#sub_button").click(function() {
if (myObj.login_id && myObj.email == "ok") {
alert("This would submit the form. login ID obj is: "+myObj.login_id+" and email email obj is: "+myObj.email);
} else {
alert("the form is bad!");
}
});
I've tried it with two == and three ===, it still isn't working. The myObj.login_id or myObj.email could equal ANYTHING and it still pops up the "This would submit the form" alert, and shows in the alert box that the value(s) is NOT "ok".
What am I doing wrong?

This isn't comparing what you think it's comparing. When you read this aloud, it sounds right: "if login ID and email are equal to OK", but that's not how the && works. You want:
if (myObj.login_id == "ok" && myObj.email == "ok") {
....
}
The code you did write actually says "if login ID is anything at all, and if email is "ok" ".

$("#sub_button").click(function() {
if (myObj.login_id == "ok" && myObj.email == "ok") {
alert("This would submit the form. login ID obj is: "+myObj.login_id+" and email email obj is: "+myObj.email);
} else {
alert("the form is bad!");
}
});

You should do:
("#sub_button").click(function() {
if (myObj.login_id === "ok" && myObj.email === "ok") {
alert("This would submit the form. login ID obj is: "+myObj.login_id+" and email email obj is: "+myObj.email);
else {
alert("the form is bad!");
In your code you just check that myObj.login_id resolves to true (which happens everytime myObj.login_id value is not in this list)
false
null
undefined
The empty string ''
The number 0
The number NaN (yep, 'Not a Number' is a number, it is a special number)

Try this
$("#sub_button").click(function() {
if (myObj.login_id == "ok" && myObj.email == "ok") {
alert("This would submit the form. login ID obj is: "+myObj.login_id+" and email email obj is: "+myObj.email);
} else {
alert("the form is bad!");

(myObj.login_id && myObj.email == "ok") will evaluate to true if myObj.email == "ok" and myObj.login_id has a non-zero value. You're not evaluating the contents of login_id to anything, so it'll be handled as a boolean and converted to such according to the contents.
You should change it to (myObj.login_id == "ok" && myObj.email == "ok").

Related

JavaScript Multiple Entry Form Validation

I am trying to use Javascript to validate user input before page redirects.
Users can either Input Student ID, Name, or Gender, and based on their input, they will be redirected to a URL.
However, I don't seem to get the multiple entries correctly in my javascript and nothing happened when the submit button is clicked.
I have tried different solutions which I found here.
see my JavaScript code below;
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate(){
var username = document.getElementById("studentid").value;
if ( studentid == "12345" || studentid == "Daniel" || studentid == "Boy"){
alert ("Correct Input");
window.location = "https://www.google.com";
// Redirecting to other page.
return false;
}
else{
attempt --;// Decrementing by one.
alert("ATTENTION!\nInvalid student ID!\nNot associated with any student\nYou have left "+attempt+" attempt;");
// Disabling fields after 3 attempts.
if( attempt == 0){
document.getElementById("studentid").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
I have tried to use the solutions below;
if ( studentid == "#12345, #Daniel, #Boy"));{
alert ("correct input");
window.location = "https://www.google.com";
// Redirecting to other page.
if ( studentid == '12345', 'Daniel', 'Boy'){
alert ("correct input");
window.location = "https://www.amazon.com";
// Redirecting to other page.
After so many attempts, I finally got it right!
var attempt = 3;
function check(form)
{
if(form.studentid.value == "12345" || form.studentid.value == "DANIEL" || form.studentid.value == "BOY")
{
window.location.replace('https://www.google.com')
return false;
}
else
{
attempt --;// Decrementing by one.
alert("ATTENTION!\nInvalid student ID!\nNot associated with any student!\nYou have left "+attempt+" attempt;");
// Disabling fields after 3 attempts.
if( attempt == 0){
document.getElementById("studentid").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}

IF/ELSE on Javascript works strangely

I have a form where I ask for an email that I validate trought a regular expression, if the email is correct, I do a submit, if not I send an alert.
When I put an invalid email the alert is shown, but if I put a valid email the alert is shown and then the submit() is done, I don't even know how is this posible! Here is my code.
$('#sinCopago').on('click', function(event){
if($('#nombreContratante').val() != "" && $('#motivo').val() != ""){
if($('#fechaNac').val() > hoy){
alert("Ingresa una fecha de nacimiento válida.");
}else{
if(validarMail($("#correo")) == true){
event.preventDefault();
$('#progressBarSisnova').modal({show:true});
$('#payment-form-Sisnova').submit();
}
else{
alert("Ingresa un correo válido");
}
}
}
else{
alert("Por favor llene todos los campos");
}
});
function validarMail(email){
var caract = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
if(caract.test(email) == false){
return false;
}
else{
return true;
}
}
You're currently passing the $("#correo") jQuery object to validarMail:
if(validarMail($("#correo")) == true){
and proceed to test that object:
if(caract.test(email) == false){
Which won't work, of course, because you're not testing a string. Try passing the .val() of #correo instead. so that the eventual .test( is called with the value string, not the jQuery object:
if(validarMail($("#correo").val()) == true){
Feel free to remove the == true part, validarMail already returns a boolean:
if(validarMail($("#correo").val())){
You should also preventDefault when the test fails, not when the test succeeds - that way, the form will be submitted as normal without interruption only when the test succeeds. The code will also probably be flatter and easier to read if you return when there's an error:
$('#sinCopago').on('click', function(event){
if($('#nombreContratante').val() === "" || $('#motivo').val() === "") {
event.preventDefault();
return alert("Por favor llene todos los campos");
}
if($('#fechaNac').val() <= hoy){
event.preventDefault();
return alert("Ingresa una fecha de nacimiento válida.");
}
if(!validarMail($("#correo").val())){
event.preventDefault();
return alert("Ingresa un correo válido");
}
$('#progressBarSisnova').modal({show:true});
$('#payment-form-Sisnova').submit();
});
If clicking #sinCopago submits the form without preventDefault, then there's no need for the final line there $('#payment-form-Sisnova').submit();. (Otherwise, then there may be no need for preventDefault at all, if the event's default action doesn't cause a form submission or other undesirable behavior)
you should pass the value of field for function validarMail(), so replace the current cod
if(validarMail($("#correo")) == true)
for
if(validarMail($("#correo").val()) == true)
an you can improve you function.
function validarMail(email){
var caract = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
return caract.test(email)
}

match email and confirm

I would like to match email address with the confirm email address. I have tried this validation but it's not working. Don't know why.
function ValidationRequired(field, alerttxt){
with (field){
if (value==null || value==""){
alert(alerttxt);
return false;
}else{
return true;
}
}
}
function ValidateThisForm(thisform){
with(thisform){
if(ValidationRequired(EmailAddress, "You must supply an e-Mail address.") == false){
EmailAddress.focus();return false;
}
}
with(thisform){
if(ValidationRequired(EmailAddressConfirm, "You must confirm your e-Mail address.") == false){
EmailAddressConfirm.focus();return false;
}
}
with(thisform){
if(ValidationRequired(EmailAddress != EmailAddressConfirm, "Those emails don\'t match!") == false){
EmailAddressConfirm.focus();return false;
}
}
return true;
}
The first parameter to the function ValidationRequired is supposed to be a field. In the code that is supposed to match the email addresses, the first parameter is not a field, but a boolean expression.
with(thisform){
if(ValidationRequired(EmailAddress != EmailAddressConfirm, "Those emails don\'t match!") == false){
EmailAddressConfirm.focus();return false;
}
}
You could solve this in a few different ways. One way would be to write a second validation function that takes two field parameters and compares the values of two fields.
But if you want to know why the code isn't working, it's because your not passing a field to the function.

JavaScript redirection error

I am trying to use JavaScript to redirect to a PHP page on my site, however, when I do it, nothing happens, apart from the alert boxes if I do not fill in the parameters. Is there something I am doing wrong?
document.getElementById("submit").onclick = check;
function check()
{
if(document.getElementById("name").value == "")
alert("The field 'Name' is required.");
else if (document.getElementById("message").value == "")
alert("The field 'Message' is required");
else
window.location.href = "scripts/main/contact.php?msg=" + document.getElementById("message").value;
}
Your default form action takes place overriding your redirect. Return false from the handler to prevent it from taking place:
function check()
{
if(document.getElementById("name").value == "")
alert("The field 'Name' is required.");
else if (document.getElementById("message").value == "")
alert("The field 'Message' is required");
else
window.location.href = "scripts/main/contact.php?msg=" + document.getElementById("message").value;
return false; // <------ here
}

If Statement Not Acting As Expected

$(document).ready(function(){
logger();
});
function logger()
{
if(localStorage.getItem("status") === null)
{
$("#test").html("Not logged in.");
$("#buttonlogin").click(function(){
var ul = $("#userlogin").val();
var pl = $("#passlogin").val();
$.post("includes/logger.php", {type : "login", user : ul, pass : pl}, function(dlogin){
if(dlogin == 1)
{
$("#outlogin").html("Please enter a username.");
$("#userlogin").focus();
}
else if(dlogin == 2)
{
$("#outlogin").html("Please enter password.");
$("#passlogin").focus();
}
else if(dlogin == 3)
{
$("#outlogin").html("This username doesn't exist.");
$("#userlogin").focus();
}
else if(dlogin == 4)
{
$("#outlogin").html("This username and password don't match.");
$("#userlogin").focus();
}
else
{
localStorage.setItem("status", dlogin);
logger();
}
});
});
$("#buttonregister").click(function(){
var ur = $("#userregister").val();
var pr = $("#passregister").val();
var cpr = $("#confirmpassregister").val();
$.post("includes/logger.php", {type : "register", user : ur, pass : pr, cpass : cpr}, function(dregister){
if(dregister == 1)
{
$("#outregister").html("Please enter a username.");
$("#userregister").focus();
}
else if(dregister == 2)
{
$("#outregister").html("Please enter a password.");
$("#passregister").focus();
}
else if(deregister == 3)
{
$("#outregister").html("Please enter a confirm password.");
$("#cpassregister").focus();
}
else if(dregister == 4)
{
$("#outregister").html("Password and confirm password do not match.");
$("#passregister").focus();
}
else if(dregister == 5)
{
$("#outregister").html("This username is already taken.");
$("#userregister").focus();
}
else
{
localStorage.setItem("status", dregister);
logger();
}
});
});
}
else
{
$("#test").html("You are logged in.");
$("#buttonlogout").click(function(){
localStorage.removeItem("status");
logger();
});
}
}
The above code is meant to check whether or not a localStorage variable is in existence or not. If it is then only allow the log out button to be pressed. If is doesn't then let the two forms to work. Once it is done with either it is supposed to recheck if the variable is set and then do as I said above. However it ignores it when a user logs in and allows the forms to run. If you refresh however it works fine. I cannot for the life of me figure out why this is happening, and it is beginning to piss me off. Any help would be appreciated.
On your else statement, try adding:
$('#buttonlogin').unbind('click');
$('#buttonregister').unbind('click');
If I understand your problem correctly, what's happening is those events are registered when you first run $("#buttonlogin").click(function()....
It doesn't matter that you call logger() again and the if statement is false the second time around. If you want to disable these callbacks you have to do it explicitly.

Categories

Resources