2017-06-13 64 views
0

有一個複選框值。當更改複選框的值時,我向用戶詢問「你想在網站上顯示這個項目嗎?」或者「你想隱藏網站上的這個項目嗎?」複選框包含確認並保留原始複選框值如果取消

它工作正常。但問題是取消選項。如果用戶勾選複選框,確認框將出現「您想在網站上顯示此項目嗎?」。但即使用戶選擇取消它也會標記爲選中狀態。即使我使用document.getElementsByName("product").checked = false;再次打開,這是行不通的。

JS小提琴https://jsfiddle.net/9mvrfuyd/7/

注:請沒有jQuery的解決方案。只有純粹的JavaScript。

HTML

<input type="checkbox" name="product" onchange="change_property_status(this.checked);">Option 1 

的JavaScript

function change_property_status(status){ 
    if(status){ 
    status = 1; 
    var con_message = confirm("Do you want to SHOW this item on website?"); 
    if(!con_message){ 
     document.getElementsByName("product").checked = false; 
     return false; 
    } 
    } else { 
    status = 0; 
    var con_message = confirm("Do you want to HIDDEN this item on website?"); 
    if(!con_message){ 
     document.getElementsByName("product").checked = true; 
     return false; 
    } 
    } 

} 

更新:我沒有使用id屬性爲複選框,但我用getElementsByName。所以這不是問題。

回答

2

只是缺少[0]getElementsByName()

document.getElementsByName("product")[0].checked = true; 

Updated jsFiddle

getElementsByName()方法返回所有元素的集合中 具有指定名稱(名字 屬性的值)的文件,作爲一個節點列表對象。

NodeList對象表示一組節點。節點可以通過索引號訪問 。索引從0開始。

0

在輸入標籤內添加id =「product」。

+0

他使用getElementsByName –

+0

哦!剛剛注意到。我會再檢查一次。 – Rebecca

0

試試這個它會幫助你

HTML

<input type="checkbox" id="product" name="product" onchange="change_property_status(this.checked);">Option 1 

的Javascript

function change_property_status(status){ 
    if(status){ 
    status = 1; 
    var con_message = confirm("Do you want to SHOW this item on website?"); 

    if(con_message == false){ 
     document.getElementById("product").checked = false; 
     return false; 
    } 
    } else { 
    status = 0; 
    var con_message = confirm("Do you want to HIDDEN this item on website?"); 
    if(con_message == false){ 
     document.getElementById("product").checked = true; 
     return false; 
    } 
    } 
} 
+0

不工作...............我不認爲使用'getElementByName'而不是'getElementById'有問題。 –

+0

我已經在你的jsfiddle中檢查過它正在工作...... !!! :) –

1

我認爲getElementsByName返回列表元素,因此您需要爲其添加索引。 document.getElementsByName("product")[0].checked = false;

+2

現場演示仍然缺少'[0]' –