Ricky
Ricky

Reputation: 35

Option value need to be different, Instead of being same as displayed in Select Box

I am having little issue in java script generated select box, The problem is that i want to display PK - 1, PK - 2 .. in select box but the value which will be attached to them will be different. For example for PK - 1 , I want to have 1 as it value, Similarly for PK - 2 i want to have 2 as its passing value. But here in this code the script is passing PK - 1 as it is. As i am new to java Script, I do not know how to do it. Here is my code

function categoryInput(data){
    var category_vals = document.getElementById("categroy_renew");
for(var i=0;i<data.length;i++){
var option = document.createElement("option");
option.text = "PK - "+data[i].cat,data[i].cat;
category_vals.add(option);
}
}       

Upvotes: 0

Views: 33

Answers (3)

RobH
RobH

Reputation: 3612

You just need to set the value on your option like you are setting the text:

var option = document.createElement("option");
option.text = "PK - " + data[i].cat, data[i].cat; // Why are you doing this part?
option.value = data[i].cat;                       // Just need "PK - " + data[i].cat;
category_vals.add(option);

As mentioned in comments there is an easier way to create new options, take a look at this question.

Upvotes: 1

Arie Xiao
Arie Xiao

Reputation: 14082

function categoryInput(data) {
    var category_vals = document.getElementById("categroy_renew");
    for (var i = 0; i < data.length; i++) {
        var option = document.createElement("option");
        option.text = "PK - " + data[i].cat;
        option.value = "" + data[i].cat;
        category_vals.add(option);
    }
}

Upvotes: 0

Jasper Van Kerschaver
Jasper Van Kerschaver

Reputation: 81

It seems to me that you're forgetting to set the "value" of each option. Like you've set option.text, try to set option.value for each option.

Upvotes: 0

Related Questions