Setting a form variable value before submitting - javascript

I have a page where you can view a hotel's information. On this page is a little form to search for room availability for the hotel page you are on.
<form id="form1" name="form1" action="search.asp" method="POST">
<input type="hidden" id="Hotel" name="Hotel" value="<%= HotelID %>">
Arrive: <input value="<% strURLBookingDate %>" type="text" id="ArrivalDate" name="ArrivalDate">
Depart: <input value="<% strURLBookingDate2 %>" type="text" id="DepartureDate" name="DepartureDate">
<input type="submit" name="btnHotelSearch" value="Search This Hotel">
<input type="submit" name="btnHotelSearchAll" value="Search All Hotels">
</form>
But I also need to add a button to the form that will allow me to search all hotels if I click it. For that to happen, I just need to set the hidden input value named "Hotel" to 0 when the button is clicked.
How can I set that hidden value before the form is submitted when I click btnHotelSearchAll?

You can hook the click event on btnHotelSearchAll and then fill in the value:
document.getElementById("btnHotelSearchAll").onclick = function() {
document.getElementById("Hotel").value = "0";
};
Be absolutely certain there's nothing else on the page that has either the id or name "Hotel", and that you don't have any global variables you've declared with that name, because some versions of IE have bugs where they conflate name values and global variable names into the namespace they use for document.getElementById. Or, alternately, make the id on the hidden field a bit more unique (the name can stay as it is so you don't have to change the backend; the id is only client-side, the name is what's sent to the server). E.g., you can do this:
<input type="hidden" id="HotelField" name="Hotel" value="<%= HotelID %>">
^
and then change the code a bit:
document.getElementById("btnHotelSearchAll").onclick = function() {
document.getElementById("HotelField").value = "0";
// ^
};
Update:
Note that the code to hook up the button must run after the button has been put in the DOM. So with the code above, that means making sure that the script block is below the form in the page, like this:
<form ...>
....
</form>
...
<script>
...
</script>
If the script block is above the button, then the button won't exist yet as of when the script runs. This is one reason why it's frequently best to put scripts at the end of the body element, just before the closing </body> tag (more here).
If you really want the script above the button, you have to delay the call by making it an onload event handler or that sort of thing. But window.onload happens very late in the process of a page load (it waits for all images and other assets to load, for instance), long after your users may be interacting with your form, so usually best to do it sooner.
Off-topic: My standard note that a lot of this stuff is made earlier and more robust by using a decent JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others. jQuery, for instance, will deal with the IE bugs in document.getElementById for you so you don't have to worry about the conflation problem.

If you'd like to use jQuery, try the following.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" ></script>
<script type="text/javascript" >
$(function(){
$('#btnHotelSearch').click(function(){
$('#Hotel').val(0);
});
});
</script>

using onclick attribute to call javascript function that will set the hidden field value
<input type="submit" name="btnHotelSearchAll" value="Search All Hotels" onclick="SetHotelID();">
<script>
function SetHotelID()
{
$('#Hotel').val('0');
}
</script>
Note I am using Jquery

Here you go, let me know if this works...
<form id="form1" name="form1" action="" method="POST">
<input type="hidden" id="Hotel" name="Hotel" value="<%= HotelID %>">
Arrive: <input value="<% strURLBookingDate %>" type="text" id="ArrivalDate" name="ArrivalDate">
Depart: <input value="<% strURLBookingDate2 %>" type="text" id="DepartureDate" name="DepartureDate">
<input type="submit" name="btnHotelSearch" value="Search This Hotel">
<input type="submit" name="btnHotelSearchAll" value="Search All Hotels" onclick='document.getElementById("Hotel").value="0"'>

Related

javascript redirect isnt working

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>

Multiple form with same form-name. But I want to send that form value that is being selected

