Search code examples
javascriptjqueryhtmlformsurl-validation

Jquery validating not empty and is URL in forms


I'm using the following fiddle to create a form and check that both fields are not empty and that the second field is a valid URL. http://jsfiddle.net/nc6NW/366/

<form method=post>
     <input type="text" id='first_name'>
     <input type="url" id='second_name'>
     <input type="submit" value="Submit" id="submit" disabled>
</form>

<script>
$(':text').keyup(function() {
     if($('#first_name').val() != "" && $('#second_name').val() != "") {
           $('#submit').removeAttr('disabled');
}    else {
           $('#submit').attr('disabled', true);   
     }
});

</script>

However it only works when you return to amend the first field after adding the URL


Solution

  • The :text is the issue.

    Update your jQuery to the below

    $("input").keyup(function() {
       if($('#first_name').val() != "" && $('#second_name').val() != "") {
          $('#submit').removeAttr('disabled');
       } else {
          $('#submit').attr('disabled', true);   
       }
    });