2017-07-14 16 views
0

我想建立一個網頁,將有對象前的列表: -obj1 -obj2 -obj3 而且每次都會有一個複選框。我在構建函數時遇到了問題,該函數將返回已檢查的所有框的值。的Javascript如何建立一個返回已檢查值的複選框列表

這裏是我的代碼,我覺得我很接近,但它不工作:

function myFunction() { 
 
    var x = document.getElementById("objs").value; 
 
    document.getElementById("demo").innerHTML = x; 
 
}
OBJ1: <input type="checkbox" id="obj1" value="1"> 
 
OBJ2: <input type="checkbox" id="obj2" value="2"> 
 
OBJ3: <input type="checkbox" id="obj3" value="3"> 
 
<p>Click the "Try it" button to display the value of the value attribute of the checkbox.</p> 
 
<button onclick="myFunction()">Refresh</button> 
 
<p id="demo"></p>

+0

'getElementById(「objs」)'這應該得到什麼元素? – j08691

+0

它應該得到一個指定的輸入的ID,但我試圖讓它可用於所有的輸入對象沒有成功 – Bruno

+0

@ j08691不幸的是,你提供的鏈接回答了一個不同的情況。 –

回答

0

您可以使用querySelectorAll來獲取在檢查了所有的複選框,使用有效的選擇(而不是你的「OBJ文件」,這是無效的,因爲沒有這樣的元素):

function myFunction() { 
 
    var selected = Array.from(document.querySelectorAll("input[type=checkbox]:checked")) 
 
         .map(function(checkbox) { return checkbox.value; }) 
 
         .join(' '); 
 

 
    document.getElementById("demo").innerHTML = selected; 
 
}
OBJ1: <input type="checkbox" id="obj1" value="1"> 
 
OBJ2: <input type="checkbox" id="obj2" value="2"> 
 
OBJ3: <input type="checkbox" id="obj3" value="3"> 
 
<p>Click the "Try it" button to display the value of the value attribute of the checkbox.</p> 
 
<button onclick="myFunction()">Refresh</button> 
 
<p id="demo"></p>

0

可能的解決方案。

const btn = document.getElementById('btn'); 
 

 
btn.addEventListener('click',() => { 
 
    const elems = document.querySelectorAll('input[type="checkbox"]:checked'); 
 
    console.log(Array.from(elems).map(c => c.value)); 
 
})
OBJ1: <input type="checkbox" id="obj1" value="1"> 
 
OBJ2: <input type="checkbox" id="obj2" value="2"> 
 
OBJ3: <input type="checkbox" id="obj3" value="3"> 
 
<p>Click the "Try it" button to display the value of the value attribute of the checkbox.</p> 
 
<button id='btn'>Refresh</button> 
 
<p id="demo"></p>

0

不清楚自己在輸出方面尋找,但這個讓你已籤的複選框的值

function myFunction() { 
 
    var x = document.getElementsByClassName("objs"); 
 
    var s=''; 
 
    for (var i = 0;i<x.length;i++){ 
 
     if (x[i].checked) s = s + x[i].value; 
 
    } 
 
    
 
    document.getElementById("demo").innerHTML = s; 
 
}
OBJ1: <input type="checkbox" class="objs" value="1"> 
 
OBJ2: <input type="checkbox" class="objs" value="2"> 
 
OBJ3: <input type="checkbox" class="objs" value="3"> 
 
<p>Click the "Try it" button to display the value of the value attribute of the checkbox.</p> 
 
<button onclick="myFunction()">Refresh</button> 
 
<p id="demo"></p>

相關問題