javascript redirect isnt working - javascript

I have a form that takes a users input and redirects to a the window to a URL with their input appended to the end.
Here is my HTML
<form id="wikiForm">
<label id="sideBarLabel">VoIP Services
<input type="text" placeholder="Search Wiki: e.g. E911" name="queryString" id="query-string" />
</label>
<input type="submit" value="Search" onclick="searchWiki();" />
</form>
The javascript it runs
function searchWiki() {
alert("Form Works!");
var siteQuery = $('#query-string').val();
window.location.href = "http://wiki.voipinnovations.com/dosearchsite.action?queryString=" + siteQuery;
alert("SECOND MESSAGE");
}
The issue is that it does not redirect. It only appends the 'siteQuery' variable to the end of the current URL. I know its calling the javascript because I see both alerts. I'm not sure what I'm doing wrong here.

There reason is because you using type="submit", which submits and sends an GET header to the default action parameter (current page).
Change the type="submit" to type="button".
<form id="wikiForm">
<label id="sideBarLabel">VoIP Services
<input type="text" placeholder="Search Wiki: e.g. E911" name="queryString" id="query-string" />
</label>
<input type="button" value="Search" onclick="searchWiki();" />
</form>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
function searchWiki() {
alert("Form Works!");
var siteQuery = $('#query-string').val();
alert(siteQuery);
window.location.assign("http://wiki.voipinnovations.com/dosearchsite.action?queryString=" + siteQuery);
alert("SECOND MESSAGE");
}
</script>
I tried the code with type="submit" and it's alerting, but not redirecting, because the submit is prioritized before the window.location change, thats the reason it just appends a ?queryString=value to the current url.
If you change the type like showed in the code above, it's working perfectly.

The issue is due to the fact that you're actually submitting your form, and the redirection is lost as the form submission occurs first. There are two easy ways to fix this:
Change the type of the input from submit to button, OR
Stop the submission of the form by returning false from your function and changing the call of the function to onclick="return searchWiki();"
jsFiddle example (1)
jsFiddle example (2)

Can't you just use assign?
window.location.assign("http://wiki.voipinnovations.com/dosearchsite.action?queryString=" + siteQuery);
Check out: http://www.w3schools.com/js/js_window_location.asp

Use default action and method attributes instead
The HTML form element provides the mechanism for doing this out of the box.
<form id="wikiForm" action="http://wiki.voipinnovations.com/dosearchsite.action" method="GET">
<label id="sideBarLabel">VoIP Services
<input type="text" placeholder="Search Wiki: e.g. E911" name="queryString" id="query-string" />
</label>
<input type="submit" value="Search" />
</form>
But, if you must use javascript, make this change:
From:
window.location.href = "…";
To:
window.location.assign("…"); // or
window.location = "…"
This is because location.href is a read-only property and location.assign() is the proper method for setting the new location to be loaded. You may also directly assign a string to the location object:
Whenever a new value is assigned to the location object, a document
will be loaded using the URL as if location.assign() had been called
with the modified URL.
Source: MDN

Change input type=submit to type=button
http://plnkr.co/edit/w4U7Sbm3XSKN8j3zUFMe?p=preview
<form id="wikiForm">
<label id="sideBarLabel">VoIP Services
<input type="text" placeholder="Search Wiki: e.g. E911" name="queryString" id="query-string" />
</label>
<input type="button" value="Search" onclick="searchWiki();" />
</form>

Related

Using Form Input to redirect to subfolder [duplicate]

I am attempting to create a form on the page that requires the user to input text. Once the form is submitted, the user will then be redirected to the page assigned to it. My question is where am I going wrong and how should I resolve this issue? Could someone include a JSFiddle or Codepen.io pen for deminstration purposes?
For example:
User enters and submits "123456"
User is then redirected to the page www.domain.com/123456
I am assuming it is something like this:
HTML
<form>
<input id="projectid" maxlength="6">
<input onclick="findProject()" type="submit" value="Go">
</form>
Javascript
function findProject(){
document.location = document.getElementById('projectId').value();
}
I have included my own pen: http://codepen.io/ShaneHicks/pen/eZbbLz
Put a / before the url fragment
document.location = '/' + document.getElementById('projectId').value;
<form>
<input id="projectId" maxlength="6">
<input onclick="return findProject()" type="submit" value="Go">
</form>
<script>
function findProject(){
window.location = document.getElementById("projectId").value;
return false;
}
</script>

How can my user hit enter or click a button to submit and be redirected?

