Set submit button to another when clicking enter - javascript

I'm trying to set the submit button in an ASP.NET website to another submit button when clicking enter key on the keyboard. I've so far accomplished to do so, but problem is it still sends the second submit button too. I tried returning false in the onkeypress event in the input elements, but then it won't let me write anything to the text input boxes..
This is my javascript function:
function button_click() {
if (window.event.keyCode == 13) {
document.getElementById("msSend").focus();
document.getElementById("msSend").click();
}
}
And a sample text input box:
<input type="text" id="msname" name="msname" runat="server" onkeypress="button_click()" /></td>
Any suggestions?

I fixed it! I had some buttons in my MasterPage that was for some reason defined as type="submit".
I changed:
<button name="bmenu" onclick="DisableHL('bmenu'); location.href='<%= movies %>'; return false;" class="btn">סרטים</button>
to:
<button name="bmenu" onclick="DisableHL('bmenu'); location.href='<%= movies %>'; return false;" class="btn" type="button">סרטים</button>
And there it fixed it! ;)

Related

Can't Get Form to Submit Properly [duplicate]

The title speaks for itself... I have a couple of forms, one of them is just a single text input form and the other one is composed by two text inputs. I do not want any submit button in any of them, I want each form to submit whenever the user presses the ENTER button at any text input:
The form composed by just one input submits everytime the user presses the ENTER button - Perfect!
The second form composed by two text inputs does not behave this way, it does not submit when the user presses the ENTER button at any of both inputs.
Is there a way to make a form with more than one text input behave this way and avoid having a submit button in it?
Try adding this between the <form></form> tags
<input type="submit" style="display: none" />
Tested it and it works on Firefox and Chrome. If you have a submit input type in the form, enter should automatically submit it, regardless of whether it's visible or not.
I am actually using this myself in a login form, though in the username field, it makes more sense to move to the next field than to submit. Just in case you have a similar use case, here's the code I used (requires jQuery)
$('#username').keypress(function(event) {
if (event.keyCode == 13 || event.which == 13) {
$('#password').focus();
event.preventDefault();
}
});
Note that there is a slight bug though -- if the user selects a browser autocomplete username and presses enter, it still moves to the next field instead of selecting it. Didn't have time to debug this, but if someone can figure out how to fix it, that would be cool.
I was looking for a solution to this problem and want to share my solution, based on many posts over here. (Tested on modern Chrome/Firefox/IE)
So, using only Javascript the follow code submits the form if ENTER key is pressed on any field or if the button Submit is pressed. After that it clear/reset the form, which is a nice thing to do.
Hope it helps.
<!DOCTYPE html>
<html>
<body>
<p>Based on http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_ev_onsubmit</p>
<p>When you submit the form, a function is triggered which alerts some text.</p>
<div onKeyPress="return myFunction(event)">
<form id="form01" action="demo_form.asp" onsubmit="return false;" >
Enter name: <input type="text" name="fname">
<input type="button" value="Submit" onclick="myFunction(0)">
</form>
</div>
<script>
function myFunction(e) {
if((e && e.keyCode == 13) || e == 0) {
alert("The form was submitted");
document.forms.form01.submit();
document.forms.form01.fname.value = ""; // could be form01.reset as well
}
}
</script>
</body>
</html>
Be sure that your inputs are inside "form" element and give the "form" element an "action" attribute.
You will have to look for the Enter key press. This post here shows how to do that.
Enter key press event in JavaScript
You can use the code below to submit a form after pressing Enter.
<input id="videoid" placeholder="Enter the video ID">
<button id="mybutton" type="button" onclick="myFunction()">Submit</button>
<script>
var input = document.getElementById("videoid");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("mybutton").click();
}
});
</script>

Flask/html - submit only one button on Enter key

I have folowing form:
<form method="post">
<input type="submit" name="submit" value="Save" class="button">
<input type="text" name="search_input" id="search_input">
<input type="submit" name="submit" value="Search" id="searchBtn" class="button">
</form>
Desired behavior is that when I enter some text to input field and hit Enter key, form shall post submit/Search and search_input.
Instead I get two separate posts:
request.form['submit'] =
ImmutableMultiDict([('submit', 'Save'), ('search_input', 'exampletext')])
ImmutableMultiDict([('search_input', 'exampletext'), ('submit', 'Search')])
I also tried to use following js, but the result is same:
var input = document.getElementById("search");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchBtn").click();
}
});
Do you have any idea, what's wrong and how to fix it?
From your js script i understand that you want the form to only click search and not save when you press the enter key?
If that is so then you need to change the name of the two buttons because form submit uses the name attribute to identify elements.
Since both your inputs have the same name you get two posts.
Edit: I just found out that the first submit in the form is clicked by default when you press the enter key (Without needing any js code), So in your case when you press the enter key the first button (Save) is pressed by default and from your js script the second button (Search) is pressed.
So you just have to put the search button on top of the save button and use CSS to change the order in the webpage

Javascript field validation not working properly

