开发者

Echo value of checkbox checked element in HTML form

I've created an HTML form that has checkboxes that are checked dynamically due to a variable from a previous page (there is only one checkbox checked each time).

What I'd like is to echo the value of this checkbox out (to make the main title of the page so javascript alert is not adapted).

Example :

<html>
    <body>
    <h1>Here I'd like to echo the value of the checkbox that is checked<h1>
    <form id="myform" n开发者_Python百科ame="myform">
       <p>
       <input type="checkbox" name="car" id="porsche" /> <label for="porsche">porsche</label><br />
       <input type="checkbox" name="car" id="ferrari" /> <label for="ferrari">ferrari</label><br />
       </p>
    <script type="text/javascript">

    function loopForm(form,car) {
       var cbResults = 'Checkboxes: ';
       var radioResults = 'Radio buttons: ';
       for (var i = 0; i < form.elements.length; i++ ) {
          if (form.elements[i].type == 'checkbox') {
             if (form.elements[i].id == car) {
                 form.elements[i].checked = true ;
             }
          }
        }
     }
     ...
     // This function will check one of the two checkboxes
     loopForm(document.myform,car);
     </script>
     </body>
     </html>


The best I can do, I'm afraid, is the following:

var inputs = document.getElementsByTagName('input');
var checkboxes = [];

for (i=0; i<inputs.length; i++){
    if (inputs[i].type == 'checkbox' && inputs[i].getAttribute('checked') == 'checked'){
        checkboxes.push(inputs[i].value);
    }
}

document.getElementsByTagName('h1')[0].innerHTML = checkboxes;

JS Fiddle demo.

This is slightly clunky, but does, at least, use plain JavaScript; albeit it does seem to require that the checked checkboxes be marked up as following: checked="checked".


You can use jQuery to achieve this. Listen for the change() event on the checkboxes and change the text() of the h1 when this happens.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