In my website, I am retrieving multiple previously saved addresses from the database and showing them on my website. Now, the user can select any one of them and the data of the address selected will be send to the next page to be inserted into the database.
http://tinypic.com/r/2lj70i9/5
My jsp code to fetch address:
<a href="javascript:next()">
<div class="address1">
<form name="form2" method="post">
<input name="name" type="text" readonly="readonly" value="<% out.print(x1); %>" style="font-weight: bold;" />
<input name="address" type="text" readonly="readonly" value="<% out.print(x2);%>"/>
<input name="city" type="text" readonly="readonly" value="<% out.print(rs1.getString("city"));%>"/>
<input name="state" type="text" readonly="readonly" value="<% out.print(rs1.getString("state"));%>"/>
<input name="pin" type="text" readonly="readonly" value="<% out.print(rs1.getString("pin"));%>"/>
<input name="phone" type="text" readonly="readonly" value="<% out.print(rs1.getString("mob"));%>"/>
</form>
<div class="selectLine">Click to Select</div>
</div>
</a>
and my Javascript is:
function next()
{
var f=document.forms["form2"];
f.method="post";
f.action='checkout3.jsp';
f.submit();
}
but the problem is whatever I'm selecting only the top address is being fetched to the next page.
Currently your anchor elements all call your next() function without passing any information about which item was selected. You could change that by using onclick='next(this)' so that your function gets a reference to the clicked anchor, but it's generally best not to include JS directly inside your html - especially if you're using a library like jQuery which makes it really easy to set up event handlers. (I assume you are either using jQuery already or are open to it given you added the jQuery tag to your question.)
I'd suggesting changing your anchor from:
<a href="javascript:next()">
...to something like:
<a class="selectAddress">
And then instead of your next() function you can use a jQuery-based click handler as follows:
$(document).ready(function() {
$("a.selectAddress").click(function() {
$(this).find("form")
.prop("action", "checkout3.jsp")
.submit();
});
});
That is, bind a click handler to all anchors with that class. Within the handler, this will be the particular anchor clicked, so you can use the .find() method to select the form that is a descendant of the anchor, then set its action property, then submit it. Note that your form has method="post" in its html, so there's no need to set this again like you do in your next() function.

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>

Javascript injection

I would like to fill out and a submit a form explicitly with JavaScript. First, I thought I had to use window.open but it's certainly wrong because if it gets loaded, the left of my scripts written for example in a html file would be ignored.
Do I have to create a .js file and fire that one?
uhhhh...not exactly sure how this relates to injections...you can do this with jQuery in a handful of lines of code.
say you have the following form:
<form id="theForm" name="testForm" action="whatever.php" method="get">
<input type="text" name="cow" />
<input type="text" name="sheep" />
<input type="text" name="pig" />
<input type="submit" value="Submit" />
</form>
If you have jQuery loaded, all you need to do is this:
function submitForm(){
var cowVal="Cows go moooo!";
var sheepVal="Sheep go baaaaaaah!";
var pigVal="pigs go sooooeeeeeeeh!";
$("#theForm input").eq(0).val(cowVal).next().val(sheepVal).next().val(pigVal).parent().submit();
}
Hope that helps!

How to get function to fire when buttonless form is submitted

I have a page with many forms on it. could be 1..200. None of these forms have buttons and they are built programatically. I am using jquery to submit all the forms that are checked.
function FakeName()
{
$("input:checked").parent("form").submit();
}
My forms look like:
<form name="FakeForm<%=i%>" action="javascript:void%200" onSubmit="processRow(<%=i%>)" method="post" style="margin:0px;">
<input type="checkbox" name="FakeNameCheck" value="FakeNameCheck"/>
<input type="hidden" name="FakeNum" value="<%= FakeNum%>"/>
<input type="hidden" name="FakeId" value="<%=FakeIdr%>"/>
<input type="hidden" name="FakeAmt" value="<%=FakeAmount%>"/>
<input type="hidden" name="FakeTrans" value="FakeTrans"/>
</form>
Note: action is set to "javascript:void%200" so that it posts to a fake page. I want to handle my own posting in processRow.
OnSubmit never gets called and therefore ProcessRow never gets called.
Obviously all the names of the functions and variables have been changed to protect their identity :D
How can I get a function in each form to fire when I call submit programmatically.
The onsubmit handler is deliberately not triggered when you programatically submit the form. This is to avoid infinite recursion if an event handler would cause the event to be triggered again (and therefore the event handler to be called again)
However, of course you can call the processRow() function yourself in place of the .submit() call.
You're allowed to have inputs outside of forms. One school of thought is that a <form> shouldn't be a <form> if it's not intended to be submitted to the server via HTML.
Look up dispatchEvent and it's equivalent fireEvent. It's not the easiest thing in the world to use, but I think that's what you are looking for.
I'm surprised that there's no library that helps with this easily. Prototype (the one I've used the most) comes closest with a .fire() method on elements.
Looks like I may be able to do this:
<form name="FakeForm<%=i%>" action="javascript:processRow(<%=i%>)" method="post" style="margin:0px;">
<input type="checkbox" name="FakeNameCheck" value="FakeNameCheck"/>
<input type="hidden" name="FakeNum" value="<%= FakeNum%>"/>
<input type="hidden" name="FakeId" value="<%=FakeIdr%>"/>
<input type="hidden" name="FakeAmt" value="<%=FakeAmount%>"/>
<input type="hidden" name="FakeTrans" value="FakeTrans"/>
</form>
Are there any drawbacks to this?

Categories

Resources