1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Form submits when input is null

Discussion in 'jQuery' started by makamo66, Nov 25, 2016.

  1. #1
    I want to prevent form submission when there is no input in the text boxes but the form submits even when the input is empty. How do I fix this?
    SEMrush
    <input type="text" size="30" id="zip" name="zip"><br />
    <input type="text" size="30" id="phone" name="phone">
    
    var input = $("#zip").val();
    var input1 = $("#phone").val();
    
    if ( $.trim(input).length == 0 || $.trim(input1).length == 0 ){
        event.preventDefault();
        }
    Code (JavaScript):
    <button type="submit" class="btn btn-success">Continue</button>
     
    Last edited by a moderator: Nov 25, 2016
    makamo66, Nov 25, 2016 IP
    SEMrush
  2. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,630
    Likes Received:
    724
    Best Answers:
    152
    Trophy Points:
    470
    #2
    It's because you haven't wrapped it in a function-call, and "event" is not defined. This works:
    $('button[type=submit]').click(function(event) {
    var input = $("#zip").val();
    var input1 = $("#phone").val();
    console.log(input.length);
    if ( $.trim(input).length == 0 || $.trim(input1).length == 0 ){
    event.preventDefault();
    }
    })
    Code (JavaScript):
     
    PoPSiCLe, Nov 25, 2016 IP
  3. makamo66

    makamo66 Member

    Messages:
    112
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    26
    #3
    Thank you PoPSiCle
     
    makamo66, Nov 26, 2016 IP