Home >Web Front-end >JS Tutorial >Js implementation code to obtain the value and text of the selected item in the drop-down box_javascript skills

Js implementation code to obtain the value and text of the selected item in the drop-down box_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:58:201291browse

Js provides two methods to obtain the value and text of the drop-down box: But some people are very irresponsible. They do not consider the errors caused by the differences between browsers, causing many novices to figure it out for a long time and cannot find it. mistake!

Below I summarize how to get the value and text of the selected item in the drop-down box under Firefox and IE:

1. Methods supported by both IE and Firefox:
Get text

Copy code The code is as follows:

var obj=document.getElementById('select_template');
var text=obj.options[obj.selectedIndex].text;//Get text

var obj=document.getElementById("select_template");
for(i=0;i if(obj [i].selected==true) {
          var text=obj[i].text;//Get text
      }
}


Compared with the previous one The method is relatively simple

2. IE supports Firefox but not:
Copy code Code As follows:

var obj=document.getElementById(name);

for(i=0;i if(obj[i].selected==true) {
var text= obj[i].innerText;
}
}


The method of getting the value is common to IE and Firefox:
var value=document.getElementById("select_template").value;//Getting the value

Summary: In fact, the main reason is that both IE and Firefox support the value and text attributes, but Firefox does not support the innerText attribute.

Js implements opening a new link on the current page:
window.location.href=url;

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