basic html text form - javascript

I want a text form for entering a string which is later read by javascript.
<form style='margin:10px;'>
Input Value: <input type="text" value="3" id="input" name="input"/>
</form>
I'm noticing that when I press enter while it's selected causes the page to be reloaded. This is not what I want. How do I make it not reload the page when the form is "submitted"?

Do you need the <form> tags? They don't seem to be doing anything. If you remove them you will no longer get that submission behaviour when you hit enter.

Pressing enter is submitting the form. You can use Javascript to prevent the form from being submitted - one way of doing that is by using a submit button:
<input type="submit" onsubmit="formhandle(); return false;">
Create a formhandle() function in Javascript to do the processing you want to do. Returning false should prevent the form from being posted back to the server - however, that doesn't always work. There's more detailed information on preventing default actions in browsers here:
http://www.quirksmode.org/js/events_early.html

You have to catch the form send with JScript and send it to the server with ajax
<form style='margin:10px;' id='formID'>
Input Value: <input type="text" value="3" id="input" name="input"/>
</form>
the JQuery (you can use Prototype or pure JS if you want) code goes a litte something like this
$('#target').submit(function() {
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType,
});
return false;
});
The return false prevents the page from reloading. The documentation can be found here

Related

Multiple form submit with one Submit button

I have two forms. I want to submit both forms with 1 button. Is there any method that can help me do it?
Example:
<form method="post" action="">
<input type="text" name="something">
</form>
<form method="post" action="">
<input type="text" name="something">
<input type="submit" value="submit" name="submit">
</form>
I want both forms to be submitted with 1 submit button. Any help would be appreciated.
The problem here is that when you submit a form, the current page is stopped. Any activity on the page is stopped. So, as soon as you click "submit" for a form or use JavaScript to submit the form, the page is history. You cannot continue to submit another page.
A simplistic solution is to keep the current page active by having the form's submission load in a new window or tab. When that happens, the current page remains active. So, you can easily have two forms, each opening in a window. This is done with the target attribute. Use something unique for each one:
<form action='' method='post' target='_blank1'>
The target is the window or tab to use. There shouldn't be one named "_blank1", so it will open in a new window. Now, you can use JavaScript to submit both forms. To do so, you need to give each a unique ID:
<form id='myform1' action='' method='post' target='_blank1'>
That is one form. The other needs another ID. You can make a submit button of type button (not submit) that fires off JavaScript on click:
<submit type='button' onclick="document.getElementById('myform1').submit();document.getElementById('myform2').submit();" value='Click to Submit Both Forms'>
When you click the button, JavaScript submits both forms. The results open in new windows. A bit annoying, but it does what you specifically asked for. I wouldn't do that at all. There are two better solutions.
The easiest is to make one form, not two:
<form action='' method='post'>
<input type='text' name='text1'>
<input type='text' name='text2'>
<input type='submit' value='Submit'>
</form>
You can place a lot of HTML between the form tags, so the input boxes don't need to be close together on the page.
The second, harder, solution is to use Ajax. The example is certainly more complicated than you are prepared to handle. So, I suggest simply using one form instead of two.
Note: After I submitted this, Nicholas D submitted an Ajax solution. If you simply cannot use one form, use his Ajax solution.
You have to do something like that :
button :
<div id="button1">
<button>My click text</button>
</div>
js
<script>
$('#button1').click(function(){
form1 = $('#idIFirstForm');
form2 = $('#idISecondForm');
$.ajax({
type: "POST",
url: form1.attr('action'),
data: form1.serialize(),
success: function( response ) {
console.log( response );
}
});
$.ajax({
type: "POST",
url: form2.attr('action'),
data: form2.serialize(),
success: function( response2 ) {
console.log( response2 );
}
});
});
</script>
You could create a pseudo form in the background. No time to write the code, jsut the theory. After clicking submit just stop propagation of all other events and gather all the informations you need into one other form you append to document (newly created via jquery) then you can submit the third form where all the necesary infos are.
Without getting into why you want to use only 1 button for 2 forms being submitted at the same time, these tools that will get the input data available for use elsewhere:
Option 1...
Instead of using <form> - collect the data with the usual Input syntax.
ex: <input type="text" name="dcity" placeholder="City" />
Instead of using the form as in this example:
<form class="contact" method="post" action="cheque.php" name="pp" id="pp">
<label for="invoice">Your Name</label>
<input type="text" id="invoice" name="invoice" />
<button class="button" type="submit" id="submit">Do It Now</button>
</form>
use:
<label for="invoice">Your Name</label>
<input type="text" id="invoice" name="invoice" />
<button type="button" onclick="CmpProc();" style="border:none;"><img src="yourimage.png"/> Do It Now</button>
Then code the function CmpProc() to handle the processing/submittion.
Inside that function use the Javascript form object with the submit() method as in...
<script type="text/javascript">
function submitform() {
document.xxxyourformname.submit();
}
</script>
Somehow I suspect making the two forms into one for the POST / GET is worth reconsidering.
Option 2...
Instead of POST to use the data to the next page consider using PHP's $_SESSION to store each of your entries for use across your multiple pages. (Remember to use the session_start(); at the start of each page you are storing or retrieving the variables from so the Global aspect is available on the page) Also less work.
Look man. This is not possible with only HTML. weither you gether the inputs in one form or else you use jquery to handle this for you.

