detect the submit event when click enter key - javascript

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.

Related

How to validate HTML elements when submitting through JQuery?

I have an HTML form as shown below with some form fields and a submit and a delete button:
There is also a floating component which appears whenever there are changes in the form as shown in the same diagram with text: You have unsaved changes. This is a common component which appears for all the forms in my website.
When I submit the form using the form's Submit button, it validates all the fields as per the validations.
(for example: <input type="number" min="0"> will check that the number should be positive)
But if I submit the form from the Save button on the floating element, it does not checks for any validation, and just posts the request.
I tried using the following code, but the reportValidity() function doesn't do anything.
if (!form.checkValidity()) {
form.reportValidity();
}
form.checkValidity() and form.reportValidity() both are returning false when I do a console.log.
What am I missing here, and how can I fix this?
P.S. I tried this on chrome v98.
Edit: Adding HTML code:
<form method="post" action="/products/manage/{{.Product.ID}}/submit/">
<div class="form-group col-md-5">
<label>Product Quantity</label>
<input type="number" min="0" name="ProductQuantity" value="{{if .Product}}{{.Product.Qunatity}}{{else}}10{{end}}">
</div>
<button type="submit" class="btn btn-success" value="Submit">Submit</button>
<button type="submit" class="btn btn-danger" value="Delete" formaction="/products/manage/{{.Product.ID}}/delete/">Delete</button>
</form>
Save button calls this function:
function submitForm(form, url) {
const form = $(form)[0]
if (!form.checkValidity()) { //<- Added the code here
form.reportValidity();
}
var serialized = serializeForm(form);
// Do some more things then use HTTP to request the API
}
You can easily use the jQuery event handlers do the work for you.
A simplified example below:
Give your form some identifier (example: id="form1")
Catch the click event on button click
Trigger the submit event to submit that form
$('.unsavedChangesBtn').on('click',function(){
$('#form1').submit();
});
In below example you can submit the form either by clicking the submit button or the save button.
$('document').ready(function(){
$('#form1').on('submit',function(){
alert("SUBMITTED");
});
$('.unsavedChangesBtn').on('click',function(){
$('#form1').submit();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="form1" action="javascript:void(0);">
<div class="form-group col-md-5">
<label>Product Quantity</label>
<input type="number" min="0" name="ProductQuantity" value="{{if .Product}}{{.Product.Qunatity}}{{else}}10{{end}}">
</div>
<button type="submit" class="btn btn-success" value="Submit">Submit</button>
<button type="submit" class="btn btn-danger" value="Delete" formaction="/products/manage/{{.Product.ID}}/delete/">Delete</button>
</form>
<button class="unsavedChangesBtn"> SAVE </button>

Trigger submit on pressing enter (as well if submit button is clicked)

I know this has been asked before, and I have read the replies carefully, but still cannot get it to work in my code.
This is what I would like to achieve:
there is a text input field. The user types in the field. On clicking 'submit' button, the word 'done' appears on the screen. I can do this part without difficulty. However, I also want the user to able to submit by hitting 'enter' when they are in the input field, instead of having to hit 'submit' button (although I still want the submit button to work also - basically user has two options on how to submit, by clicking submit button, or hitting enter).
I followed instructions on W3, and have the following code:
var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("submit").click();
}
});
function myFunction() {
document.getElementById("demo1").innerHTML = "done";
}
<div class = 'method'>
<form id="myFunction">
<h3>myFunction():</h3>
<input id="myInput" name="name">
<button id="submit" type="button" onclick="myFunction()">Submit</button>
<div id="demo1">function result on submit goes here</div>
</form>
</div>
What am I missing?
Thanks in advance
By using a <button type="submit"> instead of type="button", you won't need the javascript to detect a keystroke. Both hitting the submit button and pressing enter will cause the onsubmit event to fire on the form. By calling event.preventDefault(), you make sure the browser does not navigate after submitting the form.
function myFunction(event) {
event.preventDefault();
document.getElementById("demo1").innerHTML = "done";
}
<div class='method'>
<form id="myFunction" onsubmit="myFunction(event)">
<h3>myFunction():</h3>
<input id="myInput" name="name">
<button type="submit">Submit</button>
<div id="demo1">function result on submit goes here</div>
</form>
</div>
You dont need to add event listeners to your button or your input.
Instead add the event listener to your form and prevent default event, because forms can be submitted by both 'enter' key as well as submit buttons (button needs to be of type 'submit').
document.getElementById('myFunction').addEventListener('submit', myFunction)
function myFunction(e) {
e.preventDefault();
document.getElementById("demo1").innerHTML = "done";
}
<div class='method'>
<form id="myFunction">
<h3>myFunction():</h3>
<input id="myInput" name="name">
<button id="submit" type="submit">Submit</button>
<div id="demo1">function result on submit goes here</div>
</form>
</div>
You can simplify your code to listen for the submit event, which will trigger when the form is submitted by hitting enter or by clicking the submit button:
var input = document.getElementById("myInput");
var form = document.getElementById( "myFunction" );
form.addEventListener( "submit", function( e ){
e.preventDefault();
document.getElementById( "demo1" ).innerHTML = "done";
});
<div class='method'>
<form id="myFunction">
<h3>myFunction():</h3>
<input id="myInput" name="name">
<button id="submit" type="submit">Submit</button>
<div id="demo1">function result on submit goes here</div>
</form>
</div>

mvc - submit text input field when enter

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

Button first action on click and second action on click

The animated Search Box is expanding at click on the button the input. After entering any Text and a second click on the icon it should send the form with the method get.
I do not know what I am doing wrong and would be happy if I can get some help.
<form action="navi.php" method="GET">
<div class="search-wrapper">
<div class="input-holder">
<input type="text" class="search-input" placeholder="Type to search" />
<button class="search-icon" onclick="searchToggle(this, event);"><span></span></button>
</div>
</div>
</form>
The Javascript Function
function searchToggle(obj, evt){
var container = $(obj).closest('.search-wrapper');
if(!container.hasClass('active')){
container.addClass('active');
evt.preventDefault();
}
else if(container.hasClass('active')){
container.removeClass('active');
// clear input
container.find('.search-input').val('');
// clear and hide result container when we press close
container.find('.result-container').fadeOut(100, function(){$(this).empty();});
}
}
Try using it like this
function searchToggle(obj){
var container = $(obj).find('.search-wrapper');
if(!container.hasClass('active')){
container.addClass('active');
return false;
}
else if(container.hasClass('active')){
container.removeClass('active');
// clear input
container.find('.search-input').val('');
// clear and hide result container when we press close
container.find('.result-container').fadeOut(100, function(){$(this).empty();});
return true;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="navi.php" method="GET" onsubmit="return searchToggle(this);">
<div class="search-wrapper">
<div class="input-holder">
<input type="text" class="search-input" placeholder="Type to search" />
<button class="search-icon" type="submit"><span></span>SUBMIT</button>
</div>
</div>
</form>
Well, you making value of your .search-input empty and sending empty value to navi.php.
And your button must have attribute type="submit" to submit form.
If you remove container.find('.search-input').val(''); and add type="submit" it will work.
Also else if(container.hasClass('active')) is meaningless, you can use just else. And onclick is not recommended to use. If you use jQuery, you should use $.bind() or $.on() ...

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/

Categories