1

I have the code below, which I am using to create a table and then populate it with data from JSON. My issue is that I have several data objects and would like to switch between them using select tag. Could you please help?

HTML

<select name="selector" onchange="onDataChange();">
    <option value="data1">RD1</option>
    <option value="data2">RD2</option>
    <option value="data3">RD3</option>
</select>

JSON Data

var data1 = [
    {"value":"RD01"}, 
    {"value":"RD02X"},
    {"value":"RD021ZX"}
];
var data2 = [
    {"value":"AX761"}, 
    {"value":"GT02X"},
    {"value":"GB051ZX"}
];
var data3 = [
    {"value":"BG761"}, 
    {"value":"OP02Z"},
    {"value":"FBL1ZX"}
];

JQuery

function onDataChange(){
    var select = $("select[name=selector]").val();
    //some logic
}
function buildTable(){
    var table = $(".code-table");
    for(i = 0; i < data.length; i++){
        var row = "<tr><td>" + data[i].value + "</td></tr>";
        table.append(row);
    }
}
buildTable();
3
  • What is the problem here? Could you provide an example of what you are trying to accomplish? Commented Feb 3, 2016 at 20:19
  • 1
    The data you posted isn't JSON, it's just JavaScript. The format is very similar but JSON doesn't have declarations like var Commented Feb 3, 2016 at 20:23
  • Thanks for comments, the issue is solved :) Commented Feb 3, 2016 at 20:27

1 Answer 1

1

The simplest solution is just to add a parameter to buildTable()

function onDataChange(){
    var select = $("select[name=selector]").val();
    if (select == 'data1') buildTable(data1);
    else if (select == 'data2') buildTable(data2);
    else if (select == 'data3') buildTable(data3);
    //some logic
}

function buildTable(data){
    $(".code-table tr").remove(); //clear out table
    var table = $(".code-table");
    for(i = 0; i < data.length; i++){
        var row = "<tr><td>" + data[i].value + "</td></tr>";
        table.append(row);
    }
}
buildTable(data1);
Sign up to request clarification or add additional context in comments.

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.