Question

I have a bootstrap modal box that contains a signup form. I've added some code that makes the modal box disappear when the submit button is pressed:

$(".dismiss-signup-modal").click(function () {
    jQuery('#signup_modal').modal('hide'); }
});

This works fine but I want to make the modal box stay where it is if the phone number field of the signup form is blank and only disappear if the phone number field has a value, something like this:

$(".dismiss-signup-modal").click(function () {

    if ($('.signup-phone').length > 0) {

    jQuery('#signup_modal').modal('hide'); }

    else {}
});

But the above code doesn't do anything, the modal box still disappears if the phone number field is left blank. I've tried every combination I can think of placing the if else statement outside the function or creating a new function or making the .signup-phone into a var but nothing works, any ideas? thanks

Was it helpful?

Solution

You need to check for the length of the value..

But you were checking for the existence of the jQuery object (If the element exists or not)

Supposed to be

   if( $('.signup-phone').val().length > 0 ) {

$('.signup-phone').length will always be greater than one, since that element is pressnton the page. So the condition is always true.

OTHER TIPS

Length on a JQuery object is different than length on a DOM element. JQuery.length gives you the count of elements contained, not the length of the input elements value. So:

$('.signup-phone').length;

should be a value of 1 because a single element was found with the class 'signup-phone'. What you want is actually the length of the elements value instead:

$('.signup-phone').val().length;

I think $('.signup-phone').length is pointing toward the length of the element not the length of it value.

Maybe you could try this:

$(".dismiss-signup-modal").click(function () {

    if ($('.signup-phone').text.length > 0) {
    // or you could use 
    //if ($('.signup-phone').value.length > 0) {
    jQuery('#signup_modal').modal('hide'); }

    else {}
});

EDIT: By Element I mean JQuery Element(s //If the selector is a reference to more than one element).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top