简体   繁体   English

如何在jQuery中验证动态文本框值

[英]how to validate dynamic text box values in jquery

Thanks in advance.I have a popup window which has a dynamic text box fields.These textboxes will multiple according to the selected combo box values from the first form.The dynamic textboxes are displayed from jquery. 预先谢谢,我有一个弹出窗口,其中包含一个动态文本框字段。这些文本框将根据从第一种形式选择的组合框值进行多个显示。动态文本框从jquery显示。 Please anyone help me how to validate a dynamic text boxes on clicking the submit button. 请任何人帮助我单击提交按钮时如何验证动态文本框。 Actually I have to validate the textboxes before sending the mail. 实际上,我必须在发送邮件之前验证文本框。 I have written a code which will validate only static textboxes. 我已经编写了仅验证静态文本框的代码。 My code as below 我的代码如下

<head>
<script>
  $(document).ready(function () { 
        $(".myformid").click(function(){
        var nameVal = $('.names').val();
        var emailVal = $('.emails').val();
        var phoneVal = $('.phones').val();       
        if(nameVal == "")   
        {
           $('#errmsg').html("<p style='color:red;font-weight:bold'>Please enter the Name</p>");      
        }   
        else if(emailVal == ""){
          //alert("A textbox is required"); 
          $('#errmsg').html("<p style='color:red;font-weight:bold'>Please enter the email Id</p>"); 
        }
        else if(!ValidateEmail(emailVal))
        {
           $('#errmsg').html("<p style='color:red;font-weight:bold'>Invalid Email Id</p>");  

        }
        else if(phoneVal == "")   
        {
           $('#errmsg').html("<p style='color:red;font-weight:bold'>Please enter the Phone Number</p>");

        }
        else if(isNaN(phoneVal))
        {
           $('#errmsg').html("<p style='color:red;font-weight:bold'>Please enter the Valid Phone Number</p>");

        }
        else if(emailVal !="" && phoneVal != "")    
        {
           $('#errmsg').text(" ");

           var username = $('#usernameId').val();
    var length = $('#lengthId').val();    
    var nameArray = [];     
    var emailArray = [];
    var phoneArray = [];
    $('.names').each(function(){
       nameArray.push(this.value);         

    });    
    var nameboxVal = nameArray.join(",");           

    //alert(nameboxVal);     

    $('.emails').each(function(){
       emailArray.push(this.value);

    });
    var emailboxVal = emailArray.join(",");
    //alert(emailboxVal);  

    $('.phones').each(function(){
       phoneArray.push(this.value);   

    });
    var phoneboxVal = phoneArray.join(",");          

    //alert(phoneboxVal);

      $.ajax({

          type: "POST",
          url: "/invl_exams/popSubmit",   
          data: {user:username,name:nameboxVal,email:emailboxVal,phone:phoneboxVal,lengths:length},              
          success: function(result){  

            console.log(result);

            $('#mailSuccess').text('Mail Send Successfully');         
            $('#mailSuccess').fadeOut(5000);
          }

        });


        }

       });

      });

// Passing dynamic textboxes inside the dialog box
    $(".create-user").change(function(){      

        var selVal = $(this).val();         
        $('#lengthId').val(selVal);    
        $("#textboxDiv").html('');    


        if(selVal > 0) {

            for(var i = 1; i<= selVal; i++) {   

              var sno = i;               


               $("#textboxDiv").append('<tr><td>'+sno+'. </td><td>Name:<input type="text" name="names" class="names" value="" required="required" /></td><td>&nbsp;</td><td>Email:<input type="email" name="emails" class="emails" value="" required="required" /></td><td>&nbsp;</td><td>Phone:<input type="text" name="phones" class="phones" value="" required="required" minlength="10" maxlength="16"/><br/></td></tr>');         

            }                            

          }


    });  

  });


</script>
</head>
<body>
  <div id="dialog" title="Enter details to send Mail">   
     <!--<form id="myformid" method="post" action="<?php //echo $this->webroot?>users/sendmail">-->
      <div id="mailSuccess" style="color:#019002;font-weight:bold"></div> 
      <form id="myformid" method="post">     
      <table id="examtable">   
        <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
        </tr>        
        <tr> 
          <div id="textboxDiv"></div>  
          <input type="hidden" name="username" id="usernameId" value="<?php echo $this->Session->read('Auth.User.username'); ?>">
          <input type="hidden" name="length" id="lengthId" value="">                                    
        </tr>
      <tr>
       <td>&nbsp;</td>
       <td>&nbsp;</td>
       <td>&nbsp;</td>
       <td>        
         <!--<input type="submit" name="btnSubmit" value="Submit">-->
        <input type="button" name="btnSubmit" value="Send Mail" id="popSubmit">                           
       </td>        
      </tr>
      </table>
      </form>
    </div>
   </div>
</body>

I don't think any validation is happening at all, whether the elements are static or dynamic. 我认为无论元素是静态的还是动态的,都根本没有进行任何验证。

$(".myformid").click(function(){

will not bind to anything because there are no elements with the class "myformid". 不会绑定任何东西,因为没有任何带有“ myformid” 类的元素。 The "." “。” at the start of a selector indicates a class. 选择器的开头表示课程。

However you do have an element with an id "myformid". 但是,您确实有一个ID为 “ myformid”的元素。 If you change your selector from . 如果从更改选择器。 to # to indicate an id, then it will bind the event to the form. #表示ID,然后将事件绑定到表单。 However, "click" is not the correct event to bind to a <form> element. 但是,“ click”不是绑定到<form>元素的正确事件。 You want to handle the form's "submit" event: 您要处理表单的“ submit”事件:

$("#myformid").submit(function(event){

Lastly, as it stands, your form will do a regular (non-ajax) postback as well as running your function, because the default behaviour of the submit event is not suppressed. 最后,就目前情况而言,您的表单将执行常规(非ajax)回发并运行您的函数,因为未取消submit事件的默认行为。 Add this line as the first line of the above function: 将此行添加为上述函数的第一行:

event.preventDefault();

This will stop a regular postback from happening and allow your validation function to execute. 这将阻止定期回发,并允许您执行验证功能。 At that point you should have a working solution, assuming the logic in your validation code is what you want. 到那时,您应该有一个可行的解决方案,假设您想要的是验证代码中的逻辑。

If your validations are right you just need to attach event in way that dinamicly created elements will be supported too (jQuery on) 如果您的验证正确,则只需要附加事件即可支持动态创建的元素(jQuery on)

$( selector ).live( events, data, handler );                // jQuery 1.3+
$( document ).delegate( selector, events, data, handler );  // jQuery 1.4.3+
$( document ).on( events, selector, data, handler );        // jQuery 1.7+

for example 例如

from

$(".myformid").click(function(){/*Some action*/});

to

$("body").on('click', ".myformid", function(){/*Some action*/});

from

$(".create-user").change(function(){/*Some action*/});

to

$("body").on('change', ".create-user", function(){/*Some action*/});

Small advice: Try to avoid using $("body") selector you can see what is your good dom element witch is parent to your dynamically generated contend/elements. 小建议:尽量避免使用$(“ body”)选择器,您可以看到什么是动态生成的内容/元素的父元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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