moonlight
moonlight

Reputation: 37

onchange function doesn't fire when first selecting an item from the dropdown - Stack Overflow

HTML code:

<select id="nodeselect"></select></p>

JavaScript code:

var select1 = document.getElementById("nodeselect");
var textnode;
for (var i = startnode; i <= endnode; i++) {

    if (i <= 9)
        textnode = document.createTextNode("n400" + i);
    else
        textnode = document.createTextNode("n40" + i);

    node = document.createElement("Option");
    node.appendChild(textnode);
    node.value = "https://10.10.10." + (i);
    select1.appendChild(node);


}
select1.onchange = function() {
    var link = this.value;
    window.open(link);
}

I know that the onchange attribute fires the moment when the value of the element is changed. If I select the first element from the drop-down list onchange will not be fired.

Is there any way to let the first element when clicked on goes to the specified ip address?

Upvotes: 0

Views: 60

Answers (2)

Shiv Patne
Shiv Patne

Reputation: 553

Adding another answer, if you don't want select/blank option.

var select1 = document.getElementById("nodeselect");
var textnode;
startnode = 0;
endnode = 10;
for (var i = startnode; i <= endnode; i++) {

  if (i <= 9)
    textnode = document.createTextNode("n400" + i);
  else
    textnode = document.createTextNode("n40" + i);

  node = document.createElement("Option");
  node.appendChild(textnode);
  node.value = "https://10.10.10.2" + (i);
  select1.appendChild(node);


}
document.getElementById("nodeselect").onmouseout = function() {
  var link = this.value;
  alert(link);
};
<select id="nodeselect">
</select>

Upvotes: 0

Shiv Patne
Shiv Patne

Reputation: 553

By default your first element is selected, so you should have select/blank option first. Please refer below code.

var select1 = document.getElementById("nodeselect");
var textnode;
startnode = 0;
endnode = 10;
for (var i = startnode; i <= endnode; i++) {

  if (i <= 9)
    textnode = document.createTextNode("n400" + i);
  else
    textnode = document.createTextNode("n40" + i);

  node = document.createElement("Option");
  node.appendChild(textnode);
  node.value = "https://10.10.10.2" + (i);
  select1.appendChild(node);


}
select1.onchange = function() {
  var link = this.value;
  alert(link);
}
<select id="nodeselect">
  <option value="">Select</option>
</select>

Upvotes: 1

Related Questions