1

I have checkboxes in html as follows:

    <td><input type="checkbox" name="ChkmemberId" value="D657868" onclick="javascript:saveJobDetails('D657868','1');BindGrid('','Edit');">D657868

<input type="checkbox" name="ChkmemberId" value="M78786" onclick="javascript:saveJobDetails('M78786','1');BindGrid('','Edit');">M78786

<input type="checkbox" name="ChkmemberId" value="D89798" onclick="javascript:saveJobDetails('D89798','1');BindGrid('','Edit');">D89798</td>

I wanted to access checked items of these in javascript.

I tried as follows:

 elm = document.getElementByName("ChkmemberId");

                if (elm != null) {

                    alert('1');
                    var checkBoxes = elm.getElementsByTagName("input");
                    var label = elm.getElementsByTagName("label");
                    alert('2');
                    for (i = 0; i < checkBoxes.length; i++) {
                        if (checkBoxes[i].checked == true) {

                            userID = userID + checkBoxes[i].value + ",";
                        }

                    }
                }
            }

But its not working.

Please help me how can i access checkboxlist in javascript.

5
  • In what way is it "not working"? Commented Apr 11, 2014 at 7:23
  • Its not binding checked items in UserID as userID = userID + checkBoxes[i].value + ","; Commented Apr 11, 2014 at 7:24
  • even its not giving me alerts which i kept for testing Commented Apr 11, 2014 at 7:24
  • What is userID? Where is it declared and what is its initial value? Commented Apr 11, 2014 at 7:26
  • The method you're looking for is getElementsByName(), note the 's' in there. Commented Apr 11, 2014 at 7:29

2 Answers 2

2

You are trying to get child elements from an element who hasn't got any child elements.

var checkBoxes = elm.getElementsByTagName("input");

You want to get all the elements with the same name. After that you want to loop trough them all and put the value in userId.

Try it with this code:

var checkBoxes = document.getElementsByName('ChkmemberId');
for (var i = 0; i < checkBoxes.length; i++) {
    if (checkBoxes[i].checked) {
        userID += checkBoxes[i].value;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

How's this:

var checks = document.getElementsByName("ChkmemberId"),
    check, parts = [],
    userID, i;

for (i = 0; i < checks.length; i += 1) {
    check = checks[i];
    if (check.checked) {
        parts.push(check.value);
    }
}

userID = parts.join(", ");

Working fiddle:

http://jsfiddle.net/EVQwc/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.