Validation errors in javascript - javascript

I want to check if my application's buttons are pressed or not. The error I face is, even when the buttons are clicked all the alerts display. Attached is the code snippet, the variables are set by click of buttons.
I want the alert not to display if any of the values are selected,
var condition ;
var clickable; // GLOBAL VARIABLES
function clickMe1()
{
clickable = "Sell";
}
function clickMe2()
{
clickable = "Rent";
}
function condition1()
{
condition="Excellent"
}
function condition2()
{
condition="Good"
}
function condition3()
{
condition="Fair"
}
function condition4()
{
condition="New"
}
function display()
{
if (condition != "Excellent"||"New"||"Fair"||"Good")
{
alert( " Please enter the condition ");
}
if (clickable != "Sell"||"Rent")
{
alert("Please enter the Sell");
}
if (costSell === '')
{
alert("Please select a Price ");
}
if ((condition === "Excellent"||"New"||"Fair"||"Good") && (clickable === "Selling"||"leasing")&&(!isNaN(costSell)))
{
// Do Something
},
error: function(data){
console.log("not added");
}
});
}
else
{
alert(" price is not a number");
}
}
I also tried:
if(condition !='Excellent'|| condition!='New' || condition!='Fair'|| condition!='Good')
{
alert( " Please enter the condition ");
}
if (clickable !='Sell'||'Rent' )
{
alert("Please enter the Sell ");

if(condition !='Excellent'|| condition!='New' || condition!='Fair'|| condition!='Good')
should be
if (condition != 'Excellent' && condition != 'New' && condition != 'Fair' && condition != 'Good')​
because your version triggers if the condition is any one of Excellent, New, Fair, or Good. The corrected line triggers when the condition is not one of those.
And
if (clickable !='Sell'||'Rent' )
should be
if (clickable !='Sell' && clickable !='Rent' )
because you can't make that shortcut of only using clickable once.

condition !="Excellent"||"New"||"Fair"||"Good"
Conditions like this are your problem.
condition !="Excellent" && condition != "New" ...
^The solution

Your problem is you're testing multiple conditions without repeating the left-hand operand.
For example:
condition !="Excellent"||"New"||"Fair"||"Good"
It should be this:
condition != "Excellent" || condition != "New" || condition != "Fair" || condition !="Good"

Related

jQuery check if input is empty

I am trying to get it where, if there is value in the input, go ahead and do your thing but if there isn't, don't do anything. I keep getting getting it where, if there is nothing in the input, a failure message occurs but only if I hit the enter key
jsfiddle.net/BBaughn/8ovrmhgp click the space in the lower right corner, then press enter. It shouldn't pop up, because the input is not focused.
login/failure jQuery:
$(document).ready(function(){
$('.btn1').on('click', function(){
var login = [marion, 'FATHER1'];
var marion = $('#logging').val();
marion = marion.toUpperCase();
if (marion !== 'FATHER1' && $('#logging').val()) {
alert('Login Failed');
} else if (marion === 'FATHER1' && $('#logging').val()) {
$('.notify').css('margin-top', '0');
$('#logging').val('');
}
});
$('.exit').on('click', function(){
$('.notify').slideUp('slow');
});
});
if you just want to check if an input is empty, I'm guessing #logging is the input:
$('.btn1').on('click', function(){
var marion = $('#logging').val();
if (marion == '') {
//this means the input value was empty
}
});
if the length is equal zero, that means the field is empty. It works after adding length === 0 check, please try this,
if (e.which == 13 && $('.btn1').val().length === 0) {
e.preventDefault();
} else if (e.which == 13 && $('.btn1').focus()) {
$('.btn1').click();
}
Ok, I think I get what you mean now. You're checking the entire document for keypresses as is, you need to check the input only. I think this is a good solution to do that:
$('.login input').keypress(function (e) {
if (e.which == 13 && !$('#logging').val()) {
e.PreventDefault();
} else if (e.which == 13 && $('.btn1').focus()) {
$('.btn1').click();
}
});
Working Fiddle here
$(document).ready(function(){
$('.btn1').on('click', function(){
var login = [marion, 'FATHER1'];
var marion = $('#logging').val();
marion = marion.toUpperCase();
if (marion !== 'FATHER1' && $('#logging').val()) {
alert('Login Failed');
} else if (marion === 'FATHER1' && $('#logging').val()) {
$('.notify').css('margin-top', '0');
$('#logging').val('');
}
});
$('.exit').on('click', function(){
$('.notify').slideUp('slow');
});
});
I didn't realize that my if statement was if the input wasn't detecting the right login, so it didn't matter if it was out of focus. Now it says "if it's not FATHER1 and there is value in the input only, then send this alert"

jQuery multi vals required

I am trying to show a field, which is hidden, but shows up when 2 previous fields are filled.
$('#planner-locatie-ehv').change(function() {
if ($("#planner-locatie-ehv").val() == "Requirement1" && $("#planner-stad").val() == "Requirement2") {
$("#hideentertainment").show();
}
else {
$("#hideentertainment").hide();
}
});
But the field which is called #hideentertainment won't show up, although the previous fields has Requirement1 and Requirement2, when i use the OR statement ||, it does work, when 1 value is filled in it shows up. How can i make this possible?
You need to listen on both elements, not just the first one.
$('#planner-locatie-ehv, #planner-stad').change(function() {
var isValid = $("#planner-locatie-ehv").val() == "Requirement1" && $("#planner-stad").val() == "Requirement2";
$("#hideentertainment").toggle(isValid);
});
#dandavis is correct. It's only watching the first one for change. You can add the other to your selector to fix it.
$('#planner-locatie-ehv, #planner-stad').change(function() {
if ($("#planner-locatie-ehv").val() == "Requirement1" && $("#planner-stad").val() == "Requirement2") {
$("#hideentertainment").show();
}
else {
$("#hideentertainment").hide();
}
});

validate input type="number"

I try to do some programming:
I have this order form with different input fields (name, amountOfProductA, amountOfProductB, amountOfProduct...) and I submit this form, after some validation, with a jquery script.
I plan to reuse the code and the number of product fields may vary form time to time.
In the validation I make sure that at least one of the (type="number") product input fields is filled in.
If a user types a number in one of the product inputfields and by mistake a character (or a number and a character) in the other the form submits with this later field empty.
Because the wrong filled in field submits empty I cannot validate this.
Can you please give me a clue how validate this?
Should I just juse type="text" input fields? (How do I check if at least one product field is filled in then?)
This is my code:
jQuery(function ($) {
$('#bttn-submit').click(function () {
$('input').css('background', '#fff'); // reset BGcolor
var formOk = true;
var allProdFields = $('input[type=number]') // Selection of all Product('number') fields
var numberOfProdFields = allProdFields.length; // How many ('number') fields are there?
// How many product fields are empty?
var prodFieldsEmpty = 0;
for (i = 0; i < numberOfProdFields; i++) {
if( $(allProdFields[i]).val() == '' || $(allProdFields[i]).val() == 0){
prodFieldsEmpty++;
}
}
// Is there at least one product field filled?
if(prodFieldsEmpty == numberOfProdFields){
var formOk = false;
alert('Form not OK');
allProdFields.css('background', '#f30302');
}
// Is the name field filled?
if( $('#pesoonNaam').val() == '') {
$('#pesoonNaam').css('background', '#f30302');
var formOk = false;
}
if( formOk == true ) {
document.actieForm.submit();
}
})
})
The code below will not let the user enter character in your field only number. Because the type="number" is html5 and doesn't work in all the browsers.
$(document).on('keydown', '.numeric-input', function(event) {
var dot_split = $(this).val().split('.');
if ($.inArray(event.keyCode,[46,8,9,27,13]) !== -1 || (event.keyCode == 65 && event.ctrlKey === true) || (event.keyCode >= 35 && event.keyCode <= 39) && dot_split.length <= 2) {
// let it happen, don't do anything
return;
}else{
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
})
Then you can check with an .each if any of the fields is empty.
prodFieldsEmpty = 0;
$('.numeric-input').each(function(){
if($(this).val() != ""){
prodFieldsEmpty++;
}
})
I hope this helps you!
You can try smth like:
function checkInputs(){
result = false;
$('input[type="number"]').each(function(){
if($(this).val() != '' && isNumeric($(this).val())) result = true;
})
return result;
}
UPD: Fiddle
You should not attach validation to the submit button as the user can submit the form without pressing it, attach validation to the form's submit handler:
jQuery(function ($) {
$('#formID').submit(
...
jQuery has an each method for iterating, so:
$('input[type=number]').each( function(index) {
/* do validation */
});
Within each, the function's this is set to the current element, so you can do:
if (this.value == 0) {
prodFieldsEmpty++;
}
The value of a form control is always a string, so the test this.value == 0 will return true if the value is '0' or '' (empty string). If you don't like using type coercion, then do:
if (this.value === '0' || this.value === '') {
If you want to check that the value is an integer, then there are any number of answers here about that, the simplest is probably the accepted answer here:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Note that this will allow all types of numbers, e.g. 2.34e3. If you just want to allow say positive integers, you can try:
function isPositiveInt(n) {
return /^\d+$/.test(n); // or return !/\D/.test(n)
}
Again, there are many ways to approach that.
Rather than count the number of fields and then the number that pass, if you only want to check that at least one passed, set a flag:
var passNumeric = false;
$('input[type=number]').each( function(index) {
if (isNumber(this.value)) {
passNumeric = true;
} else {
// do something with fails?
}
});
You can use the else branch to do something with the fails (or nothing).

Validate multiple textboxes

I have this code that validates if ContentPlaceHolder1_locationTextBox has text in it before newIndex can become 3.
if ((newIndex === 3 && $("#ContentPlaceHolder1_locationTextBox").val() == "")) {
$('#ContentPlaceHolder1_locationLabelV').show();
return false;
}
else {
$('#ContentPlaceHolder1_locationLabelV').hide();
}
However I also have ContentPlaceHolder1_countryTextBox & ContentPlaceHolder1_seaTextBox on the page with thier respective labels, how can I modify the script so that it validates against all textboxes?
I tried adding a horrible or statement however this was causing the page to freeze. What s the best method to check against all three textboxes?
You can add class for all inputs, example: validate
After you can create JS function. You can fire this function as you wish.
function check(){
$('.validate').each(function(){
label = $("label[for='"+$(this).attr('id')+"']");
if ((newIndex === 3 && $(this).val() == "")) {
label.show();
return false;
}
else {
label.hide();
}
});
}
function validate(value) {
if ...
//show div
else ...
// hide div
}
$("input[type='text']").each(function(){
//value from input text field
var myval = $(this).val();
//call validation function
validate(myval);
});

Javascript Multiple conditions from two or more functions

Forgive me if this is simple. I'm new to javascript.
I'm trying to make certain divs appear or hide based on the users answer to questions. I've created a function for each question that gets the results of that question based on their value. But I can't get the && additional condition to work. I need the div to appear ONLY if both conditions are true. It doesn't even seem to recognize anything from && and beyond. Q1 also sets some of the text in the div based on the answer. That seems to be working fine.
// Question 1
function analyzeQ1(answerQ1) {
if (answerQ1 == "TMC" || answerQ1 == "CMH" || answerQ1 == "SLH" || answerQ1 == "KU" || answerQ1 == "UMKC") {
document.getElementById('A1').innerHTML = " • Contact Research Administration at "+ answerQ1; + hideStuff('Q1a') + showStuff('A1')
} else if
(answerQ1 == "Other") {
showStuff('Q1a')
}
}
//Question 3
function analyzeQ3(answerQ3) {
if (answerQ3 == "no" && answerQ1 == "TMC") {
showStuff('A3') + hideStuff('Q3a')
} else if
(answerQ3 == "yes") {
showStuff('Q3a')
}
In the first code snippet you have a stray semicolon:
document.getElementById('A1').innerHTML = " • Contact Research Administration at "+ answerQ1;
hideStuff('Q1a');
showStuff('A1');
In the second code snippet you refer to answerQ1 but never pass it in to the function so you need:
//Question 3
function analyzeQ3(answerQ3, answerQ1) {
if (answerQ3 === "no" && answerQ1 === "TMC") {
showStuff('A3') + hideStuff('Q3a')
} else if
(answerQ3 === "yes") {
showStuff('Q3a')
}
Note that I used === vs ==. == is evil and you should forget that it exists in Javascript.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Comparison_Operators

Categories