Ensuring form does not submit on enter but instead runs function - javascript

I think that I understand that "button" are supposedly the correct way to achieve the result I desire; somehow they are supposed to be different from submit buttons. But I don't understand how to get the result I want.
I have the following:
<form action="http://www.google.com">
<input type="text" id="box1">
<button id="button1" onclick="myFunction()">Submit</button>
</form>
If a user clicks the button, the function runs correctly. (The function ultimately pulls the value from box1) and does something with it). However, if while the user has their cursor inside the textbox, they hit enter on their keyboard, the form submits and links to google.
How can I make it so that hitting enter in box1 does not change the page, and instead runs myFunction?

Add proper event handlers and listen for the submit event instead
<form action="http://www.google.com" id="myForm">
<input type="text" id="box1">
<button id="button1">Submit</button>
</form>
<script type="text/javascript">
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
myFunction()
}, false);
</script>
FIDDLE

Related

onclick event submits when button clicked but not when enter is pressed on keyboard?

I'm only using HTML and JavaScript.
I have one form
<form id="form1">
<input name="name" type="text" size="20">
</form>
And one button
<button onclick="outputname()" type="submit">Search</button>
So the idea is the user types a number on the form and clicks the search button and an action is performed (this works great).
However, if the user enters a number and hits the Enter button on keyboard the page is refreshed. The same happens on iPad. ("Return" button is displayed instead of "Go").
So I want the Enter button to work on keyboard and Go to work on iOS.
The idea is that the user enters a customer number and the relevant details are displayed.
Give an ID to both your input field and button, to be sure you trap the correct one:
HTML:
<form action="destination.html" method="post">
<input id="foo" name="name" type="text" size="20">
<button id="mybutt" onclick="outputname()" type="submit">Search</button>
</form>
Note that destination.html is where you want the data posted to. If you want it posted to the same file, just use: action="" or leave it out.
Javascript:
document.getElementById('foo').onkeypress = function(e){
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '13'){
var btn = document.getElementById('mybutt');
mybutt.click();
return false;
}
}
Sources:
How to detect when the user presses Enter in an input field
Capturing the Enter key to cause a button click with javascript
Insert this:
action="post"
Inside your form tag. I.e., your form tag will have to be this way
<form id="form1" action="post">
In this case, you could manage the submit event, instead of key/click events.
<form id="form1" onsubmit="outputname()">
Submission events triggered by either a click or pressing enter will call outputname.

Input validation Javascript

In a Windows 8 Javascript app I'm trying to validate the user's input and keep the results on screen after the user presses Apply by using the following:
<form>
<input id="test" type="number" min="1" max="10" />
<button id="button" type="button">Apply</button>
</form>
But when I click Apply the validation doesn't work. It only works if I replace type="button" with type="submit". The problem is that submit refreshes the page and the results disappear. What can I do?
Here is an example of what I'm trying to do: JSFiddle
UPDATE:
I changed my code to this:
<buton id="button" type="submit" onsubmit="doTest(); return false;">Apply</button>
but it still refreshes my page.
Form validation does not fire until the onSubmit event fires, the behavior is as designed.
One thing you could do is set the for to have an "onSubmit" event, change the button to a submit type, then in the onSubmit function call the event.stopPropigation to stop the page from doing a full postback.

Best way to form submission without using form action in JavaScript

I am building a PhoneGap application using JavaScript, HTML and jQuery Mobile.
All the HTML is in the same file, separated into <div data-role="page"> as pages.
Several pages have a form including one or more text/selection input and a submit button.
The submit is not a traditional form submit button but a button which using onClick runs a JavaScript function which can do many things.
I want the form to have this features:
When pressing the button and after running the function, clear the form.
In some cases the function should change the page.
The enter button on one of the inputs should submit the form (Activate the function).
Should I use the form HTML tag? If so what should I use for action? How to clear the form?
etc.
If you are trying to bind onClick to an input type="submit" then you're gonna have a bad time.
Unfortunately even if you return false or e.preventDefault when clicking that button, the form still sends the submit trigger so once your onClick code is finished then it will submit.
Example:
<form action="woot.php" method="POST">
<input type="submit" value="submit" onClick="alert('You clicked me! How could you?! It's cool the form will still go to woot.php. return FALSE wont help you either.'); return FALSE;">
</form>
What you probably want to do:
<form action="woot.php" method="POST">
<input type="submit" value="Submit" onSubmit="alert('You aint goin nowhere!'); return FALSE;">
</form>
What you should do:
<form action="woot.php" method="POST">
<input type="button" value="Button" onClick="alert('Away with you!'); window.location = 'http://www.google.com/';">
<input type="button" value="Button" onClick="someCoolFunction();">
</form>
I wouldn't use type="button", especially if you want to have the best chance of the form submitting when the user presses enter.
Use your regular form <input type="submit"> and then your JavaScript:
$('form').submit(function(e) {
// all your form handling here;
if (your_form_was_validated_and_handled) {
$('input[type!="submit"]').val('');
}
e.preventDefault();
});
Generic fiddle: http://jsfiddle.net/
You can still use the form tag, as it's useful for markup.
Just make sure that your buttons have attribute
type="button"
otherwise the button will submit the form by default.
To reset the form:
function resetForm() {
$('#form').each(function(){
this.reset();
});
}

