Zerivo 0 Posted June 22, 2016 Report Share Posted June 22, 2016 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? Quote Link to post Share on other sites
davej 251 Posted June 22, 2016 Report Share Posted June 22, 2016 <!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 Quote Link to post Share on other sites
Ingolme 1,020 Posted June 22, 2016 Report Share Posted June 22, 2016 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; } Quote Link to post Share on other sites
dsonesuk 913 Posted June 22, 2016 Report Share Posted June 22, 2016 davej attribute selector wrong incomplete with ']' missing also you could just use $(document).ready(function(){ $("#btn1, #btn2").click(function(){ $("[value=A2]").text($(this).val()); }); }); Quote Link to post Share on other sites
Zerivo 0 Posted June 23, 2016 Author Report Share Posted June 23, 2016 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 Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.