1

I have a jquery variable that is storing a comma separated list of id names. I need help writing something in jquery that separates that variable and uses those values to populate a forms checkbox values when the page loads.

so my jquery variable is $storedFormValues that is a comma separated list of values "checkbox1, checkbox, etc."

and my form

<form name="formname" id="formid">
<input type='checkbox' class='catcheck' id='checkbox1' value='checkbox1' name='catselect' />Checkbox 1
<input type='checkbox' class='catcheck' id='checkbox2' value='checkbox2' name='catselect' />Checkbox 2
<input type="submit" name="submit" value="Submit" />
</form>

Any help would be greatly appreciated!

0

3 Answers 3

2

This should do it:

var $storedFormValues = "checkbox3,checkbox5";

$(function() {
    $.each($storedFormValues.split(","), function(intIndex, objValue) {
        $("#" + objValue).attr("checked", "true");
    });
})

See the fiddle: http://jsfiddle.net/xNyww/

Sign up to request clarification or add additional context in comments.

Comments

1

Not jQuery, but plain JS: You can use split to separate the values in an array: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split

I do not know what do the csv looks like. If it's only one line, e.g:

checkbox1, checkbox7, checkbox2

then use it as:

var checkboxes[] = csvString.split(",");

for (str in checkboxes) {
    $("#"+str).yourActionHere();
}

If it's several lines (one per checkbox) , e.g.

checkbox1, true
checkbox2, false

then :

var checkboxes[] = csvString.split(/\r\n|\r|\n/);

for (str in checkboxes) {
    var data = str.split(",");
    $("#"+data[0]).yourActionHere(data[1]);
}

Comments

0

Live Demo

var storedFormValues = "checkbox1, checkbox3, checkbox4";

$('#formid').children('input[id^=checkbox]').each(function() {
    if (storedFormValues.indexOf($(this).attr('id')) != -1) {
        $(this).attr('checked', 'checked');
    }
});

Note: If you plan on having more than 10 checkboxes, I recommend naming them with a leading zero (ex: checkbox01) otherwise you may run into an issue where checkbox1 matches against checkbox11.

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.