2016-01-20 59 views
-1

This is my HTML code:複選框在<a href> tag

<a id="id_1" name="n_1" href="#" onclick="callFn(this.id);"> 
    <input type="checkbox" name="ck_1" id="xyz"> 
    Click Here 
</a> 

I want to check this checkbox using Javascript code. How to do it??

+1

你的HTML是無效的。錨不能包含交互式元素,包括輸入元素。 – Quentin

+0

我懷疑你的問題的解決方案是「使用標籤元素,而不是錨點」 – Quentin

回答

1

Use <label> instead of <a>.

<label id="id_1" onclick="callFn(this.id);"> 
    <input type="checkbox" name="ck_1" id="xyz"> 
    Click Here 
</labek> 

This is the use of <label> tag. And moreover, you don't need callFn(this.id); at all.

+1

正確的HTML,只是不回答JavaScript問題 – Gavriel

+1

@Gavriel請刪除您的評論。我將添加更多信息。 –

+0

不需要,因爲這是一個重複的問題:) – Gavriel

0

Get the element using its ID:document.getElementById("xyz")

Then change its property checked to true:

document.getElementById("xyz").checked = true;

+2

你的答案可能是正確的,但請多加一點,以便初學者能夠理解你要來的東西。社區想要幫助你,我們努力是最好的,但我們只能理解有意義的問題。嘗試格式化您的問題有點不同之後,您檢查了StackOverflow的幫助中心頁面上如何編寫一個很好的答案。 – OneStig

0

Here is simple DEMO ..希望它有助於

$("#check").click(function() { 
     var checkBoxes = $("#xyz"); 
     checkBoxes.attr("checked", !checkBoxes.attr("checked")); 
    }); 
<label id="id_1" onclick="callFn(this.id);" for="xyz"> 
    <input type="checkbox" name="ck_1" id="xyz"> 
    Click Here 
</labek> 
<br/> 
<button id="check">By button</button>