Stop reloading page with 'Enter Key' - javascript

I have a search box at the top of page that makes an ajax call when a user hits the adjacent button. I am trying to update the input tag so that when a user hit the 'enter' key, the apropriate JavaScript takes place without reloading the page. The problem is that the page keeps reloading. Here is my latest attempt:
$("searchText").bind('keyup', function(event){
if(event.keyCode == 13){
event.preventDefault();
$("#buttonSrch").click();
return false;
}
});
<input type='search' id='searchText' />
<input type='button' id='buttonSrch' onclick="search(document.getElementById('searchText'))" value='Search' />

Don't bind to the inputs; bind to the form. Assuming the form has an ID of searchForm:
$("#searchForm").submit(function() {
search($("#searchText").get(0));
return false;
});
Try it out.
It can also be done with plain JavaScript:
document.getElementById('searchForm').addEventListener('submit', function(e) {
search(document.getElementById('searchText'));
e.preventDefault();
}, false);

I know its a little late but I ran into the same problem as you. It worked for me using "keypress" instead of bind.
$('#searchText').keypress(function (e) {
if (e.which == 13) {
e.preventDefault();
//do something
}
});

You are missing # in the selector. Try this
<input type='text' id='searchText' />
JS
$("#searchText").bind('keyup', function(event){
if(event.keyCode == 13){
event.preventDefault();
//$("#buttonSrch").click();
search(this.value);
}
});

Add onSubmit="return false;" on your form tag
<form onSubmit="return false;">
/* form elements here */
</form>`

$('#seachForm').submit(function(e){
e.preventDefault();
//do something
});

You could set the form action attribute to javascript:void(0); that way the form doesn't post/get so the page wont refresh.
$(document).ready(function () {
$('#form1').attr('action', 'javascript:void(0);');
});

Just use the "action" attribute in <form> tag.
Like this
<form action="#"> // your content </form>

$("searchText").keypress(function(event){
if(event.keyCode == 13){
$("#buttonSrch").click();
return false;
}
});

Does your JS execute immediately or on document ready? If it's not in a document ready the button won't exist at the time you're trying to call bind.

This is what ended up working for me. Please note that my struggle was to find the object that triggered the form submit:
$('#missingStaff').submit(function (e) {
e.preventDefault();
var comment = $(document.activeElement)[0];
submitComments(comment);
});

You just need to add this:
<form #submit.prevent="search">
whatever function is triggered for search. When I press that search button search() func is triggered. That is why: #submit.prevent="search"
async search() {
let yuyu = document.getElementById('search').value
console.log('lsd', yuyu)
try {
let newRecipes = await this.$axios.$get(
`/api/videosset/?user=&id=&title=${yuyu}&price=&category=`
)
this.$store.commit('CHANGE_NAV_LAYOUT', newRecipes)
} catch (e) {
console.log(e)
}
},

Related

jQuery keyboard event fires on wrong input fields

I'm creating simple forms without direct submitting, than running script before. So classic hitting enter will not send the form. However, since users are often hitting enter button to send a form, I create simple extension for hitting enter that is calling script when button is clicked.
For example, I have a simple form:
<form id="testForm">
<input type="email" id="email" />
<input type="password" id="pass" />
<button id="btnLogin" type="button">Login</button>
</form>
And extension I created is looking like this:
(function($){
$.fn.noEnter=function(options){
let settings=$.extend({btn:""},options);
function _init(){
$(this).on("keypress",function(event){
if(event.keyCode === 13) {
event.preventDefault();
$("#"+settings.btn).click();
return false;
}
});
}
this.each(function(){_init();});
return{}
};
}(jQuery));
Then in script I call something like this:
$("#email").noEnter({btn:"btnLogin"});
$("#pass").noEnter({btn:"btnLogin"});
$("#btnLogin").click(function(){
.....
});
And this is working. Problem is that it is working twice, for each input field. Looks like other input field is accepting keypress (or keydown) event. Or am I missing something?
The problem is this is referring window object in _init function to avoid that try below code
(function($){
$.fn.noEnter=function(options){
let settings=$.extend({btn:""},options);
var self = this;
function _init(){
$(self).on("keypress",function(event){
if(event.keyCode === 13) {
event.preventDefault();
$("#"+settings.btn).click();
return false;
}
});
}
this.each(function(){_init();});
return{}
};
}(jQuery));
$("#email").noEnter({btn:"btnLogin"});
$("#pass").noEnter({btn:"btnLogin"});
$("#btnLogin").click(function(e){
console.log('righty');
});
There is working example is jsfiddle if you want to try
use event.stopPropagation(); to prevent executing further.
$(this).on("keypress",function(event){
if(event.keyCode === 13) {
event.stopPropagation();
event.preventDefault();
$("#"+settings.btn).click();
return false;
}
});

Javascript Block Form action on "enter" submit

i'm working in laravel framework, and i have this form:
VIEW
{!! Form::open() !!}
<input type="text" name="puntata" id="puntata">
<button id="registro" type="button" class="btn-primary">PUNTA</button>
{!! Form::close()!!}
JS
var button = d.getElementById('registro');
function puntata() {
....my code...
}
var submit = button.onclick = puntata;
When i insert a value in my input "puntata" and do click on button "registro" it call my function js, it work well.
But If i insert a value in my input "puntata" and i do "ENTER" in my keyboard it submit the form without call my function javascript. How can i block this?
i would like that on event "ENTER" call my function puntata() and NOT submit the form.
Thank you for your help!
You should use jQuery's keydown to do this:
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) { // -- 13 for enter key
event.preventDefault();
return false;
}
});
});
Hope this helps!
using jquery:
$(document).keypress(function(e) {
if(e.which == 13) {
$('#registro').click();
}
});
Just add the event handler to the form submission and not the button being clicked.
$('form').on('submit', function(e) {
// whatever you were doing on button click
});

How to disable submit button? [duplicate]

I wrote this code to disable submit buttons on my website after the click:
$('input[type=submit]').click(function(){
$(this).attr('disabled', 'disabled');
});
Unfortunately, it doesn't send the form. How can I fix this?
EDIT
I'd like to bind the submit, not the form :)
Do it onSubmit():
$('form#id').submit(function(){
$(this).find(':input[type=submit]').prop('disabled', true);
});
What is happening is you're disabling the button altogether before it actually triggers the submit event.
You should probably also think about naming your elements with IDs or CLASSes, so you don't select all inputs of submit type on the page.
Demonstration: http://jsfiddle.net/userdude/2hgnZ/
(Note, I use preventDefault() and return false so the form doesn't actual submit in the example; leave this off in your use.)
Specifically if someone is facing problem in Chrome:
What you need to do to fix this is to use the onSubmit tag in the <form> element to set the submit button disabled. This will allow Chrome to disable the button immediately after it is pressed and the form submission will still go ahead...
<form name ="myform" method="POST" action="dosomething.php" onSubmit="document.getElementById('submit').disabled=true;">
<input type="submit" name="submit" value="Submit" id="submit">
</form>
Disabled controls do not submit their values which does not help in knowing if the user clicked save or delete.
So I store the button value in a hidden which does get submitted. The name of the hidden is the same as the button name. I call all my buttons by the name of button.
E.g. <button type="submit" name="button" value="save">Save</button>
Based on this I found here. Just store the clicked button in a variable.
$(document).ready(function(){
var submitButton$;
$(document).on('click', ":submit", function (e)
{
// you may choose to remove disabled from all buttons first here.
submitButton$ = $(this);
});
$(document).on('submit', "form", function(e)
{
var form$ = $(this);
var hiddenButton$ = $('#button', form$);
if (IsNull(hiddenButton$))
{
// add the hidden to the form as needed
hiddenButton$ = $('<input>')
.attr({ type: 'hidden', id: 'button', name: 'button' })
.appendTo(form$);
}
hiddenButton$.attr('value', submitButton$.attr('value'));
submitButton$.attr("disabled", "disabled");
}
});
Here is my IsNull function. Use or substitue your own version for IsNull or undefined etc.
function IsNull(obj)
{
var is;
if (obj instanceof jQuery)
is = obj.length <= 0;
else
is = obj === null || typeof obj === 'undefined' || obj == "";
return is;
}
Simple and effective solution is
<form ... onsubmit="myButton.disabled = true; return true;">
...
<input type="submit" name="myButton" value="Submit">
</form>
Source: here
This should take care of it in your app.
$(":submit").closest("form").submit(function(){
$(':submit').attr('disabled', 'disabled');
});
A more simplier way.
I've tried this and it worked fine for me:
$(':input[type=submit]').prop('disabled', true);
Want to submit value of button as well and prevent double form submit?
If you are using button of type submit and want to submit value of button as well, which will not happen if the button is disabled, you can set a form data attribute and test afterwards.
// Add class disableonsubmit to your form
$(document).ready(function () {
$('form.disableonsubmit').submit(function(e) {
if ($(this).data('submitted') === true) {
// Form is already submitted
console.log('Form is already submitted, waiting response.');
// Stop form from submitting again
e.preventDefault();
} else {
// Set the data-submitted attribute to true for record
$(this).data('submitted', true);
}
});
});
Your code actually works on FF, it doesn't work on Chrome.
This works on FF and Chrome.
$(document).ready(function() {
// Solution for disabling the submit temporarily for all the submit buttons.
// Avoids double form submit.
// Doing it directly on the submit click made the form not to submit in Chrome.
// This works in FF and Chrome.
$('form').on('submit', function(e){
//console.log('submit2', e, $(this).find('[clicked=true]'));
var submit = $(this).find('[clicked=true]')[0];
if (!submit.hasAttribute('disabled'))
{
submit.setAttribute('disabled', true);
setTimeout(function(){
submit.removeAttribute('disabled');
}, 1000);
}
submit.removeAttribute('clicked');
e.preventDefault();
});
$('[type=submit]').on('click touchstart', function(){
this.setAttribute('clicked', true);
});
});
</script>
How to disable submit button
just call a function on onclick event and... return true to submit and false to disable submit.
OR
call a function on window.onload like :
window.onload = init();
and in init() do something like this :
var theForm = document.getElementById(‘theForm’);
theForm.onsubmit = // what ever you want to do
The following worked for me:
var form_enabled = true;
$().ready(function(){
// allow the user to submit the form only once each time the page loads
$('#form_id').on('submit', function(){
if (form_enabled) {
form_enabled = false;
return true;
}
return false;
});
});
This cancels the submit event if the user tries to submit the form multiple times (by clicking a submit button, pressing Enter, etc.)
I have been using blockUI to avoid browser incompatibilies on disabled or hidden buttons.
http://malsup.com/jquery/block/#element
Then my buttons have a class autobutton:
$(".autobutton").click(
function(event) {
var nv = $(this).html();
var nv2 = '<span class="fa fa-circle-o-notch fa-spin" aria-hidden="true"></span> ' + nv;
$(this).html(nv2);
var form = $(this).parents('form:first');
$(this).block({ message: null });
form.submit();
});
Then a form is like that:
<form>
....
<button class="autobutton">Submit</button>
</form>
Button Code
<button id="submit" name="submit" type="submit" value="Submit">Submit</button>
Disable Button
if(When You Disable the button this Case){
$(':input[type="submit"]').prop('disabled', true);
}else{
$(':input[type="submit"]').prop('disabled', false);
}
Note: You Case may Be Multiple this time more condition may need
Easy Method:
Javascript & HTML:
$('form#id').submit(function(e){
$(this).children('input[type=submit]').attr('disabled', 'disabled');
// this is just for demonstration
e.preventDefault();
return false;
});
<!-- begin snippet: js hide: false console: true babel: false -->
<form id="id">
<input type="submit"/>
</form>
Note: works perfectly on chrome and edge.
The simplest pure javascript solution is to simply disable the button:
<form id="blah" action="foo.php" method="post" onSubmit="return checkForm();">
<button id="blahButton">Submit</button>
</form>
document.getElementById('blahButton').disabled = true ;
It works with/without onSubmit. Form stays visible, but nothing can be sumbitted.
In my case i had to put a little delay so that form submits correctly and then disable the button
$(document).on('submit','#for',function()
{
var $this = $(this);
setTimeout(function (){
$this.find(':input[type=submit]').attr('disabled', 'disabled')
},1);
});

jQuery button takes value from input and do an action - how does it works?

I've got a small piece of code here
<label for="pass">Password</label>
<input type="text" id="pass" value="QWERTY">
<button for="pass">Submit!</button>
and jquery action
$("button").click(function(){
var value=$("input[id=pass]").attr("value");
if (value==="QWERTY"){
alert("Good!");
};
and it doesnt work. Do you know how to fix it?
Try this.
$("button").click(function(){
var value=$("input#pass").val();
if ( value === "QWERTY"){
alert("Good!");
}
});
jQuery has it's own built in function for fetching values from input fields.
You should prevent the default action from triggering when the button is clicked (otherwise the form will be submitted, and the JS will not execute). You should also use val() when accessing an input's value.
You should also wrap your code inside the DOMReady handler, to ensure that the DOM is accessible when your script is run.
Here's an updated version of your code:
$(function() {
$("button").click(function(e) {
e.preventDefault();
var the_value = $("#pass").val();
if(value == "QWERTY")
{
alert("Good!");
}
};
});
Try this : It's more optimized...
$("button").click(function(e){
e.preventDefault();
var value=$("#pass")[0].value;
if (value==="QWERTY"){
alert("Good!");
};
You can also remove the "for" attribute on the button, it's non correct ;)
Your code should work if you don't forget the }); at last and have put the code into dom ready callback function. The demo.
And you could write it like below:
$("button").click(function(){
if ($('#pass').val()==="QWERTY"){
alert("Good!");
};
});
I think you just have a syntax error. You need to make sure you close your function curly brace and your click close paren.
$("document").ready(function () {
$("button").click(function () {
var value = $("input[id=pass]").attr("value");
if (value === "QWERTY") {
alert("Good!");
}
});
});
Example:
http://jsfiddle.net/pandaPowder/5VjeD/3/

properly disabling the submit button

this is the code that I use to disable the button
$("#btnSubmit").attr('disabled', 'disabled')
$("#btnSubmit").disabled = true;
and this is my submit button
<input id="btnSubmit" class="grayButtonBlueText" type="submit" value="Submit" />
the button although looks disabled, you can still click on it.. This is tested with FF 3.0 and IE6
Am I doing something wrong here?
If it's a real form, ie not javascript event handled, this should work.
If you're handling the button with an onClick event, you'll find it probably still triggers. If you are doing that, you'll do better just to set a variable in your JS like buttonDisabled and check that var when you handle the onClick event.
Otherwise try
$(yourButton).attr("disabled", "true");
And if after all of that, you're still getting nowhere, you can manually "break" the button using jquery (this is getting serious now):
$(submitButton).click(function(ev) {
ev.stopPropagation();
ev.preventDefault();
});
That should stop the button acting like a button.
Depending on how the form submission is handled you might also need to remove any click handlers and/or add one that aborts the submission.
$('#btnSubmit').unbind('click').click( function() { return false; } );
You'd have to add the click handler's again when (if) you re-enable the button.
You need to process Back/Prev button into browser.
Example bellow
1) Create form.js:
(function($) {
$.enhanceFormsBehaviour = function() {
$('form').enhanceBehaviour();
}
$.fn.enhanceBehaviour = function() {
return this.each(function() {
var submits = $(this).find(':submit');
submits.click(function() {
var hidden = document.createElement('input');
hidden.type = 'hidden';
hidden.name = this.name;
hidden.value = this.value;
this.parentNode.insertBefore(hidden, this)
});
$(this).submit(function() {
submits.attr("disabled", "disabled");
});
$(window).unload(function() {
submits.removeAttr("disabled");
})
});
}
})(jQuery);
2) Add to your HTML:
<script type="text/javascript">
$(document).ready(function(){
$('#contact_frm ).enhanceBehaviour();
});
</script>
<form id="contact_frm" method="post" action="/contact">
<input type="submit" value="Send" name="doSend" />
</form>
Done :)

Categories

Resources