Javascript:Block form submit on Enter Key press - javascript

I have a web page where i have 2 forms when i click the enter key, I am calling a javascript function to force the page to load another page.My code is
function SearchUser()
{
var text = document.getElementById("searchItem").value;
text = text == "" ? -1 : text;
var by = document.getElementById("listBy").value;
var on="";
if(by==1)
{
on="USERNAME";
}
else if(by==2)
{
on="FIRSTNAME";
}
else if(by==3)
{
on="EMAIL_ID";
}
gotoUrl="userlist.php?searchItem="+text+"&onSearch="+on;
alert(gotoUrl);
window.navigate=gotoUrl;
}
and
$(document).ready(function()
{
$("#frmUserListSearch").keyup(function(event)
{
if(event.keyCode == 13)
{
SearchUser();
}
});
});
But the page is doing a form submit when the SearchUSer function being called.I am getting the correct url in the alert.But The page is not loading in the brower
Any Ideas ???
Thanks in advance

if (document.addEventListener) {
document.getElementById('strip').addEventListener('keypress',HandleKeyPress,false);
} else {
document.getElementById('strip').onkeypress = HandleKeyPress;
}
function HandleKeyPress(e) {
switch (e.keyCode) {
case e.DOM_VK_ENTER:
if (e.preventDefault)
e.preventDefault();
else e.returnValue = false;
}
}
EDIT due to original Question edit:
all you need is:
$(document).ready(function()
{
$("#frmUserListSearch").keyup(function(event)
{
if(event.keyCode == 13)
{
SearchUser();
if (e.preventDefault)
e.preventDefault();
else e.returnValue = false;
}
});
});
edited to reflect comment

Returning false often does the trick.
http://javascript.about.com/library/bldisdef.htm

I have two recommendations. First, use the keydown event instead of keyup (it catches "enter" before submit better). Second, in your SearchUser() function, use window.location instead of window.navigate to go to the other page.
$(document).ready(function() {
$("#frmUserListSearch").keydown(function(event) {
if(event.keyCode == 13){
SearchUser();
return false;
}
});
});
NOTE: Don't forget to remove the "alert()" inside the SearchUser() function as it causes the form to submit before navigating away from the page.

You can do this by using the action attribute of the form, without having to deal with key events, granted that you will later need javascript to take action on the control that submits the form.
<html>
<head>
<script type="text/javascript">
function donothing() {}
</script>
<body>
<form action='javascript:donothing()'>
...
</form>
</body>
</html>

Related

event.prevendefault() not working inside a function that has an each() function

I have function that will do a simple validation, if every input text is empyt an alert will pop up, and the program will stop. Function will fire up after a click of a button. I'm allready passing the event, but somehow the event.PreventDefault() not working, so still accessing the server side code.
Below is the function to do simple validation.
var checkRequired = function(event)
$('.box-load .requir').each(function(index,item) {
var index = $(item).data('index');
if(index === 'text') {
if ($(item).val() == "") {
$(this).focus();
alert('Please input the required parameter');
event.preventDefault();
}
}
});
}
For the trigger the function I use this code:
$(document).on('click','.box-load .btn-save', function(event) {
event.preventDefault();
checkRequired(event);
Bellow the checkRequired(), I'm gonna do an ajax request. What i want is, if one of the input text is empty, the event is stop. But with that code, is not working. Any suggestion?
Thanks in advance.
if you call event.preventDefault(), default action of the event will not be triggered.
$(document).on('click','.box-load .btn-save', function(event)
{
checkRequired(event);
event.preventDefault();
event.preventDefault() should be outside the for loop.
var checkRequired = function(event)
{
$('.box-load .requir').each(function(index,item) {
var index = $(item).data('index');
if(index === 'text') {
if ($(item).val() == "") {
$(this).focus();
alert('Please input the required parameter');
}
}
});
event.preventDefault();
}
event.preventDefault() will just stop the default action, not stop your function call. If you don't specifically return from your function, it will go on and launch the ajax.

Run function on enter press

I have a jQuery button function that works properly and executes the code inside, what I want is when I press the Enter on the search box, it will execute the same function inside the onclick one. I don't want to copy paste the entire code of my function to the on Enter press event because that will be the wrong way to do it. This is the click event:
$("#checkScout").click(function(e){
...
}
And this is the one I tried with the on enter press
var enterKey = document.getElementById("addChannelsToScout");
enterKey.addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
$("#checkScout").click(function (e);
}
});
it should be just
$("#checkScout").click();
so
$('#addChannelsToScout').keydown(function (e) {
if (e.which == 13) {
$("#checkScout").click();
//$("#checkScout").trigger('click');
}
})
Demo: Fiddle
Try:
$("#checkScout").trigger('click');
Trigger Performance
Change:
$("#checkScout").click(function(e);
To:
$("#checkScout").click();
Your code:
var enterKey = document.getElementById("addChannelsToScout");
enterKey.addEventListener("keydown", function (e) {
if (e.keyCode === 13)
{
$("#checkScout").click();//modified here
}
});
just this will work $("#checkScout").click();
var enterKey = document.getElementById("addChannelsToScout");
enterKey.addEventListener("keydown", function (e) {
if (e.keyCode === 13)
{
$("#checkScout").click();
}
});
actually you need to trigger the event. since it is already been handled it will perform the task that you have written in the event
Check Triggers here http://api.jquery.com/trigger/
$("#checkScout").trigger("click");

Javascript - how to correctly verify form data?

I have a form with a few text inputs and also with one file-type input, in which I attempt to verify, if the selected file is PDF. I am doing that this way:
$("#myform").bind("submit", function() {
var ext = $('#file_input').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['pdf']) == -1) {
alert('ERROR!');
}
});
But in the part of code above is one lack - if all inputs except the file-input (lets sat the file is DOC) are valid (=> file-input is not valid) and I click on the SUBMIT button, then is displayed alert message ERROR!, but the form is sent.
How can I "stop" sending the form, if the file type is not valid?
Try this:
$("#myform").bind("submit", function(e) {
var ext = $('#file_input').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['pdf']) == -1) {
e.preventDefault(); //Prevents the default action which is form submit
alert('ERROR!');
}
});
You can shorten the code by doing this:
if (!(/\.pdf$/i).test($('#file_input').val())) {
// not valid, do what you like here
// return false to prevent submit
return false;
The form is prevented from submitting by returning false; preventDefault on the form submit event is not working in IE 7/8, return false does the job.
In a jQuery callback function bound to an event you have two options.
You can pass a reference to the event to the anonymous function and call e.preventDefault():
$('#myform').bind('submit', function(e) {
e.preventDefault();
// Your code
});
e.preventDefault() prevents the default functionality (in this case, submitting the form).
Or you can return false to both prevent the default functionality and prevent the event from bubbling; the same as calling e.preventDefault(); e.stopPropagation().
You have 2 ways:
Keep your code as it is and add return false:
$("#myform").bind("submit", function() {
var ext = $('#file_input').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['pdf']) == -1) {
alert('ERROR!');
return false;
}
});
change the function signature to accept the event and use the preventDefault():
$("#myform").bind("submit", function(e) {
var ext = $('#file_input').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['pdf']) == -1) {
alert('ERROR!');
e.preventDefault();
}
});

