Home > OS >  How to set the value of an Option element in a dynamically created Select in a table as it is create
How to set the value of an Option element in a dynamically created Select in a table as it is create

Time:10-24

I am dynamically creating a dropdown list in a table and want to set the value of the dropdown to the current value (the user can then change it to one of the other values). The row looks like this (there are multiple rows):

enter image description here

In this case the value of PAR should initially be 2 (each row can have a different initial value).

The code is:

html  = "<td style='width : 1%; white-space: nowrap;'><select name='parRating'>"
for (let i = 0; i <= paraArray; i  ) {
    html  = "<option name='parRatingOption' value='"   parRatingArray[i]   "'>"   parRatingArray[i]   "</option>"
};
html  = "</select></td>";
// set the current option to this.parRating 

CodePudding user response:

It seems, that you need to add "selected" attribute to the <option>, that you need

Something like this:

html  = "<td style='width : 1%; white-space: nowrap;'><select 
        name='parRating'>";
let selectedValue = "2"; // <-- 
let selected = "";
for (let i = 0; i <= paraArray; i  ) {
  selected =  parRatingArray[i] == selectedValue ? " selected "  : "";
  html  = "<option " selected " name='parRatingOption' value='"   parRatingArray[i]   
     "'>"   parRatingArray[i]   "</option>"
};
html  = "</select></td>";

// set the current option to this.parRating

CodePudding user response:

You can use template literals:

html  = `<option name='parRatingOption' value='${parRatingArray[i]}'>${parRatingArray[i]}</option>`

This also helps to avoid awkward string joints. The best practice would be to create a function that generates n number of options with given one selected:

const generateOptions = (n, selectedOne) => {
    let options = ''
    for(let i=0; i<n; i  ){
        options =`<option name='parRatingOption' ${i===selectedOne ? 'selected' : ''} value='${parRatingArray[i]}'>${parRatingArray[i]}</option>`
    }
    return options;
}

html =`<td style='width : 1%; white-space: nowrap;'>
          <select name='parRating'>
             ${generateOptions(5, 2)}
          </select>
       </td>`

This dynamically generates 5 inputs with second one selected

CodePudding user response:

I modified Abdullokh's and Alex's answers and added "selected" to the option element:

html  = "<td style='width : 1%; white-space: nowrap;'><select name='parRating'>"
for (let i = 0; i <= paraArray; i  ) {
    if (this.parRating  == parRatingArray[i]) {
        // set the current option to this.parRating 
        html  = "<option selected name='parRatingOption' value='"   parIdArray[i]   "'>"   parRatingArray[i]   "</option>"
    }else {
        html  = "<option name='parRatingOption' value='"   parIdArray[i]   "'>"   parRatingArray[i]   "</option>"
    }
};
html  = "</select></td>";
  • Related