Update form fields without refresh (prevent duplicated form)

I need to update (submit) form without refresh. I know it should be done using Ajax, so I found many examples on this website, but none of them was useful in my case. Here's the catch - I don't need to display any "success" or similar messages when form was submitted, I need to display exactly the same form, but with new values.
Examining examples on this site, I got it working, but when form is submitted via ajax (this part works fine), I see two forms displayed. Here's the example - http://www.lipskas.com/form/ (the whole source is available to view)
What should I change here?
P.S. If I change "$('#msg').html(html);" to "$('#myForm').html(html);" duplicated form doesn't appear, except one "little" problem - the form can be submitted only for the 1st time. Then no more values are properly submitted.
In case you are interested why I need to display exactly the same form (but with updated fields) again, it's because I built some type of calculator which has many fields, and when user updates ANY field, re-calculations are made ( http://lipskas.com/bandymas/ )
Get rid of the "onclick" in the submit button and add this in the header above the chk function
<body>
<form id="myForm">
<input type="text" name="username" value="submitted - "><br/>
<input type="text" name="password" value="submitted - "><br/>
<select name="some_array[1]"><option value="1">1</option><option value="2">2</option></select>
<select name="some_stuff[2]"><option value="3">3</option><option value="4">4</option></select>
<input type="submit" name="submit_ok" value="test me">
</form>
</body>
function chk(this)
{
$.ajax({
type:"post",
url:"index.php",
data: this.serialize(),
cache:false,
success: function (html){
$('body').html(html);
}
});
}
$(function(){
$("body").on("submit","#myForm",function(){
chk($(this));
return false;
});
});

PHP included JavaScript is not working properly in Jquery Mobile

In my jquery mobile web app I include a Login-Form on every page the user is navigating to. I do that so that the user could login at every time he wants to, not just on the start page.
Since I do the Form submitting procedure with my very own Ajax logic, I disabled the Jquery Mobile Ajax logic with data-ajax="false" on the Form. The Ajax logic is implemented with JavsScript. On the start page everything works fine, but if I navigate to another page (through a link on the start page), my JavaScript is not firing anymore, but the form is submitted via the Jquery mobile own Ajax logic (and therefore it don't works).
The code (which I include at every page) looks like this:
<div data-role="fieldcontain">
<form id="loginForm" data-ajax="false" onsubmit="login();return false;">
<div data-role="fieldcontain">
<h2>Login</h2>
<label for="textinput1">
Email
</label>
<input name="emaillogin" id="textinput1" placeholder="Email" value=""
type="text">
<label for="textinput2">
Password
</label>
<input name="passwordlogin" id="textinput2" placeholder="Password" value=""
type="password">
</div>
<input type="submit" data-icon="ok" data-iconpos="left" value="OK">
<input type="hidden" name="inputCase" value="login">
</form>
</div>
The JavaScript (which is just at the end of the Code stated above) looks like that:
<script>
function login()
{
var request = $.ajax({
url: "../case.php",
type: "POST",
data: $('#loginForm').serialize(),
dataType: "json"
});
request.done(function(msg) {
if(parseInt(msg.status)==1)
{
//top_notification("Willkommen zurück!","success");
window.location="index.php";
}
else if(parseInt(msg.status)==0)
{
alert(msg.text);
}
else {
alert("Gibts nicht");
}
});
request.fail(function(jqXHR, textStatus) {
alert("Fehler");
});
}
</script>
Maybe I got the Jquery Mobile "we replace just the page-div with the other page-div from the new URL" thing wrong, but I understand it in that way that my whole JS logic will also be pulled from the new ressource.
EDIT Thanks. I have updated my JS code, which looks now like that:
<script>
$(document).on('pageinit', '[data-role="page"]', function(){
$(document).on('click','#submit-btn',function() {
login();
});
});
function login()
{
var request = $.ajax({
url: "../case.php",
type: "POST",
data: $('#loginForm').serialize(),
dataType: "json"
});
request.done(function(msg) {
if(parseInt(msg.status)==1)
{
//top_notification("Willkommen zurück!","success");
window.location="index.php";
}
else if(parseInt(msg.status)==0)
{
alert(msg.text);
}
else {
alert("Gibts nicht");
}
});
request.fail(function(jqXHR, textStatus) {
alert("Fehler");
});
}
</script>
BUT. Now when I navigate to 3 pages, and then submit the login Form, I will get 3 alerts (even when I navigate to just 1 site) of the request.fail function... after that the login goes correctly!
Ajax is still your problem. You have disabled ajax form submition but ajax is still used to load additional pages. This is just my assumption because you didn't mentioned that ajax is turned off all together.
If ajax is still used to load pages all your other pages are loaded into the DOM. Because of this you will have multiple forms with a same ID. When your first page is loaded there's only 1 form in a DOM and that form is used. But when another pages is loaded then additional form (with a same id) is added to the DOM. And whey you click a submit button jQuery will find first form with that ID from the DOM. And because there are 2 of them it will submit first for, same form loaded with an initial page.
That is why you NEVER use inline javascript with jQuery Mobile.
Instead of
onclick="..."
Your submit button should have an id and make it type="button".
<input type="button" data-icon="ok" data-iconpos="left" value="OK" id="submit-btn">
Put a click event on every button and use a $.mobile.activePage selector to find a form on an currently active page.
$(document).on('click','#submit-btn',function() {
$.mobile.activePage.find('#loginForm').submit();
});
Also everything should be wrapped inside a correct jQuery Mobile page event:
$(document).on('pageinit', '[data-role="page"]', function(){
$(document).on('click','#submit-btn',function() {
$.mobile.activePage.find('#loginForm').submit();
});
});

Create a Form element using javascript and submit it without redirecting/refreshing

I am using a Form in a LightBox which contains some input element.
<form name="imageUploadForm" action="uploadImage.do" method="post" enctype="multipart/form-data">
<input type="text" id="id" name="id" style="display: none;" value="">
<div id="fileUploaderDiv">
<input type='file' name="file0" id ="file0" />
</div>
<button onclick="javascript:ImageUploader.attachImage();">Upload</button>
</form>
can anybody tell me how to copy this form in new one and submit it without redirecting user or knowing him about form submission using javascript or jquery?
http://api.jquery.com/serialize/
$('#yourbutton_notintheexample_you_provided').click(function(){
var myForm = $('form[name=imageUploadForm]')
var data = myForm.serialize();
$.ajax({
url: myForm.attr('action'),
type: myForm.attr('method'),
data: data,
success: function(){
window.alert("write your form handling code here")
}
});
});
or something along the lines.
In prototype, there was a single convenience method, called Form.request, read about it here.
In order to send data to a server (through submitting a form or otherwise) one can use AJAX. The user does not need to be informed (but I'd recommend letting the user know somehow).
JavaScript tutorial
jQuery docs

Jquery .load and POST data

This is really frustrating I would appreciate some help with this. I have a div, called comments and a form inside of that div. What I want to do is post a form to the current page and have it load inside of the div without reloading the entire thing. Here is my current code:
<div id="comments">
<form action="#" method="post" onsubmit="return false;" >
<input type="hidden" name="txtname" value="test">
<textarea id="wysiwyg" name="wysiwyg" rows="5" cols="50"></textarea>
<input type="submit" name="post" id="post" value="Submit">
</form>
<script type="text/javascript">
EDIT: Read edit below for current code
</script>
</div>
When I submit, the alert fires, but the page does not load. It works fine if I make the event as follows:
$("#comments").load("comments.asp");
It's not liking the posting of data. I have used .load before but never to post data. I got the above code from these very same forums.
I'm honestly not sure of the purpose of 'name' and 'tel' - do I refer to those variables or the form variable names when processing the code? This is in ASP classic.
What's wrong with the above code, how can I get it to send data from the forum via POST? Thanks!
EDIT:
I am now using the following code:
$("#post").submit(function(event){
var $form = $(this),
$inputs = $form.find("input, select, button, textarea"),
serializedData = $form.serialize();
$inputs.attr("disabled", "disabled");
$.ajax({
url: "/comments.asp",
type: "post",
data: serializedData,
success: function(response, textStatus, jqXHR){
console.log("comment posted");
},
error: function(jqXHR, textStatus, errorThrown){
console.log(
textStatus, errorThrown
);
},
complete: function(){
// enable the inputs
$inputs.removeAttr("disabled");
}
});
event.preventDefault();
});
And now it's using properly getting the form handled...however it goes to comments.asp. How can I make all the action happen in a certain div (comments div?)
It seems to me you are blending a bunch of different techniques in a way that is not entirely coherent.
$.post is a shortened version of $.ajax (see here).
$.load takes a url and sticks it into a <div> or other DOM Element (see here).
If I understand it correctly (and I may not!), you're not really wanting to load the form, but put values into the form fields. $.load is an odd way to do this. (It may work, but I do it another way.)
If you're using $(#...).submit, you can also leave out a whole bunch of stuff in your form. The following should work fine.
<form id="form_id">
...
<input type="submit" value="Submit">
</form>
My method is: (1) have a hardcoded HTML form (or build it by AJAX), (2) get the values from the DB (or wherever) using $.post (or $.ajax), (3) stick the values into the form using .val() (or equivalent - whatever is right for the input type) and the DOM id of that input, and then (4) use .submit (in a manner similar to yours). You will need to add preventDefault as the others have suggested.
You're also muddying the waters using #post as the DOM id. You really want to give the form itself the ID, and then use $(#form_id).submit(... I can't test it now, but having the submit on the input field may cause some grief. The official example attaches the .submit to the form id.
I'm also not sure the <div> with id 'comments' really does much. I have a container id like your 'comments', but that's because I build forms by AJAX and stick them into the container. If you don't need to do that, the id 'comments' is unnecessary to the whole procedure.
Your text box element dont have an id with value txtname. But in your script you are trying to access using # (which is supposed be with an id context). So add an id element to your input box.
<input type="hidden" name="txtname" id="txtname" value="test">
And as expascarello said, You need to stop the default behaviour of the submit button . Other wise it will do the normal form posting so you wont be able to feel the ajax effect.
Use preventDefault
$(function(){
$("#post").click(function(e) {
e.preventDefault()
alert("clicked");
$("#comments").load("comments.asp", {
'name': $("#wysiwyg").val(),
'tel': $("#txtname").val()
});
});
});
You are not cancelling the clicking of the button so the form is submitting and resetting the page.
$("#post").click(function(evt) {
evt.preventDefault();
...
jQuery event.preventDefault()
The load() method does a get and not a post.

Categories

Resources