So I have this html form:
<form>
<input type="text" placeholder="Equation" id="equation_input" onsubmit="return button_click()"/>
<input class = "search_button" type="submit" id="search" onclick="button_click()" value="Search"/>
</form>
And I need to take the value the user entered in the equation input, add it to the beginning of a url, and then redirect the user to that newly formed url.
I tried this in my script tags:
function button_click() {
var url = `https://exampleurl.com?q=${document.getElementById('equation_input').value}`;
window.location.replace(url);
}
I've tried a couple things, but I'm not sure what's causing the problem so I don't know exactly what to try.
No need for any js to do this. It can be done by default form submit by naming the input and setting action and method attributes of the form.
Note that an <input> has no submit event, only a <form> does
<form method="GET" action="https://exampleurl.com">
<input type="text" placeholder="Equation" id="equation_input" name="q" required/>
<input class="search_button" type="submit" id="search" value="Search" />
</form>

window.location.assign() navigate to user input of url?

I need to use Javascript window.location.assign() to take input from a user in an inputbox and once a button is clicked the user will be taken to the URL they entered in that inputbox- I am having difficulty finding this online. I am assuming I would need to add a function to my script (not shown).
<form style="padding-top: 20px;">
URL: <input type="url" name="url">
<input type="button" value="GO!" onclick="newUrl()">
</form>
First, instead of putting the function in "onclick" in the button, I suggest putting it on the form element's "onsubmit" handler. That way, a simple "Enter" key can also cause the navigation.
Second, since we're putting the callback on the form, the form's action should changed to 'javascript', like this:
<form style="padding-top 20px;" action="javascript://#" onsubmit="newUrl(this.elements['url'].value)">
URL: <input type="text" name="url">
<input type="submit" value="GO!">
</form>
I've put the url in the first parameter of the "newUrl" function, for ease of writing.
Finally, your "newUrl" function:
function newUrl(url) {
window.location.assign(url);
}
Before using the window.location.assign I would like you to read this
https://developer.mozilla.org/en-US/docs/Web/API/Location/assign
The Location.assign() method causes the window to load and display the
document at the URL specified.
If the assignment can't happen because of a security violation, a
DOMException of the SECURITY_ERROR type is thrown. This happens if the
origin of the script calling the method is different from the origin
of the page originally described by the Location object, mostly when
the script is hosted on a different domain.
If the provided URL is not valid, a DOMException of the SYNTAX_ERROR
type is thrown.
Here is the what you can do to use it
function newUrl(){
window.location.assign(document.getElementById("url").value);
}
<form style="padding-top: 20px;">
URL: <input type="url" name="url" id="url">
<input type="button" value="GO!" onclick="newUrl()">
</form>
Simple alternative
<form style="padding-top 20px;" onsubmit="this.action=document.getElementById('url').value">
URL: <input type="text" id="url">
<input type="submit" value="GO!">
</form>

Passing var url using window location

trying to open search results in window (enter and click) it looks like the code is doing what I want it to do except accessing the actual search url any help is greatly appreciated.
the site is also on dev so you can see what I mean if you enter a search term.
http://staging.asla.org/2014awards/index.html
Code:
<script type="text/javascript">
$(document).ready(function() {
$('form[role="search"]').submit(function() {
var url = "http://asla.org/awardssearch.html";
url += "?s=" + $('#GoogleCSE').val();
window.location = url;
});
});
</script>
<form class="navbar-form navbar-right" role="search">
<div class="search">
<input id="GoogleCSE" type="text" onblur="if(this.value=='')this.value=this.defaultValue;" onfocus="if(this.value==this.defaultValue)this.value='';" value="Search All Awards" name="Search All Awards" />
<input id="submit" type="submit" value="Search" />
</div>
</form>
Setting the location doesn't work beacuse the browser has already started to post the form. The browser will go to the page specified in the action attribute in the form, and as you don't have one, it will use the current page.
Use the preventDefault method to stop the posting of the form:
$('form[role="search"]').submit(function(e) {
e.preventDefault();
...
The issue caused is because of the on focus and onblir event where you are trying to show a placeholder text,
Change your input text to
<input id="GoogleCSE" type="text" placeholder="Search All Awards"/>
It should work.

Trigger autocomplete without submitting a form

I am writing a very simple web app with three text inputs. The inputs are used to generate a result, but all the work is done in Javascript, so there is no need to submit a form. I'm trying to find a way to get the browser to store input values for autocomplete as it would if they were in a form that was submitted.
I have tried giving the inputs autocomplete="on" manually, but without a form to submit, the browser has no way of knowing when it should store the values, so this has no effect.
I have also tried wrapping the inputs in a form that has onSubmit="return false;", but preventing the form from actually submitting appears to also prevent the browser from storing its inputs' values.
It is of course possible to manually use localStorage or a cookie to persist inputs and then generate autocomplete hints from those, but I'm hoping to find a solution that taps into native browser behavior instead of duplicating it by hand.
Tested with Chrome, IE and Firefox:
<iframe id="remember" name="remember" class="hidden" src="/content/blank"></iframe>
<form target="remember" method="post" action="/content/blank">
<fieldset>
<label for="username">Username</label>
<input type="text" name="username" id="username" value="">
<label for="password">Password</label>
<input type="password" name="password" id="password" value="">
</fieldset>
<button type="submit" class="hidden"></button>
</form>
In your Javascript trigger the submit, e.g. $("form").submit(); $("#submit_button").click() (updated from comments)
You need to return an empty page at /content/blank for get & post (about:blank didn't work for me but YMMV).
We know that the browser saves its information only when the form is submitted, which means that we can't cancel it with return false or e.preventDefault()
What we can do is make it submit the data to nowhere without reloading a page. We can do that with an iframe
<iframe name="💾" style="display:none" src="about:blank"></iframe>
<form target="💾" action="about:blank">
<input name="user">
<input name="password" type="password">
<input value="Login" type="submit">
</form>
Demo on JSfiddle (tested in IE9, Firefox, Chrome)
Pros over the currently accepted answer:
shorter code;
no jQuery;
no server-side page loaded;
no additional javascript;
no additional classes necessary.
There is no additional javascript. You normally attach an handler to the submit event of the form to send the XHR and don't cancel it.
Javascript example
// for modern browsers with window.fetch
document.forms[0].addEventListener('submit', function (event) {
fetch('login.php', {
method: 'post',
body: new FormData(event.target))
}).then(r => r.text()).then(() => { /* login completed */ })
// no return false!!
});
No-javascript support
Ideally, you should let the form work without javascript too, so remove the target and set the action to a page that will receive your form data.
<form action="login.php">
And then simply add it via javascript when you add the submit event:
formElement.target = '💾';
formElement.action = 'about:blank';
I haven't tested this, but it might work if you submit the form to a hidden iframe (so that the form is actually submitted but the current page is not reloaded).
<iframe name="my_iframe" src="about:blank"></iframe>
<form target="my_iframe" action="about:blank" method="get">...</form>
---WITHOUT IFRAME---
Instead of using iframe, you can use action="javascript:void(0)", this way it doesn't go to another page and autocomplete will store the values.
<form action="javascript:void(0)">
<input type="text" name="firstName" />
<button type="submit">Submit</button>
</form>
Maybe you can use this Twitter Typeahead...is a very complete implementation of a autocomplete, with local and remote prefetch, and this make use of localStorage to persist results and also it show a hint in the input element...the code is easy to understand and if you don't want to use the complete jquery plugin, I think you can take a look of the code to see how to achieve what you want...
You can use jQuery to persist autocomplete data in the localstorage when focusout and when focusin it autocompletes to the value persisted.
i.e.
$(function(){
$('#txtElement').on('focusout',function(){
$(this).data('fldName',$(this).val());
}
$('#txtElement').on('focusin',function(){
$(this).val($(this).data('fldName'));
}
}
You can also bind persistence logic on other events also depending on the your application requirement.
For those who would rather not change their existing form functionality, you can use a second form to receive copies of all the form values and then submit to a blank page before your main form submits. Here is a fully testable HTML document using JQuery Mobile demonstrating the solution.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile.structure-1.4.5.min.css" />
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<form method="post">
<input type="text" name="email" />
<input type="submit" value="GO" onclick="save_autofill(this);" />
</form>
<script>
function save_autofill(o) {
$(':input[name]', $('#hidden_form')).val(function () {
return $(':input[name=' + this.name + ']', $(o.form)).val();
});
$('#hidden_form').find("input[type=submit]").click();
}
</script>
<iframe name="hidden_iframe" style="display:none"></iframe>
<form target="hidden_iframe" id="hidden_form" action="about:blank" style="display:none">
<input type="text" name="email" />
<input type="submit" />
</form>
</body>
</html>
The save_autofill function just needs to be called on your main form submit button. If you have a scripted function that submits your form, place that call after the save_autofill call. You must have a named textbox in your hidden_form for each one in your main form.
If your site uses SSL, then you must change the URL for about:blank with https://about:blank.
From what i searched.. it seems you need to identify the names. Some standard names like 'name', 'email', 'phone', 'address' are automatically saved in most browser.
Well, the problem is, browsers handle these names differenetly. For example, here is chrome's regex:
first name: "first.*name|initials|fname|first$"
email: "e.?mail"
address (line 1): "address.*line|address1|addr1|street"
zipcode: "zip|postal|post.*code|pcode|^1z$"
But chrome also uses autocomplete, so you can customize the name and put an autocomplete type, but i believe this is not for custom fields..
Here is chrome's standard
And it's another thing in IE, Opera, and Mozilla. For now, you can try the iframe solution there, so you can submit it. (Maybe it's something semi-standard)
Well, that's all i can help.
Make sure you're submitting the form via POST. If you're submitting via ajax, do <form autocomplete="on" method="post">, omitting the action attribute.
you can use "." in both iframe src and form action.
<iframe id="remember" name="remember" style="display:none;" src="."></iframe>
<form target="remember" method="post" action=".">
<input type="text" id="path" size='110'>
<button type="submit" onclick="doyouthing();">your button</button>
</form>

Categories

Resources