Hello,

I am trying to print all the selected checkbox values to a textbox separated by commas (, ). However, the first value in the textbox always starts with a comma (, ) i.e. (, one, two, three) etc. My current script trys to check if the first 2 characters (substring) are ", " (comma then space) then attempts to remove them. However this hasn't worked and I have no idea what to try next.

<head>
<script type="text/javascript">
function list(c,n,z) {
s=document.form.marktext.value;
if (c.checked) {
if (s.indexOf(n)<0) s+=', '+n;
} else {
s=document.form.marktext.value.replace(', '+n,'');
}
z=", ";
if (s.substring(2) == z) s=s.substring(2);
document.form.marktext.value=s;}
</script>
</head>

<body>
<form name="form">
<input type="text" value="" name="marktext"><br>
<input type="checkbox" name="mark" onclick="list(this,'Word')">Word<br>
<input type="checkbox" name="mark" onclick="list(this,'Type')">Type<br>
<input type="checkbox" name="makr" onclick="list(this,'Other')">Other<br>
</form>
</body>

Thanks

Chris

why not use a function like

function getchecked() {
    var newtxt = '';
    var chkbx = document.getElementsByTagName('input');
    for(var i = 0; i < chkbx.length; i ++) {
        if(chkbx[i].type == 'checkbox' && chkbx[i].checked === true) {
            if(newtxt.length !== 0) {
                newtxt += ',';
            }
            newtxt += chkbx.innerHTML;
        }
    }
    document.form.marktext.value = newtxt;
}

run that on your onclick event and bobs your uncle

it would be better to set a value for each checkbox instead of getting the innerHTML all the time

I see a spelling error in the name of the third checkbox.

Hi, thanks for the replies,

I will try that code posted above. Thanks

The code is part of a webspace explorer system, each checkbox is given a value based on the path of the item being selected. Any number of checkboxes may be displayed all with a unique value. The javascript is so that the user is able to see which checkboxes have been selected in case a mistake is made. The HTML I provided was just an example, which I typed directly, sorry I made a spelling mistake.

Thanks again, Chris

how to make the reverse of this process how to populate checkboxes according to the comma seperated values in textbox say say i have typed 1,2 in textbox then 1& 2 checkboxes will got be checked

do you plz provide me help in that

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.