2010-04-21 83 views
2

在下面的代碼如何驗證爲只有動態添加文本框即r_score1,r_score2空值.........驗證動態添加文本框

<script> 
    function validate() 
    { 
     //How to validate the r_Score.. textfields 
    } 
    $(document).ready(function() { 
    for(var i=0;i< sen.length;i++) 
    { 
    row += '<input type="text" name="r_score'+i+'" id="r_score'+r_count+'" size="8" />'; 
    } 
    $('#details').append(row); 
    }); 
    </script> 
    <div id="details"><input type="text" name="score' id="score" size="8" /></div> 
    <input type="button" value="Save" id="print" onclick="javascript:validate();" /> 

回答

1

給這個文本框類名和使用類選擇

function validate() 
    { 
     var boxes = $("#details input:text.classname"); 
     boxes.each(function(){ 
      var currentVal = $(this).val(); 
      // do your validation here 
     }); 
    } 
+0

Rahul讓我問你這個,什麼時候使用id,什麼時候使用class? – Hulk 2010-04-21 10:38:49

+0

由於您的ID是動態生成的,因此您必須使用屬性比較運算符來獲取具有特定模式的所有元素。所以在這種情況下,我認爲使用一個類可以更好地識別這些元素。 – rahul 2010-04-21 11:04:21

+0

如果你知道確切的id,那麼使用id選擇器,因爲它是最快的。否則,使用標籤和類選擇器的組合。 – rahul 2010-04-21 11:05:20

0
$("#details input[name^='r_score']").each(function(nr){ 

    if($(this).val() === "") alert("Field "+(nr+1)+" is empty"); 

});