2014-01-30 17 views
0

我基本上是這樣的設置:使用jQuery來算嵌套在DIV所有輸入

<div id="container"> 
    <div class="field_shell"> 
     <label for="name">Name</label> 
     <input type="text" name="name" id="name" class="field"> 
    </div> 
    <div class="field_shell"> 
     <label for="age">Age</label> 
     <input type="text" name="age" id="name" class="field"> 
    </div> 
</div> 

除了規模較大,有三組#container,每個#container拿着幾個(和不同數量)div.field_shell元素。大多數div.field_shell只保存一個輸入,但少數保存兩個獨立的輸入元素。

我的問題是我如何計算每個#content中輸入元素的數量。獎勵積分,讓您瞭解檢查每個#container div中的每個輸入是否已填充的最佳方法,如果是,則返回特定結果。

我認爲.length在這裏是可行的,但我很難過。特別是在檢查每個#container的「狀態」時(狀態,我的意思是如果在該#container內的每個輸入都被填充,而不是空的)。

謝謝你們這麼多,通過閱讀,並感謝你更多的幫助:)

+0

在您的html中,我沒有看到#content –

+0

您可能獲得了輸入元素的長度,如果未填充,則爲0。 –

回答

0

試試這個代碼,

<script> 
    $(document).ready(function() { 
     var FieldShellelements = $("#container .field_shell"); 
     for (i = 0; i < FieldShellelements.length; i++) { 
      alert($(FieldShellelements[i]).children('input').length); 
     } 
    }); 
</script> 
1

我假設你想使用jQuery,我已經改變你的HTML代碼有點讓它工作。 Ids應該是唯一的。

<div id="container"> 
    <div class="field_shell"> 
     <label for="name">Name</label> 
     <input type="text" name="name" id="name" class="field"/> 
    </div> 
    <div class="field_shell"> 
     <label for="age">Age</label> 
     <input type="text" name="age" id="age" class="field"/> 
    </div> 
</div> 

和jQuery代碼每個#container來算,它會遍歷DOM樹,並返回如果你想檢查填充輸入元素匹配input

var inputs = $("#container").find($("input")); 
console.log(inputs.length) 

,所有的元素,你可以看看在element.length屬性。爲了計算多個容器,您可以運行一個循環來處理每個#container並嵌套上面的代碼。

0

演示FIDDLE

我希望這是你想要

HTML

<div id="container"> 

<div class="field_shell"> 

    <label for="name">Name</label> 
    <input type="text" name="name" id="name" value="demo" class="field"> 

</div> 

<div class="field_shell"> 

    <label for="age">Age</label> 
    <input type="text" name="age" id="name" class="field"> 

</div> 

</div> 

jQuery的

var count=0; 
$('#container').find('input[type="text"]').each(function(){ 
    if ($.trim($(this).val()).length) { 
     count+=1 
     alert("Filled Value="+$(this).val()); 
    } 
}); 
alert("Total Input Count="+$('#container').find('input[type="text"]').length+"//Filled Inputs Count="+count); 
0

您應該TR什麼y以使ID在頁面上保持唯一,因爲$("#container")將僅匹配第一個實例(而$("[id='container']")將拾取所有這些)。

// Gather all containers that have all inputs filled 
var allInputsFilled = $("[id='container']").filter(function() { 
     var allFilled = true, 
      inputs = $(this).find("input"); 

     inputs.each(function() { 
      // !val() equates to true when the value is empty 
      // '' is a falsy value, inverted with ! not operator 
      if (!$(this).val()) { 
       allFilled = false; 
       return false; // break out of loop early 
      } 
     }); 

     return allFilled; 
    }); 

allInputsFilled將包含所有#container的div有他們所有的投入填補。 Demo