How can I get the input value in JavaScript?

How can I retrieve the value of a text input field using JavaScript? I’m working on a search feature without using a form, as it conflicts with other elements on my page.

Here’s my input text field:

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

In my JavaScript code, I want to use the input value in the following function:

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

How can I get the input value in JavaScript?

Using document.getElementById() You can directly access the input field using its ID and retrieve its value as follows:

function searchURL() {
var inputValue = document.getElementById("searchTxt").value; // Get input value
window.location = "http://www.myurl.com/search/" + encodeURIComponent(inputValue); // Navigate to the search URL
}

Another approach is to use document.querySelector() to select the input field. This method allows for more complex selectors if needed.

function searchURL() {
var inputValue = document.querySelector("#searchTxt").value; // Get input value
window.location = "http://www.myurl.com/search/" + encodeURIComponent(inputValue); // Navigate to the search URL
}

You can also attach an event listener to the input field that triggers the search when the user presses Enter or clicks a button. This is a more interactive approach.

document.getElementById("searchTxt").addEventListener("keypress", function(event) {
if (event.key === "Enter") { // Check if Enter key is pressed
searchURL();
}
});
function searchURL() {
var inputValue = document.getElementById("searchTxt").value; // Get input value
window.location = "http://www.myurl.com/search/" + encodeURIComponent(inputValue); // Navigate to the search URL
}

The input value is retrieved from the text field with the ID search text and appended to the search URL. Using encodeURIComponent() ensures the input value is safely encoded for inclusion in the URL.