Using location.replace with data from a form - javascript

I have an HTML form that I am trying to use to navigate to a different page. I was trying to use window.location.replace to append the value of the input to the end of the form like this:
Before: https://example.com/search
After: https://example.com/search/formvalue
I have tried just about every trick I can find, but have had no luck. I was able to get it working by replacing window.location.replace with window.open, but I don't want to have to open it in a new tab. I also tried window.location.assign but had no more luck with that. I tried running both of these functions in the Chrome console and they worked fine from there. My code is below.
function onenter() {
var term = document.getElementById("searchbox").value;
window.location.replace("/search/" + term);
}
<form method="GET" onsubmit="onenter();">
<input id="searchbox" name="term" type="text" autofocus>
<button id="searchenter" type="submit">Enter</button>
</form>
What am I doing wrong/missing?

Your issue is that the form submission reloads the page. Use eventObject.preventDefault:
function onenter(event) {
event.preventDefault();
var term = document.getElementById("searchbox").value;
window.location.replace("/search/" + term);
console.log(window.location);
}
<form method="GET" onsubmit="onenter(e);">
<input id="searchbox" name="term" type="text" autofocus>
<button id="searchenter" type="submit">Enter</button>
</form>

Related

How to get form input to appear as query params when div is click instead of button

I have an html form that is more or less the following
<form action="/results">
<input name="q" type="text">
<div>See results</div>
</form>
If I type something into the form, such as "my search" and press "enter" I'll be taken to the Results page with something like this: mywebsite.com/results?q=my+search. My problem is that I would like to get the same behavior when someone clicks "See results," which currently takes them to the Results page but without the params. I know using <button> instead of <div> would get me the results I need, but in this situation using <button> is not practical due to how all of the templates have been written.
Concatenate ?q=searchstring to the URL when assigning to window.location.
document.querySelector("#results").addEventListener("click", function() {
let param = document.querySelector([name=q]).value;
let url = `/results?q=${encodeURIComponent(param)}`;
window.location = url;
}
<form action="/results">
<input name="q" type="text">
<div id="results">See results</div>
</form>
If you can use input type submit, try wrapping the it in the div as in this way:
<form action="/results">
<input name="q" type="text">
<div><input type="submit" value="See results" /></div>
</form>
If this not works for you, alternatively you can handle it using javascript as #Barmar answered above.

Javascript function on submit externally?

I'm looking to create a Chrome extension for a new tab page. I've written the page and have it working only I'm having a problem with moving my Javascript from inline to external.
Current index.html is looking like this:
<script>
function process()
{
var url="https://www.google.co.uk/search?q=" + document.getElementById("goog").value;
location.href=url;
return false;
}
</script>
<div class="container">
<form onSubmit="return process();">
<input type="text" class="form-control" id="goog" placeholder="Google Search">
<input type="submit" style="display:none"/>
</form>
I've tried a few different methods of moving this into an external file but I'm not great with Javascript. I'd imagine I would need to use an event listener of some kind. I've tried placing this in search.js:
var form = document.getElementById("search");
form.addEventListener("submit", function() {
var url="https://www.google.co.uk/search?q=" + document.getElementById("goog").value;
location.href=url;
return false;
});
With this amended html:
<form id="search">
<input type="text" class="form-control" id="goog" placeholder="Google Search">
<input type="submit" style="display:none"/>
</form>
But to no avail. Can anyone help?
You are attaching the 'submit' event to the text input element.
You should instead attach it to the form, as it's the form what gets submitted, not only that particular input. (You already do it correctly on your current index.html document).
You can do this adding an id to the form element:
<form id="your-form-id">
and then attaching the event to it like you're already doing:
var form = document.getElementById("your-form-id");
form.addEventListener("submit", function() { ...
Also, note that unless you've changed your html while moving the JS code to an external file, on the 'submit' event callback you're trying to get the search string from an element with id="url" while your text input element has id="goog", so you won't be able to retrieve it.
EDIT:
The issue seems to be that the form submit gets executed and you're redirected to the same page with a new blank input before your code can be run.
You can avoid this calling preventDefault() on the event when receiving it so the form is not submitted and your code is run, instead of returning false at the end.
form.addEventListener("submit", function(event) {
event.preventDefault();
... your code ...
I've noticed that it's possible without any Javascript. I can make a form with a method of GET and pass the contents of the form into the GET request like below:
<form method="GET" action="https://google.co.uk/search">
<input type="text" name="q" class="form-control" placeholder="Google Search">
<input type="Submit" style="display:none">
</form>
The above solution is correct but using this avoids any Javascript whatsoever.

Unable to open javascript search engine results on a new window

I'm using a javascript search engine from this script page that allows me to select different providers/search engines to perform a google like search, but I'm trying to make it open in a new window after I press the send button, without success.
I've already tried to use:
target="_blank"
in <input type="button" value="Send" onClick="startSearch()" target="_blank"> and nothing happens, or:
<form name="searchForm" target="_blank">
Nothing!
I've also tried to use _new instead of _blank and didn't work either.
Finally, I've tested what suggested on w3schools.com example but unfortunately again a failure.
Can you please, guys, help? Thanks!
try something this if you want to open a new tab link by your button-
<a href="http://www.stackoverflow.com/" target="_blank">
<input type="button" value="Send" />
</a>
Quick and dirty, you can use the window.open(); method to open the search in a new window, here's some updated HTML:
<form method="GET" action="#" id="search-form">
<p><label>Search for: <input type="text" id="q" /></label></p>
<p><label>Search from: <select id="engine">
<option selected="selected" value="http://www.google.com/search?q=">Google</option>
<option value="http://www.bing.com/search?q=">Bing</option>
<option value="http://search.yahoo.com/search?p=">Yahoo!</option>
<option value="http://search.aol.com/aol/search?q=">AOL</option>
</select></label></p>
<p><input type="button" value="Send" id="send" /></p>
</form>
And the JavaScript:
<script>
var ID = function(str){return(document.getElementById(str));};
ID('send').addEventListener('click', function(){
var search = ID('q').value, select = ID('engine'), engine = select.options[select.selectedIndex].value;
if(!search) {
alert('Please include a search string');
} else {
window.open(engine + search);
}
});
</script>
Just make sure to call that at the end of the page or put it in a DOMContentLoaded event or something.
MDN Docs on window.open()
To open the link in a new window, since you are using a <form> instead o an <a> link, you have to change the javascript shown in the example, first adding an ID to the form so it is easilly accessible via the DOM:
<form id="searchForm" name="searchForm" target="blank">
Then, change the last javascript line so instead of the location.href, it changes the form's action and submits it:
document.getElementById("searchForm").action = finalSearchString;
document.getElementById("searchForm").submit();
Example:
https://jsfiddle.net/vj99ux9e/

jQuery handle a href on clicking an anchor element

I'm using:
<input type="text" class="form-control searchValue">
Search
in order to perform search. When user clicks on search, jQuery has to get the value of the input and then redirect user to the page itself + "?search=valueInInput" in order to perform search in PHP by using GET value in URL.
For this, I used:
$(".searchButton").on("click", function($this){
var url = location.host + "/index.php?search=" + $(".searchValue").val();
$(".searchButton").attr("href", url)
});
The problem is that user is never redirected to the url, but I didn't put any return false or preventDefault, why?
How to change this in order to perform the search?
This works for me:
$(".searchButton").on("click", function(){
var url = "/index.php?search=" + $(".searchValue").val();
$(".searchButton").attr("href", url)
});
I removed $this and location.host.
This is the code I finally used. I think this is better to maintain without JS and it's more clean...
<form action="index.php" method="GET">
<div class="form-group">
<input name="search" id="search" type="text" class="form-control searchValue" value="qsdfdf">
</div>
<button type="submit" class="btn btn-default">Recherche</button>
</form>
Since it is the same page that you have to redirect to it, so you don't need to regard the file name in the URL. Also you may use the location property of the window object:
$(document).ready(function(){
$(".searchButton").click(function(){
q = $(".searchValue").val();
window.location = "?search="+q
});
});
Checkout this DEMO

submit form to string (jquery?)

I'm trying to create a form which submits a string to another page only with the parameter name removed from the URL.
i.e. submitting the following form with "foo"
<form action="search.asp" method="get">
<input type="text" name="keyword" id="keyword">
<input type="submit" value="Go">
</form>
will go to search.asp?foo NOT search.asp?keyword=foo
Can this be done with pure html?
I guess this can be done with javascript and/or jquery but I'm not certain exactly how.
Can anybody help?
I'm a bit of a noob so a copy and paste solution would be great for me.
Update:
Thanks for the answers so far but they don't seem to be working. Perhaps a better way to do this is to get JQuery to construct the URL and load that URL? Any more suggestions would be great.
or maybe...?
$('input[type="text"]').blur(function() {
$('form').attr('action', 'search.asp?' + $('input').val());
});
Let's give the form and the submit button a classname for convenience and assume we have jQuery on the page.
<form action="search.asp" method="get" class="search_form">
<input type="text" name="keyword" id="keyword">
<input type="submit" value="Go" class="search_button">
</form>
<script type="text/javascript">
$(function(){
var $form = $(".search_form");
// save the default action, because we are going to mess with it.
$form.data("original-action", $form.attr("action"));
// listen to the click on the button, update the form action and submit the form manually
$(".search_button").click(function(){
$form.attr("action", $form.data("original-action") + "?" + $("#keyword").val());
$form.submit();
return false;
});
});
</script>
Not tested, but should work. Let me know.
Btw, saving the default action is maybe not needed. But just in case that you ever want to submit it with ajax without reloading the page.
Try this:
<form action="search.asp?foo">
<script>
$(document).ready(function(){
$("#btnSubmit").click(function(){
var keywordVal = $("#keyword").val();
window.location.href = "search.asp?" + keywordVal;
});
});
</script>
<input id="keyword" type="text" name="keyword">
<button id="btnSubmit">Submit</button>

Categories