Jump to content

Change name in Option


Zerivo

Recommended Posts

Hi i need help for change name in Option when i press button.

like that code:

<select id="List">
<option value="A1">Cars</option>
<option value="A2">Bike</option>
<option value="A3">Train</option>
</select>
How i change name from "Bike" to "Plane" by press button?
Link to comment
Share on other sites

<!DOCTYPE html>
<html lang="en">
<head>
<title>change</title>
<script>
window.onerror = function(e,p,l){
alert('Javascript Error: '+e+'\nPath: '+p+'\nLine Number: '+l);
return true;
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#btn1").click(function(){
        $("[value=A2]").text("Plane");
    });
    $("#btn2").click(function(){
        $("[value=A2]").text("Bike");
    });
}); 

</script>
</head>

<body>

<h1>Demo</h1>

<select id="List">
<option value="A1">Cars</option>
<option value="A2">Bike</option>
<option value="A3">Train</option>
</select>

<input type="button" value="Plane" id="btn1">
<input type="button" value="Bike" id="btn2">

</body>
</html>

--updated 5pm cdt-- fixed ] error mentioned by Dsonesuk below

Link to comment
Share on other sites

Or more efficiently:

/* Place code right before the closing </body> tag */
// Reference to elements
var button1 = document.getElementById("btn1");
var button2 = document.getElementById("btn2");
var list = document.getElementById("List");
var option = list.querySelector("option[value=A2]");

// Event listeners
button1.addEventListener("click", changeOption, false);
button2.addEventListener("click", changeOption, false);

// Change option text
function changeOption(e) {
  var text;

  // Select text based on which button was clicked
  if(e.target == button1) {
    text = "Plane";
  } else {
    text = "Bike";
  }

  // Change the text
  option.text = text;
}
Link to comment
Share on other sites

Oh i see, last i found own way, cheep and few word ;)

 

in body i have to add id each option, like that:

 

<select id="List">
<option id="O1" value="A1">Cars</option>
<option id="O2" value="A2">Bike</option>

<option id="O3" value="A3">Train</option>

</select>

 

then in javascript when i press button:

function Button()

{

document.getElementById('O2').innerHTML="Plane";

}

 

so it work good :) anyway thank for try help me

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...