mvc - submit text input field when enter - javascript

I'm trying to use "Enter" in a text input field to submit the message (in SignalR chat). I've tried hundreds of methods, but can't seem to get it working.
I either wanna have it so when I press enter it clicks the btn or presses tab then enter.
here is the input and btn
<input class="form-control" id="message" maxlength="200" />
<input type="button" class="btn btn-default" id="sendmessage" value="Send" />

Change
<input type="button" ...
To
<input type="submit" ...
or
<button type="submit" ...
See also button type documentation.

If you don't want to use form submit, you can define the logic in javascript,
document.getElementById("message") // to get the text box
.addEventListener("keyup", function(evt) { // Keyup -> Any key pressed
if (evt.keyCode == 13) { // 13 for enter
document.getElementById("sendmessage").click();
}
});
For keycodes, you can refer this site

Related

detect the submit event when click enter key

If I have one form with actually different inputs for two submit requests. When I click on any submit button I can know what action to do.
but I need to detect in which input I'm when click Enter keyboard key.
<form class="main-form">
<div class="form_one">
<input class="form_one_input" type="text" id="form_one_input"/>
<button type="submit" class="form_one_button">Submit form one</button>
</div>
<div class="form_two">
<input class="form_two_input" type="text" id="form_two_input"/>
<button type="submit" class="form_two_button">Submit form two</button>
</div>
</form>
https://jsfiddle.net/m6433obp/
To detect which input you are in use the keyup event handler as:
$('.form_one').bind('keyup', function(e) {
if(e.keyCode === 13) {
alert($(this).attr('class'));
}
})
$('.form_two').bind('keyup', function(e) {
if(e.keyCode === 13) {
alert($(this).attr('class'));
}
})
check demo for this here
I am not really sure that I understand your question correctly. But I think that since you are using two submit buttons in the same form, you should give unique names to the buttons, so that on the server side you know that on hitting enter which input got submitted.
<form class="main-form">
<div class="form_one">
<input class="form_one_input" type="text" id="form_one_input"/>
<button type="submit" name="first_button" class="form_one_button">Submit form one</button>
</div>
<div class="form_two">
<input class="form_two_input" type="text" id="form_two_input"/>
<button type="submit" name="second_button" class="form_two_button">Submit form two</button>
</div>
</form>
And the code to check:
if (isset($_POST['first_button'])) {
} else if (isset($_POST['second_button'])) {
} else {
//no button pressed
}
Hope this is what you were looking for.

Javascript - Validate form if error found change form field background color to red

