2

I've got a jSON ajax response like the following example:

['PostA1'] =>1
['PostA2'] =>1
['PostA3'] =>2
['PostB1'] =>1
['PostB2'] =>3
['PostB3'] =>0
['PostB4'] =>2
['Pre1'] =>1
['Pre2'] =>2
['Pre3'] =>1
['Pre4'] =>3
['Pre4'] =>3

PostA-x, PostB-x and Pre data refers to sets of radio buttons which need to be set depeing on their value. I could just do this by writing a line of code to process each individual one such as:

$("input[id='Pre1-" + data.Pre1 + "']").attr('checked','checked');
$("input[id='Pre1-" + data.Pre2 + "']").attr('checked','checked');
$("input[id='PostA1-" + data.PostA1+ "']").attr('checked','checked');
$("input[id='PostA2-" + data.PostA2 + "']").attr('checked','checked');

...etc..., but ideally I'd like to be able to loop through the data set something like...

        i = 1;
        $.each("--Aray which starts with PostA--" + i){
              $("input:radio[id='PostA-" + data.PostA -- incrementer variable -- + "'].attr('checked',checked');
i++;
    }

then repeat this loop for each of the three data set...but I'm really stuck as firstly I'm not that great at jQuery selectors and secondly I don't know how to make variable variables within the selector.

Hopefully this makes sense! If you guys have any advice on how to do this (maybe I'm going about this totally the wrong way?!?!?) then it'd be greatly appreciated.

Dan

2 Answers 2

1

You could use for..in to loop the object.

for (var key in data) {
  // $("input[id='" + key + "-" + data[key]+ "']").prop('checked', true);
  // below is better if select by id
  $('#'+key+'-'+data[key]).prop('checked', true);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Why not iterate over data instead? You can use $.each() to do that, and build the current element's id from each key/value pair:

$.each(data, function(key, value) {
    $("#" + key + "-" + value).prop("checked", true);
});

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.