简体   繁体   中英

Check in inputs are empty then continue submition

I have a form and I am trying to check if both text fields are empty. If there are empty then do an alert else continue submition but my code is not working.. Any suggestions?

Unfortunately i have to work with this method and not with ajax.

<style>
.highlight{
backgound-color: #F00;  
}
</style>

<script>
$(document).ready(function(){
$("#register-form").submit(function(){
    var isFormValid = true;

    $(".required input").each(function(){
        if ($.trim($(this).val()).length == 0){
            $(this).addClass("highlight");
            isFormValid = false;
        }
        else{
            $(this).removeClass("highlight");
        }
    });

    if (!isFormValid) alert("Please fill in all the required fields (indicated by *)");

    return isFormValid;
});
});
</script>

And inside the body:

<form id="register-form" name="register-form" method="post" action="register.php">
  <p>
    <label for="usenrame"></label>
    <input type="text" name="usenrame" id="usenrame" class="required input" />
  </p>
  <p>
    <label for="passwor"></label>
    <input type="text" name="passwor" id="passwor" class="required input" />
  </p>
  <p>
    <input type="submit" name="submit" id="submit" value="Submit" />
  </p>
</form>

Here in this line

$(".required input").each(function(){

You have made mistake

$("input.required").each(function(){

use this...

Try using:

$("#register-form .required").each(function(){

instead of

$(".required input").each(function(){

This will make sure no other inputs in other <forms> are encroached upon by your jQuery selector.

Your selector appears to be wrong. Currently, your selector is selecting the <input /> element inside of an element that has a class of .required . That does not match your markup.

You can either target an <input /> element with the class of .required like the following:

$('input.required')...

or alternatively target an <input /> element with both an .input and a .required class like the following:

$('.required.input')...

You have made error in the selector.

Either it need to be :

$(".required.input").each(function(){

as it's at the same level

else it need to be

$("input.required").each(function(){

as per your code, you are looking for the children tags input inside .required class

I would suggest using .required alone if you are planning to use select box or textarea in the future. Same selector can be used for all the cases.

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM