1

HTML:

<select id="id_myselect" name="myselect">
   <option value="0">---------</option>
   <option value="1">1</option>
   <option value="7">2</option>
   <option value="10">3</option>
</select>

<select id="id_book" name="book">
   <option value="0">---------</option>
   <option value="1">Book1</option>
</select>

<input id="id_number" name="number" type="number" />
<div id="add_button">Add</div>

How to check if my form is valid after click on add_button and if is not than change color of input/select?

My try with jQuery:

if($( "#id_myselect option:selected" ).val() == 0){
       $("#id_myselect").addClass( "error" );
    }
else if($( "#id_book option:selected" ).val() == 0){
       $("#id_book").addClass( "error" );
}    

else if($( "id_number" ).val() <= 0){
       $("#id_number").addClass( "error" );
}

2 Answers2

1

Try this on clicking of a div like

$(function(){
    $('#add_button').on('click',function(){
        if($( "#id_myselect" ).val() == 0){// remove option:selected
           $("#id_myselect").addClass( "error" );
        }else if($( "#id_book" ).val() == 0){// remove option:selected
           $("#id_book").addClass( "error" );
        }    
        else if($( "#id_number" ).val() <= 0){
           $("#id_number").addClass( "error" );
        }
    });
});

Demo

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

onclick of add_button Check $('.error').length. If it is zero then there is no error:

 $('#add_button').on('click',function(){
     if($('.error').length!=0){
        console.log('Error exist');
     }
 });

And when it comes to changing color, add css to .error class.

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125