編輯:聯繫prof;我不是實際上 [假設]在此任務上使用jQuery,因爲表單上的操作(例如prof的網站)不允許。對所有那些回答如此迅速和有益的人來說,Tyvm是個好主意。因此,我對純粹的原生JS soln 感興趣。來解決這些困難:Javascript - RadioButton,onClick不使用僅切換原生JS的複選框
獲取一組複選框,根據用戶在面向DOM的表單中單擊「是」或「否」單選按鈕來打開或關閉。下面是在HTML中的職位提供
我:)單選按鈕
<label> Subscribe to our Mailing List? </label>
<input type="radio" name="raydeo" id="rad1" value="Yes" onclick="subscribe()"></input>
<label>Yes</label>
<input type="radio" name="raydeo" id="rad2" value="No" onclick="subscribe()"></input>
<label>No</label>
II)複選框
<fieldset>
<legend>Mailing List Subscriptions</legend>
<br />
<input type="checkbox" name="mailinglist" value="Corporate Press Release Emails" id="cor"></input><label> Corporate Press Release Emails</label>
<br />
<input type="checkbox" name="mailinglist" value="Upgrade Software Advertising List" id="sof"></input><label> Upgrade Software Advertising List</label>
<br />
<input type="checkbox" name="mailinglist" value="List given to spammers after buyout" id="lspa"></input><label> List given to spammers after buyout</label>
<br />
<input type="checkbox" name="mailinglist" value="The only non-cynical list" id="cyn"></input><label> The only non-cynical list</label>
<br />
<input type="checkbox" name="mailinglist" value="List to sell to spammers" id="tos"></input><label> List to sell to spammers</label>
<br />
<input type="checkbox" name="mailinglist" value="Spam List" id="spal"></input><label> Spam List</label>
<br />
</fieldset>
使用理由:(I:單選按鈕,II:複選框)。如Populating Checkboxes Based on Radio Button Click,仍然使用jQuery的,但迄今爲止我做過的最好的嘗試是:
<script>
function subscribe(){
//var yesPlease = document.getElementById("rad1");
//var noThx = document.getElementById("rad2");
var arr = new Array["cor", "sof", "lspa", "cyn", "tos", "spal"];
//var hold = document.getElementById(arr[i]);
//if(hold.getAttribute(arr[i]).checked = true && arr[i] >= 1){
//document.getElementById("cor").innerHTML=hold.getAttribute("checked");
var hold = document.getElementsByName("mailinglist")[0];
for(var i = 0; i < arr.length; i++)
{
if(document.getElementById("rad1").checked==true)
{
hold.getAttribute(arr[i]).checked == true;
}
else if(document.getElementById("rad2").checked==true)
{
hold.getAttribute(arr[i]).checked == false;
}
}
}
</script>
當我加載我的文檔並點擊其中一個時,沒有任何反應。下面是有關部分的截圖,如果有幫助:感謝:
使用(yesPlease.checked)改爲只(yesPlease.checked ==真)由於單選按鈕是檢查返回boolean值。 – Pranav
不是問題,而是'$('input [type =「checkbox」] [name =「mailinglist」]')。prop(「checked」,true);'會在一行中執行所有複選框... – nnnnnn