Add option inside optgroup

Asked

Viewed 512 times

0

I want to add a 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); 
  • 1

    Add how? By clicking a button? By loading the page? By loading another element?

3 answers

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 type element select attributable name = testSelect. Then, we filter the children of this element by selecting only the type element optgroup that has the attribute label = opt2, and 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>
  <select name="testSelect">
        <optgroup label="opt1">
            <option value="3">Apples</option>
        </optgroup>
        <optgroup label="opt2"></optgroup>
    </select>
<button id=add>Adicionar element</button>
 </body>

  • Thanks for the reply. And without using jquery?

2


With pure javascript you can do so:

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 function addOption 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');

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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.