Input field with onchange fails to trigger when user click button in another form

I have a page with multiple small forms on it. Each form has one input field that has an onchange function which will submit it's form to a url that returns a no data status.
Things work fine, submitting form after form, until the user clicks on a small form that has ONLY a submit button in it. This click works, but abandons the change in the previous field resulting in its onchange not firing the click at the bottom of the changed function fails (still trying to understand the firebug trace).
What's going on? is there a fix for my structure?
UPDATE:
First I tried simply delaying the action of the submit, but no luck.
I have hidden the and added an <input button> to the chain of "events" so that the focus has a place to come to rest before the real submit tries to happen -- the code below has been updated. So the question now becomes:
Is this as simple as it can be?
Script:
$(function() {
$('input,select').change(changed);
});
function changed(){
...
$(this).parents('form').find(':submit').click();
}
function doSubmit(elt, id)
{
$(elt).focus();
setTimeout(function(){
$(id).click();
}, 400);
}
One of may small forms:
<form class="clean" method="POST" action="QuoteProApp.php">
<input type="submit" value="field" name="btn_update" style="display: none;">
<input type="hidden" value="000242" name="quote_id">
<input type="text" maxlength="15" size="3" value="" name="q[cost][4][1][unit]">
</form>
The offending click goes into this form:
<form class="clean" method="POST" action="QuoteProApp.php">
<input type="hidden" value="000242" name="quote_id">
<input type='button' name='btn_close' value='Close' onclick='doSubmit(this,"#CLOSE");'>
<input id='CLOSE' type='submit' name='btn_close' value='Close' style='display:none;'>
</form>
Might be totally irrelevant, but your selector for the change event includes your submit input too. Can you change it to:
$('input[type="text"],select').change(changed);
to see if anything changes?
The solution turned out to be to create a button tag, set the focus explicitly to a it, and then set a timeout to click the real, but hidden, submit input tag. This allows the change in focus to run the submit associated with it and then continue with the explicit submit of the page.
The question has been updated to show this solution.

Using input type="submit" to change content

Okay, I'm pretty sure I'm missing something very obvious here, but I just couldn't find a proper solution so far. What I'm trying to do is simple: Have a user write something into a form, have him submit the form, and write that input into a textarea on the same page.
This is my code:
<html><head></head>
<body>
<form name='registration'>
<label for="input">Input:</label>
<input type="text" id="input"/>
<input type="submit" id="submit" value="Submit" onclick="execute()"/>
</form>
<div id="results">
<span>Result</span>
<span><textarea cols="30" rows="5" id="resulttext" readonly="readonly"></textarea> </span>
</div>
<script>
function execute()
{
var result = document.getElementById("input").value
document.getElementById("resulttext").value=result;
}
</script>
</body>
</html>
Now what happens if I enter something into the form is that the textarea briefly shows my input before reverting back to showing nothing. My guess is that the textarea field is only changed for the duration of the execute() function.
When I change input type="submit" to a <button> everything works as intended, but I'm pretty sure I'm not supposed to do that.
You need to cancel the default event for the submit button, otherwise it just submits the form (which in this case essentially reloads the page since there are no form elements with names). Add return false;after execute() (put a ; in between the two pieces)
Because your button is of type submit, it will submit your form after executing the execute() method. You can change the button type to type="button" and you will not have this submit behavior.
http://jsfiddle.net/PCCbh/
Note - using <button> is okay in this case. It is essentially the same as <input type="button".

Categories

Resources