I am developing a web application in which I have created a form and in the onSubmit event of the form I have called a java script function which will check for "Field must not left blank" condition if it is left blank the form must not be posted so I have written following code:
Jsp Page Form
<form action="Result.jsp" name="validityCheck" onsubmit="return fnCheckEmptyField();">
<input type="text" name="txtIIDN" id="txtIIDN" style="font-size:medium;" onkeypress="return fnKeyPress(event)"/>
<input type="submit" id="btnValidityCheck" value="Check Validity" />
</form>
Javascript code is as follows
<script>
function fnCheckEmptyField()
{
var strDomain= document.getElementsByName("txtIIDN").value;
if(strDomain == null)
{
document.getElementById("lblValidityStatus").innerHTML="";
document.getElementById("lblValidityStatus").innerHTML="Domain Name Field Can't be Left Blank";
return false;
}
else
{
return true;
}
}
</script>
When I try to submit the form the javascript function gets executed and then form will gets posted whether the return value is true or false.
I dont want to submit the form when the return value is false i.e when field is empty
and also the condition in onsubmit event onsubmit="return fnCheckEmptyField(); showing me an error
Cannot return from outside a function or method.
Can you figure out what is the mistake I am commiting and possible solution for that?
Remove the onsubmit event on the form and In the submit button HTML, put this
<input type="submit" id="btnValidityCheck" value="Check Validity" onclick="return fnCheckEmptyField();" />
Adding on to what Furqan said, you should probably use the button and an onclick event to check the form, and if the form is valid, then call .submit() on your form.
I tend to not even use a submit button, I just have a normal button, and have it run javascript... then the javascript submits the form.
Example (HTML submit button):
<button id="btnValidityCheck" value="Check Validity" onclick="return fnCheckEmptyField();">Click Here</button>
Javascript function:
function fnCheckEmptyField() {
var strDomain= document.getElementsByName("txtIIDN").value;
if(strDomain == "") {
document.getElementById("lblValidityStatus").innerHTML="Domain Name Field Can't be Left Blank";
}
else {
document.getElementById("myFormId").submit();
}
}
Notice that if the javascript feel that the form is valid, THEN it will submit your form. You need to define an id for your form tag for this to work.
Also, I changed the == null check to == ""... that may have been causing issues...
Cheers!

Button onclick works fine but undesired behavior when pressing enter to submit form

I'm not sure if I need a form for this, it's a javascript that takes an input from a textbox, does some calculation on it, and displays the results in a div. I just want the user to be able to submit by clicking submit or by pressing enter.
In short, if the button type is "button", clicking works fine but pressing enter works strangely, and if the button type is "submit", pressing enter works fine, but clicking works strangely. Below is a sample of the code (removed some business logic and other variables that were working fine to make it simpler to display here):
<form action="#" onsubmit="calcserial()">
Serial no: <input type="text" name="serialno" id="serialno" /><br />
<input type="button" value="Submit" onclick="calcserial()" />
</form>
<script type="text/javascript">
function calcserial(){
var x=document.getElementById('serialno').value;
var year=[business logic];
var month=[business logic];
document.getElementById('results').innerHTML="Shipped: " + month + ", " + year;
}
</script>
<div id=results></div>
To give more detail about the strange behavior, when input type is "button" and I press enter, rather than running the calcserial() function, the textbox is cleared and the url is changed to:
[filename].php?serialno=[value]#
With [value] being what ever was in the text box. Then, if I put in the same exact value again and press enter again, it works as intended, but only if the url already shows the value I am submitting. If I enter a different value, the text box is cleared again and the url is changed to show the new value. If I switch the input type to "submit", the problem is resolved for pressing enter, but the same problem then occurs when clicking the button to submit.
Why is this happening? Any ideas how to resolve it? Thanks!
Try changing this:
<form action="#" onsubmit="calcserial()">
To this:
<form action="#" onsubmit="calcserial();return false;">
That should stop the default action that would normally happen on submit of a form, which in your case with action="#" results in the same page being reloaded.
Given that you don't actually want to submit anything (to the webserver) you don't really need a form for this. An <input type="button"> plus checking for enter onkeyup of the text input could achieve the same effect.

textbox should invoke button click event

I have a textbox and a button; the button click event navigates to other location in the website. I want to do the same thing on pressing the enter key but unable to do that. Please help me solve this. My code snippet follows:
function call()
{
document.location= "location.aspx";
}
<input type="text" id="txt1" onkeydown ="if(event.keyCode==13)document.getElementById('bt1').click()"/>
<input type="button" id="bt1" value ="Hit me" onclick ="call()" />
This is the same as the click, both would call this function...
onkeydown ="if(event.keyCode==13) call()"
If you can edit your HTML code, you wont probably need to do any JS to get this to working.
The INPUT fields in your HTML should be wrapped inside a FORM tag (atleast thats how it semantically makes more sense in most of the cases).
If you can do that, you can then change the INPUT element from TYPE button to Type SUBMIT and can then listen for the onsubmit event on your FORM element.
The event is fired both on pressing of enter key and click of the button and it works pretty smoothly across the browsers. The only problem is IE which doesnt fire the onsubmit event on a form with just 1 text input field. For that, you will have to insert another field into the form. You can hide it for your case. More ref at : http://style-vs-substance.com/development/form-submit-by-enter-key-and-internet-explorer/
EDIT: Code Sample
<form id="myForm">
<!--[if IE]>
<input type="text" style="display: none;" disabled="disabled" size="1" /><![endif]-->
<input type="text"/>
<input type="submit" value="Search"/>
</form>
Then in your JS:
var formHandler = document.getElementById('myForm');
formHandler.onsubmit = function(){
//this callback will be invoked both by the search button and enter key now
//your logic here
}

Categories