user3430205
user3430205

Reputation: 79

jquery form validation with submit button

i'm on my web site project and it seems that my jquery function doesn't work .i have to validate this:if the user enters <<nom de famille du pere>>,<<prenom du pere>> has to be entered too.This is my html code:

<div class="form-group">
<div class="col-md-6">
  <label class="col-md-4 control-label" for="father">Nom de famille  du père </label>  
  
  <input id="father" name="father" type="text"  class="form-control input-md" >
  </div>   
</div><br/><br/><br/>

<div class="form-group">
<div class="col-md-6">
  <label class="col-md-4 control-label" for="ffather">Prénom du père</label>  
  <input id="ffather" name="ffather" type="text"  class="form-control input-md">
   </div>  
</div><br/><br/><br/>

and this is my jquery function :

$(document).ready(function() {
$('#father').submit(function() {
  if ($(this)).is(':empty')) {
	 $('#ffather').prop('required',false);  
	
	 
}
else{
	$('#ffather').prop('required',true);  
	 
	
}}  }

Upvotes: 0

Views: 58

Answers (2)

Touhid Alam
Touhid Alam

Reputation: 343

You are trying to set the attributes upon form submission, which is not the right way to do it. You should only check if the fields satisfy the requirements on submit. Defining the constrains should be on the markup. If you are not using any custom form validator, you can use HTML constrain validation. Examples can be found here http://www.w3schools.com/js/js_validation.asp

Again, the jQuery submit event can ONLY be attached to form elements. Review here https://api.jquery.com/submit/

Upvotes: 1

Sam Battat
Sam Battat

Reputation: 5745

DEMO: http://jsfiddle.net/Lfnrrdfu/1/

you have a few mistakes in your code:

$('#father').on('keyup', function () {
    if (!$(this).val()) {
       $('#ffather').prop('required',false);  
    }
    else{
      $('#ffather').prop('required',true);  
    }
    console.log($('#ffather').prop('required'));
});

You can't use submit event with an input, submit is for a form, you could use the form but then you have to prevent default then check the value of the input.

Upvotes: 1

Related Questions