StealthRT
StealthRT

Reputation: 10542

Setting true/false to if/or statement not working

Hey all i have the following js code to validate a textbox:

function submitContactUs() {
   var canSubmit = true;

   if (($('#cf_name_txt').val() == "") || ($('#cf_name_txt').val().substr(0, 1) == "*") || ($('#cf_name_txt').length == 1)) {
    if (!$('#cf_name_txt').next('img').length) { //image not there yet
        $('#cf_name_txt').after(theErrorIcon + " id=\"errIcon_cfname\" />");
        $('#errIcon_cfname').vibrate(conf);
        canSubmit = false;
        console.log('false name');
    }
   } else {
    $('#errIcon_cfname').remove();
        console.log('true name');
   }

   if (canSubmit) {
        alert(canSubmit);
        //$("#sendDataContactus").click();
   }

When i first click the button to fire off that function i get the correct false but once i hit the button again (without changing anything) it for some reason comes back as being true??? Does anyone see anything wrong with the js to cause it to do that?

The values i get from the first button press is:

false name

The value i get from the second button press is:

messagebox saying true

Upvotes: 0

Views: 212

Answers (1)

Inferpse
Inferpse

Reputation: 4145

When you click second time you already have img tag, so your variable doesn't reset canSubmit = false;

Move your variable assigning outside of creating error code block like this:

 if (($('#cf_name_txt').val() == "") || ($('#cf_name_txt').val().substr(0, 1) == "*") || ($('#cf_name_txt').length == 1)) {

    canSubmit = false;
    ...

Upvotes: 3

Related Questions