2016-05-02 79 views
1

我有一個基於SQL表中的數據創建的表單。它在做什麼來尋找所有「用戶」,即「所有者」,「經理」和「員工」。用戶將撰寫調查表,然後將其發送給任何一組人或個人。爲什麼這個jquery函數每頁觸發一次刷新?

在div中where id =「surveyList」,我有三個名爲「All_Owners」,「All_Managers」和「All_Staff」的標題複選框。在這些標題的每一個下,都有名稱爲「Owners_#OwnerId#」的複選框(其中#OwnerId#是該表中該個人的唯一ID)。

我想讓創建調查的用戶能夠檢查標題複選框,並讓它檢查/取消選中該標題下的所有單個複選框。這是我迄今爲止建立的jQuery。

//Another post lead me to target the input box this way, but same issue. 
$("#surveyList").on("click", "input[name*='All_']", function(){ 
    var $this = $(this); 
    //This grabs the value "Owner", "Manager" or "Staff" 
    var sectionChecked = $this.attr("name").replace("All_", ""); 

    //Check if the header is checked, and then apply that value to each of the individuals that matches that heading.  
    if ($this.is(":checked")) { 
    $("input[name*='" + sectionChecked + "_']").attr("checked", true); 
    } else { 
    $("input[name*='" + sectionChecked + "_']").attr("checked", false); 
    } 
}); 

就目前來看,這段代碼每頁工作兩次。單擊標題一次將檢查該標題下的所有用戶,然後類似地,取消選中它也是一樣的。它適用於所有三個標題(On和Off),但未能在隨後的點擊中觸發。我已經在每行代碼之間放置了一個alert(),並且它總是正常啓動。

任何人都可以看到我錯過了什麼以及爲什麼在第一次打開/關閉後它不能繼續工作?提前致謝。

編輯: 對於那些要求HTML,有一個coldfusion輸出循環產生用戶的複選框。

<div id="surveyList"> 
    <input type="checkbox" name="All_Owners" value="1"></td> 

    <cfoutput query="qGetOwners"> 
    <input type="checkbox" name="Owners_#qGetOwners.id#" value="1"></td> 
    </cfoutput> 

    <input type="checkbox" name="All_Managers" value="1"></td> 

    <cfoutput query="qGetManagers"> 
    <input type="checkbox" name="Managers_#qGetManagers.id#" value="1"></td> 
    </cfoutput> 

    <input type="checkbox" name="All_Staff" value="1"></td> 

    <cfoutput query="qGetStaff"> 
    <input type="checkbox" name="Staff_#qGetStaff.id#" value="1"></td> 
    </cfoutput> 

</div> 
+0

請分享HTML。 – BenG

+0

而不是'alert(...);'彈出窗口,在你的代碼中放置一個'debugger;'語句來判斷髮生了什麼。 –

回答

2

第一件事我會嘗試的,而不是使用使用propattr嘗試。

if ($this.is(":checked")) { 
    $("input[name*='" + sectionChecked + "_']").attr("checked", true); 
} else { 
    $("input[name*='" + sectionChecked + "_']").attr("checked", false); 
} 

到:

從改變你的代碼

if ($this.is(":checked")) { 
    $("input[name*='" + sectionChecked + "_']").prop("checked", true); 
} else { 
    $("input[name*='" + sectionChecked + "_']").prop("checked", false); 
} 
+1

而且解決了這個問題。我感到奇怪的是,attr爲第一次迭代工作,但不是後來的。非常感謝! –

+2

你可以很容易地省去'if':'$(「input [name * ='」+ sectionChecked +「_']」)。 '或甚至:'$(「input [name * ='」+ sectionChecked +「_']」)。prop(「checked」,this.checked);' –

+0

@DavidThomas哇...你花了5行1.完全相同。謝謝。 –

0

聽起來像點擊在DOM樹中冒泡,並且發射的次數超過了你想要的。嘗試看看stopPropagation。你可以使用這樣的:

$("#surveyList").on("click", "input[name*='All_']", function (event){ 
    event.stopPropagation(); 
    var $this = $(this); 
    // .. the rest of your code 
}); 
+0

這是一個有趣的想法,我可能從來沒有拿出自己。但是,我確實嘗試過,並且得到完全相同的結果。 –

+2

你不能使用'on()'來防止冒泡,因爲它會根據該事件冒泡到祖先元素來觸發相關的函數;在該祖先檢測到事件時,它已經完成冒泡。 –

相關問題