简体   繁体   中英

Change the values inside a select tag, when I click a button

I have a form with a select tag that have some options. I want that when I click in the button to change the value in the select tag, and in that way the tag will have the value I define by

document.getElementById('fruits').innerHTML="computer"

In this JSFiddle it does not function when I click the button.

As i see you can try:

HTML:

<select id="sel">
    <option>Apple</option>
    <option>Orange</option>
</select>
<input type="button" value="change" onclick="fill()">

JS:

function fill() {
    $('#sel').empty();
    $("#sel").append(new Option("Computer"));

}

DEMO

Or with vanilla js you can try:

function fill(){
    document.getElementById('sel').innerHTML="<option>Computer</option>";
}

DEMO2

function fill(){
    document.getElementById('fruits').innerHTML="<option>Meat</option>";}

<select id="fruits">
    <option> Apple</option>
    <option> Orange</option>
</select>

If I am getting you right then make these change in your code.

Try this

$('#change').click(function() {
    document.getElementById('fruits').innerHTML="<option>Meat</option>";
});

modified HTML to

<select id="fruits"> 
    <option> Apple</option>
    <option> Orange</option>
</select>

<input type="button" value="change" name="change" id="change">
 your html is wrong. use the code like:

 <select id="fruits">
        <option>Apple</option>
        <option>Orange</option>
  </select>

  <input type="button" value="change" onclick="fill();" />

 And change the fill function to:

  function fill() {
        document.getElementById('fruits').innerHTML = "<option>Meat</option>";
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM