Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (7k points)

I am working on search in JavaScript. I am using a form, but it is messing up something else on my page. I have this input text field:

<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>

And this is my JavaScript code:

<script type="text/javascript">

  function searchURL(){

    window.location = "http://www.myurl.com/search/" + (input text value);

  }

</script>

How do I get the value from the text field into JavaScript?

1 Answer

0 votes
by (13.1k points)

There are various methods to get an input textbox value directly

Method1:

document.getElementById('textbox_id').value to get the value of desired box

For example, document.getElementById(“searchText”).value;

Method2:
Use document.getElementsByClassName('class_name')[whole_number].value which returns a Live HTMLCollection

For example, document.getElementsByClassName(“searchText”)[0].value; if this is the first textbox in your page.

Method3:

Use document.getElementsByTagName('tag_name')[whole_number].value which also returns a live HTMLCollection

For example, document.getElementsByTagName(“input”)[0].value; if this is the first textbox in your page.

Method4:

document.getElementsByName(‘name’)[wholeNumber].value which also returns a live NodeList

For example,

document.getElementsByName(“SearchText”)[0].value; if this the first textbox with name ‘SearchText’ in your page.

Method5:

Use the powerful document.querySelector(‘selector’).value which uses a CSS selector to select the element

For example,

document.querySelector('#searchText').value; selected by id

document.querySelector('.searchField').value; selected by class

document.querySelector('input').value; selected by tagname

document.querySelector('[name="searchText"]').value; selected by name

Want to be a full stack developer? Check out the full stack developer course from Intellipaat.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...