dom - How do I get the value of text input field using JavaScript? -
i working on search javascript. use form, messes else on page. have input text field:
<input name="searchtxt" type="text" maxlength="512" id="searchtxt" class="searchfield"/>
and javascript code:
<script type="text/javascript"> function searchurl(){ window.location = "http://www.myurl.com/search/" + (input text value); } </script>
how value text field javascript?
there various methods input textbox value directly (without wrapping input element inside form element):
method 1:
document.getelementbyid('textbox_id').value
value of desired boxfor example,
document.getelementbyid("searchtxt").value;
note: method 2,3,4 , 6 returns collection of elements, use [whole_number] desired occurrence. first element, use [0], second 1 use 1, , on...
method 2:
use
document.getelementsbyclassname('class_name')[whole_number].value
returns live htmlcollectionfor example,
document.getelementsbyclassname("searchfield")[0].value;
if first textbox in page.
method 3:
use
document.getelementsbytagname('tag_name')[whole_number].value
returns live htmlcollectionfor example,
document.getelementsbytagname("input")[0].value;
, if first textbox in page.
method 4:
document.getelementsbyname('name')[whole_number].value
>returns live nodelistfor example,
document.getelementsbyname("searchtxt")[0].value;
if first textbox name 'searchtext' in page.
method 5:
use powerful
document.queryselector('selector').value
uses css selector select elementfor example,
document.queryselector('#searchtxt').value;
selected id
document.queryselector('.searchfield').value;
selected class
document.queryselector('input').value;
selected tagname
document.queryselector('[name="searchtxt"]').value;
selected name
method 6:
document.queryselectorall('selector')[whole_number].value
uses css selector select elements, returns elements selector static nodelist.for example,
document.queryselectorall('#searchtxt')[0].value;
selected id
document.queryselectorall('.searchfield')[0].value;
selected class
document.queryselectorall('input')[0].value;
selected tagname
document.queryselectorall('[name="searchtxt"]')[0].value;
selected name
support
browser method1 method2 method3 method4 method5/6 ie6 y(buggy) n y y(buggy) n ie7 y(buggy) n y y(buggy) n ie8 y n y y(buggy) y ie9 y y y y(buggy) y ie10 y y y y y ff3.0 y y y y n ie=internet explorer ff3.5/ff3.6 y y y y y ff=mozilla firefox ff4b1 y y y y y gc=google chrome gc4/gc5 y y y y y y=yes,n=no safari4/safari5 y y y y y opera10.10/ opera10.53/ y y y y(buggy) y opera10.60 opera 12 y y y y y
useful links
Comments
Post a Comment