jquery css class javascript how to get the value of checkbox checked item

        In some examples of multiple choice, checkbox is needed, but how to implement it? How does javascript get the value of the checkbox selected item? The main idea is to get all the checkboxes, then traverse which checkboxes are selected, and finally use the value attribute of the checkbox to get the value of the selected checkbox.

 

Just look at an example

<script>
function checkbox()
{
var str=document.getElementsByName("box");
var objarray=str.length;
var chestr="";
for (i=0;i<objarray;i++)
{
  if(str[i].checked == true)
  {
   chestr+=str[i].value+",";
  }
}
if(chestr == "")
{
  alert("Please choose a hobby first~!");
}
else
{
  alert("Your first choice is: "+chesr);
}
}
</script>
Choose your hobby:
  <input type="checkbox" name="box" id="box1" value="跳水" />跳水
  <input type="checkbox" name="box" id="box2" value="跑步" />跑步
  <input type="checkbox" name="box" id="box3" value="Listen to music" />Listen to music
  <input type="button" name="button" id="button" onclick="checkbox()" value="提交" />

 

He will present an option for you to choose, and then press submit, a prompt box will appear showing the option you have selected.

 

working principle:

(1) Use document.getElementsByName("box"); to get all the checkboxes in the HTML document, and the result is an array

 

(2) Traverse the array, each element in the array is a checkbox check box, and judge whether the checkbox is selected by judging the checked attribute of the checkbox. If the checked attribute is true, it means that it is selected. At this time, we can use the value attribute of the checkbox to get the value of the checkbox selected item.

 

There is another example with the same principle but different writing

<input type="checkbox" name="test" value="1"/><span>1</span>
<input type="checkbox" name="test" value="2"/><span>2</span>
<input type="checkbox" name="test" value="3"/><span>3</span>
<input type="checkbox" name="test" value="4"/><span>4</span>
<input type="checkbox" name="test" value="5"/><span>5</span>
<input type='button' value='提交' onclick="fun()"/>
<script>
function fun(){
    obj = document.getElementsByName("test");
    check_val = [];
    for(k in obj){
        if(obj[k].checked)
            check_val.push(obj[k].value);
    }
    alert(check_val);
}
</script>

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326563079&siteId=291194637