Jquery动态追加验证

时间:2013-04-06 08:28:14

标签: jquery

我有一个下拉菜单,在更改时会在HTML中添加一个文本框。我想在该文本框中添加jQuery验证,并在特定的fieldset id上附加验证。我应该遵循什么流程?

有关上下文,请参阅此JSFiddle。如果用户选择“需要更多房间或有孩子”,然后选择孩子的数量> 0,出现年龄文本框。我想添加验证以确保孩子的年龄在0到9之间。

HTML:

<div id="guestsRooms" class="clear">
    <label class="label1" for="guestsRoomsSelect">Guests:</label>
    <span>
        <span>
            <select id="guestsRoomsSelect" name="GuestsRooms" style="width: 217;       padding: 5px">
                <option value="1-1">1 adult</option>
                <option selected="selected" value="2-1">2 adults in 1 room</option>
                <option value="3-1">3 adults in 1 room</option>
                <option value="4-1">4 adults in 1 room</option>
                <option value="2-2">2 adults in 2 rooms</option>
                <option value="0">Need more rooms or have children?</option>
            </select>
        </span>
    </span>
</div>

 <div id="roomconfig" class="roomconfig_fc">
 <div id="Addition"> 

 </div>


   <div class="btnWrap" style="clear:both;border-bottom: 0.5px solid #FFFFFF;">
<a class="addRoom"  style="background-image:none; color:darkred;height:20px; margin-left:0px" href="javascript:void(0);"><img  src="../Images/SearchBox/image1.png" class="addimage "  />
Add room</a>
</div>    
<input type="submit" value="submit">

</div>

jQuery的:

 $(document).ready(function(){ 
var counter = 0;
var forage = 0;
$('#roomconfig').hide();

    var index = 0;

function childage(){

$('.hc_evt_children').bind("change",function () {  

  var item=(this).id;
  // alert(item);
$parentElement = $(this).parent().parent('div');

var id = $parentElement.attr("class");
  // alert(id);
 var index1 = $("." + id + " input").size();
// alert(index1);

var requested = $(this[this.selectedIndex]).val()
//alert(requested);

 if (requested > index1) {
            for (i = index1; i < requested; i++) {
                var $ctrl = $('<input/>').attr({ type: 'text', name: 'text', value: '',style:'width:30px;' });
               var my=$(this).closest("div"); 
               my.append($ctrl);
                 }
         }
         else if (requested < index1) {
             var x = requested - 1;
               $("." + id +" input:gt(" + x + ")").remove();
          }
   if(requested==='0'){

         $("." + id + " input").remove();
   }

 });
 }
 $('#guestsRoomsSelect').change(function () {

        if ($(this).val() === '0') {

       var $var2 = '<div id="dropdown2_ ' + (counter) + ' " class="class1"> <div class="wrapadults" style="float:left"> <label class="lbl_sm" style="font-size: 0.75em" for="adults">Adults</label>'
                $var2 = $var2 + '<br/><span> <span>     <select id="adults" class="t_adults" style="margin-left:7px;margin-right:7px; border-right: 0.5px solid #FFFFFF;">      <option value="1">1</option>        <option value="2" selected="selected">2</option>'
                $var2 = $var2 + '<option value="3">3</option>       <option value="4">4</option>        <option value="5">5</option>        <option value="6">6</option>        <option value="7">7</option>'
                $var2 = $var2 + '<option value="8">8</option>       <option value="9">9</option>        <option value="10">10</option>      </select>     </span>       </span>  </div>'
                $var2 = $var2 + '<div class="children_'+forage+'" > <label class="lbl_sm" style="font-size: .75em;" for="children">Children</label><br/> <span>  <select id="hc_f_children_' + forage + '" class="hc_evt_children " style="border-right: 0.5px solid #FFFFFF;">'
                $var2 = $var2 + '<option value="0" selected="selected">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option>'
                $var2 = $var2 + '<option value="4">4</option> </select> </span>  </div>   </div>';
                $("#Addition").prepend('<fieldset id="' + counter + '" data-index="' + index + '">' + $var2 + '</fieldset>');
                counter = counter + 1;
                index++;
                forage++;
                $('#roomconfig').show(300);
                 }
        else if ($(this).val() === '1-1' || $(this).val() === '3-1' || $(this).val() === '4-1' || $(this).val() === '2-2' || $(this).val() === '2-1') {

            $('#roomconfig').hide(300);

            $('#Addition fieldset :first').remove();
         }
   childage();


});

 $(".addRoom").click(function () {
        // on add room event

        var $var1 = '<div id="dropdown2_ ' + (counter) + ' " class="class1"> <div   class="wrapadults" style="float:left"> '
        $var1 = $var1 + '<span> <span> <select id="adults" class="t_adults" style="margin-left:7px;margin-right:7px; border-right: 0.5px solid #FFFFFF;">       <option value="1">1</option>        <option value="2" selected="selected">2</option>'
        $var1 = $var1 + '<option value="3">3</option>       <option value="4">4</option>        <option value="5">5</option>        <option value="6">6</option>        <option value="7">7</option>'
        $var1 = $var1 + '<option value="8">8</option>       <option value="9">9</option>        <option value="10">10</option>      </select>     </span>       </span>  </div>'
        $var1 = $var1 + '<div class="children_'+forage+'" > <span>  <select id="hc_f_children_' + forage + '" class="hc_evt_children " style="border-right: 0.5px solid #FFFFFF;">'
        $var1 = $var1 + '<option value="0" selected="selected">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option>'
        $var1 = $var1 + '<option value="4">4</option> </select> </span>  </div> <div id="chileage_'+forage+'" class="ch"></div>  </div>'
        $var1 = $var1 + '<div class="btnrmv" id="' + counter + '" > <a class="removeRoom " style=" width:30px; height:0px; margin:0px;left:200px;position:relative; top:-30px; background-image:none; color:#b11500;font-weight:normal;font-size:0.77em;" href="javascript:void(0);">remove<span></span> </a> </div>';

        $("#Addition").append('<fieldset id="' + counter + '" data-index="' + index + '"' + $var1 + '</fieldset>');

        counter++;
        index++;
        forage++;
        // for remove element
        $(".btnrmv").click(function () {
            $("#roomconfig fieldset#" + this.id).remove();
            counter--;

        });

       childage();

});
});

2 个答案:

答案 0 :(得分:1)

您可以在创建文本框时添加诸如class: "age"之类的类,然后单击提交按钮的单击侦听器,该按钮将使用each函数检查每个类。

我在这里添加了一个示例:http://jsfiddle.net/pYRj3/32/

答案 1 :(得分:0)

您的代码非常复杂,因此我将提供更适合您情况的通用代码示例。

在初始化插件之后添加/删除规则的主要方法是使用插件内置的方法...

  • rules('add')
  • rules('remove')

请参阅所有文档:http://docs.jquery.com/Plugins/Validation#Plugin_methods


要向动态创建的字段添加规则,您可以在创建字段后立即使用the rules('add') method

$('[name="Field2"]').rules('add', {
    required:true,
    messages: {
        required: "Custom message."
    }
});

或者对于许多新字段,请使用“starts with”选择器和.each ...

$('[name^="Field"]').each(function() {
    $(this).rules('add', {
        required:true,
        messages: {
            required: "Custom message."
        }
    });
});

此方法的简单演示:http://jsfiddle.net/xCY4T/1/


更简单的方法是使用the addClassRules method 创建 class。它可以包含一个规则或规则组合(规则组合称为“复合规则”)。

$.validator.addClassRules("MyRule", {
    required: true,
    range: [0, 9],
    // another rule, etc.
});

然后,当您创建新字段时,只需确保它们各自包含class="MyRule"和唯一name,当然。

<input type="text" name="Field1" class="MyRule" />
<input type="text" name="Field2" class="MyRule" />

此方法非常简单,但默认消息没有覆盖。

简单演示:http://jsfiddle.net/xCY4T/3/