Home >
Article > Web Front-end > Javascript gets the text value in the drop-down list box sample code_javascript skills
Javascript gets the text value in the drop-down list box sample code_javascript skills
WBOYOriginal
2016-05-16 17:27:421154browse
Recently I encountered a problem, which is to save the selected content after the user clicks an option in the drop-down list, such as the following HTML code:
That is to say, when the user selects the "Shanghai" column, the name "Shanghai" needs to be saved. In fact, the method is very simple. Look at the following javascript code:
function isSelected(value) { var cityName; var city = document.getElementById("city"); //Get the selected city name for(i=0;iif(city[i].selected==true){ cityName = city[i].innerText; //Key point alert("cityName:" cityName); } }
function isSelected(value) { var city = document.getElementById("city"); alert(city.options[city.selectedIndex].innerText); }
To give a rough explanation, first there is a drop-down box on the HTML page, and a "city" id is defined for the drop-down box, and an onchange event is bound to it, and the javascript function is called through this event.
In the javascript function, the node element of the current drop-down box is obtained through the domcument object. Since the value of the node is not only one, we can get the value of each option by looping the node. During the loop, it is judged whether the current option is selected, and if it is selected, use the city[i].innerText method to obtain the currently selected text value. Of course, if you need to get the option value, just do this: city[i].value.
At this point, the desired result can be achieved under IE through the above method. However, when testing under FIREFOX, it was found that this method did not work, and finally another method was found by consulting the information. Just change city[i].innerText to city[i].text. This method is applicable to both IE and FIXEFOX!
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn