Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating textbox when it was shown using jQuery form rules

I have a form which generates textbox when the user selects "others" in dropdown..

Dynamic textbox generation was done and I can able to get the value of "others" textbox.

But my Problem is

1) I want to validate the others textbox when it was shown..

How to do the validation any Suggesstions please..

<form name="f2" id="f2" method="post" action="" enctype="multipart/form-data">
    Type:
    <select name="type"  id="type" onchange='CheckColors(this.value);'> 
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="others">others</option>
    </select>
    <input type="text" name="others" id="others" style='display:none;'/>
    <input type="submit" name="submit"/>
</form>

//Here is the script to validate the form..I want to validate the the other textbox when only it appears..How to do that?

<script type = "text/javascript">
$(document).ready(function () {
    $("#f2").validate({
        debug: false,
        rules: {
            type: {
                required: true
            },
            others: {
                required: true
            },
            messages: {
                //messages for required
            }
        });
    }); 
</script>

I tried the above process but it always shows the required filed two times side by side.

like image 787
PHP CODER Avatar asked Sep 17 '26 12:09

PHP CODER


1 Answers

Try with this

$(document).ready(function () {
  $("#f2").validate({
    debug: false,
    rules: {
      type: {
        required: true
      },
      messages: {
        //messages for required
      }
    }
  });
});  

function CheckColors(value) {
  if(value=='others') {
    $('#others').show().attr('required','required');
  } else {
    $('#others').hide().removeAttr('required');
  }
}

Remove this line from validate function,then the validation works fine

others: {
   required: true
}

DEMO

like image 81
Sridhar R Avatar answered Sep 20 '26 03:09

Sridhar R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!