Add option within optgroup

0

I want to add one in javascript inside an HTML created.

<select name="testSelect">
 <optgroup label="opt1">
  <option value="3">Apples</option>
</optgroup>
<optgroup label="opt2">

</optgroup>
</select>

In this example I want to add the option inside the opt2 label. Something like this but inside the optgroup.

$("testSelect").set("value", 1); 
$("testSelect").set("text", teste); 
    
asked by anonymous 28.11.2016 / 00:04

3 answers

2

With pure javascript you can do this:

addOption = function(optGroup, text, value) {
  var optGroup = document.querySelector(optGroup);
  var option = document.createElement("option");
  option.value = value;
  option.innerHTML = text;

  optGroup.appendChild(option);
}

addOption('[label="opt2"]', 'teste', 'abc');
<select name="testSelect">
 <optgroup label="opt1">
  <option value="3">Apples</option>
</optgroup>
<optgroup label="opt2">

</optgroup>
</select>

Add the addOption function to your javascript, it will receive 3 parameters, the first is the optgroup selector, the second is the text of the option, and the third is the value:

addOption('[label="opt2"]', 'Pineapples', '4');
    
28.11.2016 / 11:53
2

You can use the following jQuery to add a new option :

$("select[name=testSelect]").children("optgroup[label=opt2]").append("<option value=4>Bananas</option>");

First we select the element of type select that has attribute name = testSelect . We then filter the children of this element by selecting only the element of type optgroup that has the attribute label = opt2 , and we add a new child to that element.

$("select[name=testSelect]").children("optgroup[label=opt2]").append("<option value=4>Bananas</option>");
var value = 5;
$("#add").on("click", function() {     $("select[name=testSelect]").children("optgroup[label=opt2]").append("<option value=" + value + ">novoItem" + (value - 4) + "</option>"); value++; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><body><selectname="testSelect">
        <optgroup label="opt1">
            <option value="3">Apples</option>
        </optgroup>
        <optgroup label="opt2"></optgroup>
    </select>
<button id=add>Adicionar element</button>
 </body>
    
28.11.2016 / 05:35
1

With javascript you can add HTML elements using element.innerHTML . In your example, it could be something like:

// obtem o segundo optgroup pela label
var opt = document.querySelectorAll('[label="opt2"]')[0];
opt.innerHTML = '<option value="3">Apples</option>';

var opt = document.querySelectorAll('[label="opt2"]')[0];
opt.innerHTML = '<option value="3">Apples</option>';
<select name="testSelect">
 <optgroup label="opt1">
  <option value="3">Apples</option>
</optgroup>
<optgroup label="opt2">

</optgroup>
</select>
    
28.11.2016 / 11:45