Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript getting the value of a text box

I have this text box here...

<input name="search" type="text" maxlength="512" id="search" class="searchField" autocomplete="off" title="" />

and I also have this submit

<input type="submit" name="btnSearch" value="Search" onclick="location.href='http://www.website.com/search/';" id="btnSearch" class="buttonSearch" />

what I am trying to do is add whatever is in the text box in my

onclick="location.href='http://www.website.com/search/';"

so it would look like this..

onclick="location.href='http://www.website.com/search/what ever the user searches';"

how would I go about doing this, I have been googling my little heart out.

like image 634
user979331 Avatar asked Jun 07 '12 19:06

user979331


2 Answers

Please avoid mixing JavaScript and HTML. You can remove onclick attribute and replace it with this in plain JavaScript somewhere after the DOM has loaded:

document.getElementById('btnSearch').onclick = function() {
    var search = document.getElementById('search').value;
    var searchEncoded = encodeURIComponent(search);
    window.location.url = "http://www.website.com/search/" + searchEncoded;
}

Also remember about escaping the search box, e.g. using encodeURIComponent(). Here is a working jsfiddle example.

like image 119
Tomasz Nurkiewicz Avatar answered Oct 17 '22 07:10

Tomasz Nurkiewicz


This should work:

onclick="location.href='http://www.website.com/search/'+document.getElementById('search').value;"

But I wouldn't ever write that in one of my project as writing script directly on tags is a bad practice.

like image 10
nebulousGirl Avatar answered Oct 17 '22 07:10

nebulousGirl