How make input not rebind the page?

I have a input on page in some div:
<input style='border:1px solid black;' type='text' id='inputFindBy_Name' />
and o jquery javascript function monitored it:
$("div[id=mainGridPage] input").bind("keyup", function (event) {
if (event.keyCode == 13) {
var searchField = "Name";
var searchValue = $(this)[0].value;
var pageIndex = "1";
var sortField = "Name";
Application.Services.ProductTypeService.LoadMainGridProductType(pageIndex, sort, sortField, searchField, searchValue, ResultLoadMainGridProductType, ErrorLoadMainGridProductType);
}
});
when user typed something and pressed ENTER (event.keyCode == 13) I need do some thing but without reloading the page. How do that?
Try this one
$("div[id=mainGridPage] input").bind("keyup", function (event) {
if (event.keyCode == 13) {
// needed do something here without reloading the page
return false;
}
});
just like a link.
Just return false from within the function:
var code = event.keyCode || event.which;
if (code == 13) {
// do what you have to do.....
return false;
}
Edit: the keyup event is triggered "too late" after the form submission event was already dispatched - you can't cancel or stop it in that stage. So, handle the keypress event instead. Change the line to:
$("div[id=mainGridPage] input").bind("keypress", function (event) {
And the return false; will indeed stop the form from submitting.
Live test case.
You need to do a event.stopPropagation() and maybe the return false;. Please use event.which because event.keyCode is not compatible with all browsers, also you are using div[id=mainGridPage] input which searches for an ID, a better way to put this down is: div#mainGridPage input, and probably faster.
$("div#mainGridPage input").bind("keyup", function (event) {
if (event.which == 13) {
event.stopPropagation();
// needed do something here without reloading the page
return false.
}
});
try this. this will work i think:
$("div[id=mainGridPage] input").keypress(function(event) {
if (event.keyCode == 13) {
// do your code
console.log('hello');
return false;
}
});

How to prevent ENTER key to change line in web form

I want to submit the form by press the ENTER key.
But it also change the line in content.
How to prevent this?
This is my code, but when hit ENTER, the ... run and Cursor moved to the next line:
function postmessage(e) {
if(e) {
e.preventDefault = null || e.preventDefault;
if(e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
....
return false;
}
function submitmessage(e) {
if(e.keyCode == 13) {
postmessage(e);
}
return false;
}
function bindEvent(el, eventName, eventHandler) {
if (el.addEventListener){
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent){
el.attachEvent('on'+eventName, eventHandler);
}
}
bindEvent(text, 'keydown', submitmessage);
Generally it is a bad idea to screw around with default behavior of the browser. Personally I would hate it if I was typing in some text, hit enter and bam, without a proper review of my data it get's submitted?!
If you don't want people to enter multiple lines in a textarea, why not make it a regular textbox (<input type="text" />)?
While I completely agree with #Peter in that this will create a very awkward and annoying user experience, here's how to achieve it code-wise: Capture the event on a keydown, and bypass the newline with event.preventDefault(). Then manually submit your form.
Something like this:
var el = document.getElementById('#my_textarea');
if (el.addEventListener)
{
el.addEventListener('keydown', checkEnter(event), false);
}
else if (el.attachEvent){
el.attachEvent('keywodn', checkEnter(event));
}
function checkEnter(event)
{
var charCode = (event.which) ? event.which : event.keyCode
// Enter key
if(charCode == 13) {
event.preventDefault();
document.myform.submit();
return false;
}
}
MDN Docs:
https://developer.mozilla.org/en/DOM/event.preventDefault
https://developer.mozilla.org/en/DOM/element.addEventListener
e.stopPropagation(); stopped the default action.

Categories

Resources