简体   繁体   中英

pass the checked checkbox value in javascript

This is the checkboxes in my HTML:

<input type="checkbox" name="sides" id="1" value="French Fries" >French Fries<br />
<input type="checkbox" name="sides" id="2" value="Baked Potato">Baked Potato<br />
<input type="checkbox" name="sides" id="3"  value="Cole Slaw">Cole Slaw<br />
<input type ="button" value = "Enter my side dish selections" onclick="checkbox(sides.value1,sides.value2)"/>

What i want is when the user clicks the button, it should take first two checked boxes and then display it as:

function checkbox(dish1,dish2) {
  document.getElementById("side_one").innerHTML = dish1;
  document.getElementById("side_two").innerHTML = dish1;
}

I am confused on how to do this, can you please help me here.

You can select the first two checked inputs with [...document.querySelectorAll( ":checked" )].slice( 0, 2 ); .

What it does is to create an Array from a NodeList made of all the elements that matches the:checked pseudo-class and slice it in an new Array of two items.

Then you just need to grab the .value of the found <input> elements:

 document.querySelector('[type="button"]').onclick = (evt) => { const checked = [...document.querySelectorAll( ":checked" )].slice( 0, 2 ); checkbox( ...checked.map( (input) => input.value ) ) }; function checkbox(dish1 = "", dish2 = "") { document.getElementById("side_one").innerHTML = dish1; document.getElementById("side_two").innerHTML = dish2; }
 <input type="checkbox" name="sides" id="1" value="French Fries" >French Fries<br /> <input type="checkbox" name="sides" id="2" value="Baked Potato">Baked Potato<br /> <input type="checkbox" name="sides" id="3" value="Cole Slaw">Cole Slaw<br /> <input type ="button" value = "Enter my side dish selections"/> <p id="side_one"></p> <p id="side_two"></p>

If you want it to search only in the content of a specific element, you just need to make the CSS selector in querySelectorAll more specific.

You can use something like the following:

Array.from(document.getElementsByName('entree')).filter(input => input.checked).map(input => input.value)

This makes an array out of node list of interest, filters out all unchecked elements and returns an array that will have zero or more values depending on what is checked. You can then .join() it or otherwise do as you see fit.

基本上,收音机是一个节点列表,所以你可以这样做

const radioValue = (radio.length > 0) ? radio[0].value : "";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM