2014-04-01 42 views
0
<script> 
function no_email_confirm() { 
    if (document.getElementsByName("no_email")[0].checked == false) { 
    return true; 
    } else { 
    var box= confirm("Sure?"); 
    if (box==true) 
     return true; 
    else 
     document.getElementsByName("no_email")[0].checked == false; 
    } 
} 

</script> 

這裏是我的複選框HTML:的JavaScript的onchange複選框仍然選擇在取消

<input type="checkbox" id="no_email" name="no_email" onchange="no_email_confirm()"></input> 

出於某種原因,這給了我確認彈出我第一次選中該複選框,但不之後的任何點擊。另外,即使我點擊「取消」,它仍會檢查複選框。我在這裏搜索,出於某種原因,無論我嘗試什麼,我都無法正常工作。

它應該確認他們是否真的要檢查框,如果他們選擇「是」,那麼它檢查它,如果沒有,那麼它不檢查它。我可以讓它在沒有名稱no_email的情況下工作,但我無法改變這種情況..

任何人有什麼想法?

+0

你還沒有看你的瀏覽器的錯誤控制檯,是嗎?一個NodeList(由'getElementsByName()'返回)沒有'checked'屬性。你需要迭代NodeList,或者指定一個索引來確定你想測試的元素,例如:'document.getElementsByName(no_email)[0] .checked == false' –

+0

所以這將不得不被默認檢查? – will

+0

@DavidThomas我更新了上面的代碼,現在它每次都彈出,但是在選擇取消時它仍然在選中框。這是因爲它沒有被默認選中? – will

回答

1

看起來你在那裏有幾個錯誤,最值得注意的是使用==,當時你的意思可能是=。相反,添加事件偵聽器,並確保分配工作:

var box = document.querySelector('#no_email'); 

box.addEventListener('change', function no_email_confirm() { 
    if (this.checked == false) { 
    return true; 
    } else { 
    var confirmation= confirm("This means that the VENDOR will NOT RECEIVE ANY communication!!!!"); 
    if (confirmation) 
     return true; 
    else 
     box.checked = false; 
    } 
}); 

http://jsfiddle.net/A3VGg/1/

+0

這對jsfiddle有效,但即使只是將它複製並粘貼到它所在的頁面上,也會停止它的工作。我必須檢查出來,其他的東西一定會導致它保持檢查狀態。感謝你的回答! – will

+0

@ willill沒問題。如果我幫助,別忘了接受! – SomeKittens

相關問題