[英]Catch all radiobuttons inside a div using jQuery
有人知道如何將所有單選按鈕放入div中嗎? div的ID如下
<div id="quest{{ $groups }}" class="quest">
我正在使用Laravel,因此我的想法是在div中獲取值,並在jQuery中添加類似
var radios = $("input[type='radio'][id^='quest'"+groups+"]");
但這是行不通的,所以我想知道如何在div中獲取所有單選按鈕,並使用.each進行內部循環。
我需要重復一組問題,然后才能進行驗證,但僅適用於第一組,第二組未經驗證,我已經檢查了每個單選按鈕的ID值並更改為previousid_2和調查表被克隆。 另外,我想知道在克隆調查表時如何重置值,因為如果您選擇YES NO YES NO,那么在克隆調查表的第二組中,這些結果也會被選中,並且禁用字段也是如此。
您實際上是在要求幾件事。 您的代碼暗示您可以訪問名為groups
的變量中的當前組。 所以...
1)選擇div內的所有無線電輸入:
var div = $("div#quest"+groups);
var radiosBtns = div.find("input[type='radio']");
2)遍歷它們,並對每個元素做一些工作:
var doSomeWork = function(i,radiobtn){
console.log('the value of radio button #' + i ' is ' + radiobtn.value);
};
$.each(radioBtns,doSomeWork);
3)復制一組單選按鈕:
var fromgroup = $("div#quest"+groups);
var togroup = fromgroup.clone();
var insertionPoint = $('body');
var toGroupId = 'questXXX';
// set the ID so it can be targetted
togroup.prop('id',toGroupId);
// reset radio button values
togroup.find('input[type="radio"]').each(function(){
this.prop('checked',false);
});
togroup.appendTo(insertionPoint);
4)在特定組上運行驗證
var validateGroup = function(elements){
// your validation logic goes here
var isValid = false;
$.each(function(){
console.log( this.name, this.value );
});
return isValid;
};
// run the validation on the newly inserted group
var targetElements = $("#"+toGroupId).find("input[type='radio']");
var groupIsValid = validateGroup( targetElements );
您可以獲取所有單選按鈕並對其進行迭代,如下所示
$("input[type='radio'][id^='quest']").each(function(){
// add your logic here
});
使用ID非常簡單。要獲取以“ quest”開頭的所有元素,應使用:
$("[id^=quest]")
為了得到那些以“詹德”結尾的人
$("[id$=quest]")
完整的答案是
var radios = $("input[type='radio'][id^='quest']");
關鍵是如果要通配類:( :(
$("[class^=quest]")
在像
<pre>
<a class="btn quest primary">link</a>
<pre>
它不起作用,因此當您找到它時,您將需要一個更復雜的通配符,直到我為止:D
事實是,每當需要使用類獲取元素列表時,都將不需要它,只需使用一個通用類即可:D希望我能對您有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.