获取复选框的值并以特定格式显示

时间:2019-02-13 16:57:06

标签: javascript html css

我正在尝试在复选框中获取选中的值,并使用javascript以某种特定格式显示它,但是不知何故,我不知道怎么做

我尝试使用html和javascript,但我不知道ajax或jquery,所以我只尝试使用javascript

function Hobby()
{

          var checkedValue = null; 
          var inputElements = document.getElementsByClass('messageCheckbox');
          for(var i=0; inputElements[i]; ++i){
            if(inputElements[i].checked){
                checkedValue = inputElements[i].value
                 document.getElementById("hobbies_value").innerHTML = inputElements;

                      break;
             }
           }         

}
 Hobby   <input class="messageCheckbox" type="checkbox" name="painting" id="painting" value="painting">Painting
<input class="messageCheckbox" type="checkbox" name="dancing" id="dancing" value="dancing">Dancing
  <input class="messageCheckbox" type="checkbox" name="sports " id="sports " value="sports ">Sports  
  <input type="button" value="student_submit" onclick="Hobby()"><br/>

如果选中的值为跳舞绘画

然后输出应为

爱好:#dancing#painting

并且我不想将其显示为警报框,而是希望将其显示在同一页面上

1 个答案:

答案 0 :(得分:2)

您需要连接值并在循环外显示它们。像这样:

function Hobby()
{

      var checkedValue = ""; 
      var inputElements = document.getElementsByClassName('messageCheckbox');
      for(var i=0; inputElements[i]; ++i){
          if(inputElements[i].checked){
              checkedValue += "#"+inputElements[i].value
                 
           }
      }         
      document.getElementById("hobbies_value").innerHTML = checkedValue;

}
Hobby   <input class="messageCheckbox" type="checkbox" name="painting" id="painting" value="painting">Painting
<input class="messageCheckbox" type="checkbox" name="dancing" id="dancing" value="dancing">Dancing
  <input class="messageCheckbox" type="checkbox" name="sports " id="sports " value="sports ">Sports  
  <input type="button" value="student_submit" onclick="Hobby()"><br/>
Javascript code is
<div id="hobbies_value"></div>