Ive got a form, when the user clicks on a field the value clears, when the user clicks submit, AND an error is found the background color of the field should change to red.
My problem
I manage to clear the value of the field when a user clicks it, and I managed to change the color of the field to red when an error is found, BUT when the error is found when the user clicks submit the background color only change to red for a split second and then the field value reapers again. Ive been battling away with this for the whole morning any help would be appreciated, code follows:
function validate(){
//form validation
var name=document.getElementById('name');
if (name.value == null || name.value==""){
name.style.backgroundColor="red";
}
<form id="enquire" method="post">
<h2>Test Drive an Audi Today</h2>
<input type="text" value="Name" class="textbox" id="name" name="name" onclick="if(this.value=='Name') this.value='';" /><br />
<input type="submit" name="submit" class="butt" value="Send" onclick="validate()" />
<span class="buttonText">We'll Call you Back!</span>
</form>
Change
<input type="submit" name="submit" class="butt" value="Send" onclick="validate()" />
<span class="buttonText">We'll Call you Back!</span>
to
<input type="submit" name="submit" class="butt" value="Send" onclick="return validate()" />
<span class="buttonText">We'll Call you Back!</span>
The closing bracket of the function is missing.
function validate(){
//form validation
var name=document.getElementById('name');
if (name.value == null || name.value==""){
name.style.backgroundColor="red";
return false; // add this line
}
} // This was missing

Submitting form with enter button in Ajax

My issue is that when I click my button, it will work properly, but if I use the enter button, it will attempt to submit the form and appends a ?var=x to the URL.
My two inputs:
<input type="text" name="users" onkeydown="if (event.keyCode == 13) document.getElementById('submitbtn').click()">
<input type="button" name="submitbtn" onclick="showUser(users.value)">
You may view my source for the rest. If you put in 1 or 2 and click the button, you will get results, but if you hit enter, it will not give you results and changes the URL as I said.
http://crystalarcade.com/shoutbox
you are using document.getElementById so give your button an id
like this
<input type="text" name="users" onkeydown="if (event.keyCode == 13) document.getElementById('submitbtn').click()">
<input type="button" id="submitbtn" name="submitbtn" onclick="showUser(users.value)">
and this will work for you
I am assuming you will have a form with just two input elements. With jQuery you can do something like this:
Some thing like this should get you started with, I need make a note however that this code is untested because I cannot do cross-site request using AJAX.
<script type="text/javascript">
$(function(){
$("#username").on("keypress", function(e){
if(e.keyCode==13){ //keyCode value of 13 is for the enter key
$.get("getusers.php" $("#userSearchForm").serialize(), function(data){
if(data){
$("shoutboxtxt").text(data);
}
}, "text");
}
}
});​
</script>
<form id="userSearchForm">
<input type="text" name="users" id="username" />
<input type="button" name="submitbtn" id="submitbtn" value="Search" />
</form>
<div id="shoutboxtxt"><b>Person info will be listed here.</b></div>​
Online here: http://jsfiddle.net/HwcN3/1/

jQuery Forum Submission By Hitting Enter

I have an unusual problem with a form (here's a slimmed down version):
<script>
(function($){
$("form").submit(function(){
alert('Checkout time!');
});
$("button[name='process_order']").click(function(){
alert('Button Checkout time!');
});
$("button[name='back']").click(function(){
alert('Back Button');
});
})(jQuery);
</script>
<form>
<input type="text" name="moo1" tabindex="1" />
<input type="text" name="moo2" tabindex="2" />
<button name="back" tabindex="4">Back</button>
<button name="process_order" tabindex="3">Process Order</button>
</form>
The buttons work fine, however, if I hit enter when one of the textboxes that has focus, the 'Back Button' action is what fires... even though the form's submit handler is set to do "checkout"...
You could probably change the process_order tothis:
<input type="submit" name="process_order" value="Process Order" tabindex="3" />
And change to:
<form id="myForm">
Then, bind the .submit() handler to it
$('#myForm').submit(function()
{
alert('Button checkout time!');
return false; //we return false so that it doesn't refresh the page
});
Your form has two submit buttons, the form will submit with the enter key by activating the first submit button. change
<button name="back" tabindex="4">Back</button>
to
<button type="button" name="back" tabindex="4">Back</button>
to avoid the browser interpreting the first button as a submit button

Can I determine which Submit button was used in javascript?

I have a very simple form with a name field and two submit buttons: 'change' and 'delete'. I need to do some form validation in javascript when the form is submitted so I need to know which button was clicked. If the user hits the enter key, the 'change' value is the one that makes it to the server. So really, I just need to know if the 'delete' button was clicked or not.
Can I determine which button was clicked? Or do I need to change the 'delete' button from a submit to a regular button and catch its onclick event to submit the form?
The form looks like this:
<form action="update.php" method="post" onsubmit="return checkForm(this);">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input type="submit" name="submit" value="Change" />
<input type="submit" name="submit" value="Delete" />
</form>
In the checkForm() function, form["submit"] is a node list, not a single element I can grab the value of.
Here's an unobtrusive approach using jQuery...
$(function ()
{
// for each form on the page...
$("form").each(function ()
{
var that = $(this); // define context and reference
/* for each of the submit-inputs - in each of the forms on
the page - assign click and keypress event */
$("input:submit", that).bind("click keypress", function ()
{
// store the id of the submit-input on it's enclosing form
that.data("callerid", this.id);
});
});
// assign submit-event to all forms on the page
$("form").submit(function ()
{
/* retrieve the id of the input that was clicked, stored on
it's enclosing form */
var callerId = $(this).data("callerid");
// determine appropriate action(s)
if (callerId == "delete") // do stuff...
if (callerId == "change") // do stuff...
/* note: you can return false to prevent the default behavior
of the form--that is; stop the page from submitting */
});
});
Note: this code is using the id-property to reference elements, so you have to update your markup. If you want me to update the code in my answer to make use of the name-attribute to determine appropriate actions, let me know.
You could also use the onclick event in a number of different ways to address the problem.
For instance:
<input type="submit" name="submit" value="Delete"
onclick="return TryingToDelete();" />
In the TryingToDelete() function in JavaScript, do what you want, then return false if do not want the delete to proceed.
Some browsers (at least Firefox, Opera and IE) support this:
<script type="text/javascript">
function checkForm(form, event) {
// Firefox || Opera || IE || unsupported
var target = event.explicitOriginalTarget || event.relatedTarget ||
document.activeElement || {};
alert(target.type + ' ' + target.value);
return false;
}
</script>
<form action="update.php" method="post" onsubmit="return checkForm(this, event);">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input type="submit" name="submit" value="Change" />
<input type="submit" name="submit" value="Delete" />
</form>
For an inherently cross-browser solution, you'll have to add onclick handlers to the buttons themselves.
<html>
<script type="text/javascript">
var submit;
function checkForm(form)
{
alert(submit.value);
return false;
}
function Clicked(button)
{
submit= button ;
}
</script>
<body>
<form method="post" onsubmit="return checkForm(this);">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input onclick="Clicked(this);" type="submit" name="submit" value="Change" />
<input onclick="Clicked(this);" type="submit" name="submit" value="Delete" />
</form>
</body>
</html>
You could use the SubmitEvent.submitter property.
form.addEventListener('submit', event => console.log(event.submitter))
Give each of the buttons a unique ID such as
<input type="submit" id="submitButton" name="submit" value="Change" />
<input type="submit" id="deleteButton" name="submit" value="Delete" />
I'm not sure how to do this in raw javascript but in jquery you can then do
$('#submitButton').click(function() {
//do something
});
$('#deleteButton').click(function() {
//do something
});
This says that if submitButton is clicked, do whatever is inside it.
if deleteButton is clicked, do whatever is inside it
In jQuery you can use $.data() to keep data in scope - no need for global variables in that case.
First you click submit button, then (depending on it's action) you assign data to form. I'm not preventing default action in click event, so form is submitted right after click event ends.
HTML:
<form action="update.php" method="post"">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input type="submit" name="submit" value="Change" />
<input type="submit" name="submit" value="Delete" />
</form>
JavaScript:
(function ($) {
"use strict";
$(document).ready(function () {
// click on submit button with action "Change"
$('input[value="Change"]').on("click", function () {
var $form = $(this).parents('form');
$form.data("action", "Change");
});
// click on submit button with action "Delete"
$('input[value="Delete"]').on("click", function () {
var $form = $(this).parents('form');
$form.data("action", "Delete");
});
// on form submit
$('form').on("submit", function () {
var $self = $(this);
// retrieve action type from form
// If there is none assigned, go for the default one
var action = $self.data("action") || "deafult";
// remove data so next time you won't trigger wrong action
$self.removeData("action");
// do sth depending on action type
if (action === "change") {
}
});
});
})(jQuery);
Right now you've got the same problem as you would a normal text input. You've got the same name on two different elements. Change the names to "Change" and "Delete" and then determine if either one of them were clicked by applying an event handler on both submits and providing different methods. I'm assuming you're using pure JavaScript, but if you want it to be quick, take a look at jQuery.
What you need is as simple as following what's on w3schools
Since you didn't mention using any framework, this is the cleanest way to do it with straight Javascript. With this code what you're doing is passing the button object itself into the go() function. You then have access to all of the button's properties. You don't have to do anything with setTimeout(0) or any other wacky functions.
<script type="text/javascript">
function go(button) {
if (button.id = 'submit1')
//do something
else if (button.id = 'submit2')
//do something else
}
</script>
<form action="update.php" method="post">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input id="submit1" type="submit" name="submit" value="Change" onclick="go(this);"/>
<input id="submit2" type="submit" name="submit" value="Delete" onclick="go(this);"/>
</form>
A click event anywhere in a form will be caught by a form's click handler (as long as the element clicked on allows it to propagate). It will be processed before the form's submit event.
Therefore, one can test whether the click target was an input (or button) tag of the submit type, and save the value of it (say, to a data-button attribute on the form) for processing in the form's submit handler.
The submit buttons themselves do not then need any event handlers.
I needed to do this to change a form's action and target attributes, depending upon which submit button is clicked.
// TO CAPTURE THE BUTTON CLICKED
function get_button(){
var oElement=event.target;
var oForm=oElement.form;
// IF SUBMIT INPUT BUTTON (CHANGE 'INPUT' TO 'BUTTON' IF USING THAT TAG)
if((oElement.tagName=='INPUT')&&(oElement.type=='submit')){
// SAVE THE ACTION
oForm.setAttribute('data-button',oElement.value);
}
}
// TO DO THE SUBMIT PROCESSING
function submit_form(){
var oForm=event.target;
// RETRIEVE THE BUTTON CLICKED, IF ONE WAS USED
var sAction='';
if(oForm.hasAttribute('data-button')){
// SAVE THE BUTTON, THEN DELETE THE ATTRIBUTE (SO NOT USED ON ANOTHER SUBMIT)
sAction=oForm.getAttribute('data-button');
oForm.removeAttribute('data-button');
}
// PROCESS BY THE BUTTON USED
switch(sAction){
case'Change':
// WHATEVER
alert('Change');
break;
case'Delete':
// WHATEVER
alert('Delete');
break;
default:
// WHATEVER FOR ENTER PRESSED
alert('submit: By other means');
break;
}
}
<form action="update.php" method="post" onsubmit="submit_form();" onclick="get_button();">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input type="submit" name="submit" value="Change" />
<input type="submit" name="submit" value="Delete" />
</form>
<p id="result"></p>
Here is my solution:
Just add dataset in submit button like this:
<form action="update.php" method="post" onsubmit="return checkForm(this);">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input type="submit" name="submit" value="Change" data-clicked="change" />
<input type="submit" name="submit" value="Delete" data-clicked="delete" />
</form>
In JS access it by:
$('body').on("submit", function(event){
var target = event.explicitOriginalTarget || event.relatedTarget || document.activeElement || {};
var buttonClicked = target.dataset['clicked'];
console.log(buttonClicked);
});
Name the delete button something else. Perhaps name one SubmitChange and name the other SubmitDelete.
I've been dealing with this problem myself. There's no built-in way to tell which button's submitting a form, but it's a feature which might show up in the future.
The workaround I use in production is to store the button somewhere for one event loop on click. The JavaScript could look something like this:
function grabSubmitter(input){
input.form.submitter = input;
setTimeout(function(){
input.form.submitter = null;
}, 0);
}
... and you'd set an onclick on each button:
<input type="submit" name="name" value="value" onclick="grabSubmitter(this)">
click fires before submit, so in your submit event, if there's a submitter on your form, a button was clicked.
I'm using jQuery, so I use $.fn.data() instead of expando to store the submitter. I have a tiny plugin to handle temporarily setting data on an element that looks like this:
$.fn.briefData = function(key, value){
var $el = this;
$el.data(key, value);
setTimeout(function(){
$el.removeData(key);
}, 0);
};
and I attach it to buttons like this:
$(':button, :submit').live('click', function () {
var $form = $(this.form);
if ($form.length) {
$form.briefData('submitter', this);
}
});

Categories