Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing select option dropdownlist with onclick function button

i want to change dropdown lists with some buttons, i tried this below codes but it doesnt act like what i want,

if i click the buttons, it creates an extra option, this is ok, no problem, (actually i want change between three existing option, not new one)

normally if i click directly to the existing "option 2", another div element shows text2 with ajax, but if i create a selected "option 2", the div element doesnt refresh, after i click to refresh, div element shown correctly

<select id="id1">
 <option value="1">existingshow1</option>
 <option value="2">existingshow2</option>
 <option value="3">existingshow3</option>
</select>

<button onclick="myFunction1()">111</button>
<button onclick="myFunction2()">222</button>
<button onclick="myFunction3()">333</button>

<script>
function myFunction1() {
    var x = document.createElement("OPTION");
    x.setAttribute("value", "1");
    var t = document.createTextNode("show1");
    x.appendChild(t);
    document.getElementById("id1").appendChild(x).selected = "true";
}

function myFunction2() {
    var x = document.createElement("OPTION");
    x.setAttribute("value", "2");
    var t = document.createTextNode("show2");
    x.appendChild(t);
    document.getElementById("id1").appendChild(x).selected = "true";
}

function myFunction3() {
    var x = document.createElement("OPTION");
    x.setAttribute("value", "3");
    var t = document.createTextNode("show3");
    x.appendChild(t);
    document.getElementById("id1").appendChild(x).selected = "true";
}
</script>

<div></div>
like image 256
cfg Avatar asked Feb 12 '26 01:02

cfg


1 Answers

We have an html:

<select id="id1" onChange="onChange(this)">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

<button onclick="addOption();">Add option</button>

Onchange - event, called when select changed

Javascript:

window.addOption = function (){
  var x = document.createElement('option');
  x.setAttribute("value", "new value");
  var t = document.createTextNode("show1");
  x.appendChild(t);

  var select = document.getElementById("id1");
  select.appendChild(x).selected = "true";

  // Trigger select change
  select.onchange();
}

Onchange callback for select

window.onChange = function(select){
  console.log('Select value is: ', select.value);
}

Try: https://jsfiddle.net/otLmwv20/

like image 145
Veniamin Avatar answered Feb 13 '26 13:02

Veniamin