SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Apr 2007
    Posts
    63
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    how to read checkboxes issues

    my form has following elements.
    HTML Code:
    <input type="checkbox" name="interest[]" value="2">Shopping
    <input type="checkbox" name="interest[]" value="2">Travel
    Now, how to access , say, first element from javascript?

    document.myFrm.interest[][0].checked doesn't seem to work?

  2. #2
    SitePoint Wizard Mike Borozdin's Avatar
    Join Date
    Oct 2002
    Location
    Edinburgh, UK
    Posts
    1,743
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here is my example:
    Code:
    <html>
    <head>
        <script type="text/javascript">
            function process() {
                var check = document.getElementsByTagName("input");
                for(var i = 0; i < check.length; i++) {
                    if(check[i].type == "checkbox" && check[i].name == "interest[]" && check[i].checked) {
                        window.alert(check[i].value);
                    }
                }
            }
        </script>
    </head>
    <body>
    <form>
    <input type="checkbox" name="interest[]" value="1">Shopping
    <input type="checkbox" name="interest[]" value="2">Travel<br />
    <input type="button" value="click" onClick="process();">
    </form>
    </body>
    </html>
    By the way, don't forget to put different values to checkboxes.

  3. #3
    SitePoint Addict
    Join Date
    Aug 2006
    Posts
    266
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
      
    <script type="text/javascript">
    function check(){
    var el = document.myFrm.elements["interest[]"];
    el[0].checked  = true;
    alert(el[0].value); 
    }
    </script>
    <button onclick="check()"> click me</button>
    <form name="myFrm">
    <input type="checkbox" name="interest[]" value="1" >Shopping
    <input type="checkbox" name="interest[]" value="2" >Travel
    </form>
    Code:
      
    <script type="text/javascript">
    function check(){
    var el, i = 0;
    while(el= document.getElementsByName('interest[]')[i++]){
    if(el.checked) { alert(el.value);}
    }
    }
    </script>
    <form name="myform">
    <input type="checkbox" name="interest[]" value="1" onclick="check()">Shopping
    <input type="checkbox" name="interest[]" value="2" onclick="check()">Travel
    </form>


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •