I am trying to capture the Enter key as follows,
$("#txt1").keypress(function(event){
if(event.which==13) //Also tried using event.keycode
$("#add").load("newjsp.jsp?q="+this.value)
})
But everytime I press enter, The text gets erased and does not show in the form(#add) it should. How can I do this?
Also I encountered a problem in the following code,
$("#txt1").keyup(function(event){
$("#add").load("newjsp.jsp?q="+this.value)
})
<form>
Comment: <input type="text" id="txt1"></input>
</form>
<p><p></p></p>
<form id="add">
</form>
When I run this code, the text in the textbox gets added to my form (#add) but as I press the spacebar key, the text is erased (from the #add form and not from the textbox) and then no more text is added. I have tried using keydown and keypress but same problem remains. I cannot understand where the problem lies since this.value gives me the complete value in the textbox! Including the spaces.
Your first example is the correct one. Except you need to prevent event bubbling after you press 'enter'. Pressing enter by default submits the form. FinalFrag is correct about the spaces
$('#txt1').keypress(function(e){
if (e.which===13) {
e.preventDefault();
e.stopImmediatePropagation();
$("#add").load("newjsp.jsp", {q: $(this).val()} );
}
});
*Editied to reflect Tomalak's comment.
this.value will indeed add the pressed key to the load request. However, your browser might trim the spaces off the requested url turning "q=hello " into "q=hello"
You should escape the value before you use it in the request.
Take a look at the javascript escape() function here: http://www.w3schools.com/jsref/jsref_escape.asp
For the second problem you should use encodeUricomponent() to encode the values so that you can use them in a url:
$("#txt1").keyup(function(event){
$("#add").load("newjsp.jsp?q="+encodeURIComponent(this.value));
})
For the first problem you should prevent the default action and stop the propagation:
$('#txt1').keypress(function(e){
e.preventDefault();
e.stopImmediatePropagation()
if (e.which===13) {
$("#add").load("newjsp.jsp?q=" + $(this).val());
}
});
Related
I am handling ajax suggestions using keyboard and mouse, it is capturing every keyevent except enter key(13). What I want is to get the "selected suggestion value" into the text box. For this I am handling keyevent = 13. Now the problem is when I am pressing enter key, my form get submitted instead of going into the "if block" where I am checking (keyevent = 13).
I am using struts <html:submit> tag to submit my form. I guess, the browser automatically set the focus into first <html:submit> tag that comes in its place. How to defocus this? I tried setting focus at other fields but trick doesn't work.
The other way is, I can use simple <html:button> and can get the things working, but the system already using <html:submit>. So, getting approval and modification is quite hectic.
Code for submit button:
<html:submit styleClass="btn" property="method.saveVisaRequestForRMG" onclick="bCancel=false" styleId="submitBtn">
and code for event handling:
// Handle ENTER key
case 13: handleSelectedItem(obj, container, cur);
ev.cancelBubble = true;
break;
How to come out of this problem? Please suggest me.
If you use jquery there is a simple way to handle enter press events:
$(window).keypress(function(e) {
if(e.keyCode == 13) {
e.preventDefault();
alert('Enter!');
}
});
After you prevented the default event you can do whatever you want for example posting the data into the server, saying hello or whatever :)
Try to return false; to cancel the event handling of the submit?
Do you have something like:
onsubmit="return formValidator()"
i have a function that currently working on .keypress event when the user right something in the textbox it do some code, but i want the same event to be triggered also when the user clear the textbox .change doesn't help since it fires after the user change the focus to something else
Thanks
The keyup event will detect if the user has cleared the box as well (i.e. backspace raises the event but backspace does not raise the keypress event in IE)
$("#inputname").keyup(function() {
if (!this.value) {
alert('The box is empty');
}
});
jsFiddle
As Josh says, this gets fired for every character code that is pressed in the input. This is mostly just showing that you need to use the keyup event to trigger backspace, rather than the keypress event you are currently using.
The solution by Jonathon Bolster does not cover all cases. I adapted it to also cover modifications by cutting and pasting:
$("#inputname").on('change keyup copy paste cut', function() {
//!this.value ...
});
see http://jsfiddle.net/gonfidentschal/XxLq2/
Unfortunately it's not possible to catch the cases where the field's value is set using javascript. If you set the value yourself it's not an issue because you know when you do it... but when you're using a library such as AngularJS that updates the view when the state changes then it can be a bit more work. Or you have to use a timer to check the value.
Also see the answer for Detecting input change in jQuery? which suggests the 'input' event understood by modern browsers. So just:
$("#inputname").on('input', function() {
//!this.value ...
});
Another way that does this in a concise manner is listening for "input" event on textarea/input-type:text fields
/**
* Listens on textarea input.
* Considers: undo, cut, paste, backspc, keyboard input, etc
*/
$("#myContainer").on("input", "textarea", function() {
if (!this.value) {
}
});
You can check the value of the input field inside the on input' function() and combine it with an if/else statement and it will work very well as in the code below :
$( "#myinputid" ).on('input', function() {
if($(this).val() != "") {
//Do action here like in this example am hiding the previous table row
$(this).closest("tr").prev("tr").hide(); //hides previous row
}else{
$(this).closest("tr").prev("tr").show(); //shows previous row
}
});
Inside your .keypress or .keyup function, check to see if the value of the input is empty. For example:
$("#some-input").keyup(function(){
if($(this).val() == "") {
// input is cleared
}
});
<input type="text" id="some-input" />
I have a HTML form on my page. When i am putting some value in one of the text fields in form and press 'Enter key' the form gets submitted instantly. I think this is happening due to default focus is on submit button. But i try to remove that focus using blur() function, it is not working. I am using Chrome.
Is there any way to avoid this scenario?
All suggestions are welcome. thanks in advance.
The Submit button is not actually focused; Enter in a text field is supposed to submit the form.
You could register a handler for the submit event, and then only allow it if the Submit button was actually focused at the time submit was requested.
However, you'll be deliberately breaking the way that HTML forms work. Not everyone wants to submit the form using the One True Way of actually clicking the Submit button (also, you'll be breaking accessibility and may introduce browser-specific bugs).
No. The focus is still on the text field. Pressing enter there is supposed to submit the form (and bypasses the submit button entirely).
You can suppress the behavior using JavaScript, but since it is normal behavior for the browser, I wouldn't recommend doing so.
try this solution: replace the 'input' with 'button' and add attribute
type equals 'button' and handle the onclick event with submit javascript function
<form name='testForm'>
<input type='text' value="myName" />
<button type='button' onclick='testForm.submit()'/>
</form>
i think it works also with tag input adding the same attribute
Enjoy
Mirco
blur() is the way to go. It works like this:
<button onclick="this.blur();">some button</button>
Note that you should not use JavaScript and DOM-events using Attributes. This is just for demonstration purposes. Try to be unobstrusive.
Maybe it will help you out, the form is "supposed" to be sent with enter in the text box (HTML by design), it is no a matter of focus.
If you want to avoid it, check this out.
This is the proposed script:
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
Good luck, tell me if you need any clarification!
EDIT: I do agree with Piskvor answer, it may bring some bugs
this has nothing to do with the focus, its just the default behavior of you browser. to avoid this, you could try to cath the enter-keypress like this (Source - but there are a lot of other solutions (most working the same way, just using other events like the firms onsubmit instead of the documents onkeypress)):
function catchEnter(e){
// Catch IE’s window.event if the
// ‘e’ variable is null.
// FireFox and others populate the
// e variable automagically.
if (!e) e = window.event;
// Catch the keyCode into a variable.
// IE = keyCode, DOM = which.
var code = (e.keyCode) ? e.keyCode : e.which;
// If code = 13 (enter) or 3 (return),
// cancel it out; else keep going and
// process the key.
if (code == 13 || code == 3)
return false;
else
return true;
}
// Anonymous method to push the onkeypress
// onto the document.
// You could finegrain this by
// document.formName.onkeypress or even on a control.
window.onload = function() { document.onkeypress = catchEnter; };
Change:
<input type="text" ... >
To:
<textarea ... ></textarea>
You may need to mess around with the attributes a bit, I've left them signified as ....
try to add on the keypress event of your button this javascript function :
function ButtonKeyPress()
{
var code = (window.event.which) ? window.event.which : window.event.keyCode;
if ( code == 13 )
{
event.returnValue = false;
return false;
}
return true;
}
So, you have a form. In this form, you have a text input, and a submit button.
You get in the text input, you type some text, than you press "Enter". This submits the form.
You would like to break this normal behavior.
I think this is not a good idea : The convention says that when your in a text input and press "Enter", it submits the form. If you change this behavior, users could be (I don't find the right word, let's say ~) surprised.
Anyway, if you still want to do this, you should listen for the keypress event on the text input, and than prevent default behaviour shoud do the work.
let's say you use jQuery :
$(input[type=text]).bind('keypress', function(evt) {
if(evt.keyCode == 13) {
evt.preventDefault();
}
});
This should do it. I didn't test it, maybe I made mistakes, but you got the idea, no ?
And maybe keyup is better than keypress... I don't know very well this, not enough practice on key bindings
The easiest way is to set css style like this:
&:focus {
outline: 0 none;
}
I have a form that detects if all the text-fields are valid on each keyup() and focus(); if they're all valid, it will enable the submit button for the user to press. However, if the user fills in one of the text inputs with a browsers autocomplete feature, it prevents the submit button from being enabled.
Is there a way to detect if any of the input has changed regardless of how it's been changed, using jQuery?
You could try using on input to detect text-based changes (except keys like ctrl and shift) in <input>'s.
For example:
$(input).on('input', function() {
console.log($(this).val());
});
The jQuery change event will only fire on blur. The keyup event will fire as you type. Neither fire on clicking an auto-completion option. I am also searching for a way to detect this, but I'm currently going with
$(selector).bind("change keyup",function(){
//Do something, probably with $(this).val()
});
But it doesn't quite solve the problem...
Myself I used
$(selector).on("change keyup blur input", function() {});
which did the trick in Chrome. input is what made it work for autocomplete.
My issue was detecting auto-fill (via a plugin like lastpass or 1password) as well as the issue described above.
The solution that worked for me was:
$(function(){
function validate(){
if($('#email').val() !== '' && $('#password').val() !== '')
$('#submit').prop('disabled', false);
else
$('#submit').prop('disabled', true);
}
// Validate after user input
$('#email, #password').on('keyup change', validate);
// Validate on mouse enter of body and login form
// to catch auto-fills from roboform/1password etc...
$('body, #loginform').on('mouseenter', validate);
// Validate onload incase of autocomplete/autofill
validate();
});
See demo in JSFiddle.
You could use the jQuery .change() function.
After the page initially loads, you can validate the entire form, just to check that it is in fact not filled in. After that you can use .change() to check if things have changed on the form, and if anything has changed, validate the form again.
$(document).ready(function() {
// validate form once, just to be sure (if valid, activate submit button)
});
...
<form>
<input class="target" type="text" value="Field 1" />
<select class="target">
<option value="option1" selected="selected">Option 1</option>
<option value="option2">Option 2</option>
</select>
</form>
<script type="text/javascript">
$('.target').change(function() {
alert('Something changed');
// Try validating form again (if valid, activate submit button)
});
</script>
Plan B
Another option is to always have the submit button clickable, but use .submit() to bind it to the form validator. Then if the form IS valid, carry on. If the form IS NOT valid use .preventDefault() to stop the submission of the form..... and you'd display a warning message too, indicating the missing fields.
The answer has been given in this question. It doesn't use jQuery, but it works for Autocomplete:
Use js onpropertychange event.
I have a decent solution after having the same problem. Set keyup as normal to our form fields, then mouseover to the surrounding div. So once you click the autocomplete option, you mouse will be over the top of the div:
$("#emailaddress").bind("keyup", function() {
displayFullSubcribeForm();
});
$(".center_left_box").bind("mouseover", function() {
displayFullSubcribeForm();
});
I wanted a very good user experience on a field where it would not be invalid (turn red in my case) as long as the user was reasonably active e.g. still filling out the field.
To do this for normal input, I was able to hook up to keyup with a debounce function, while blur is connected for immediate validation. While it appears that keyup is triggered by lastpass, since I have debounced it, there was a delay in validation. Thanks to #peter-ajtai I tried to add the change event and it indeed catches last pass and leaves the other niceties alone.
Coffeescript example:
#fieldExp
.keyup($.debounce(#_onExpChange, 3000))
.blur(#_onExpChange)
.change(#_onExpChange)
This worked well and lastpass form fill triggers immediate validation.
this is the ultimate solution, guaranteed to work
$(document).bind('mouseover', function(){
liveValidate();
});
I have 25 components which includes [textarea, textfile, radio, combo, etc...] and I have written a key event so that when "ENTER" is entered, I call a function which will submit the page.
Now my page is getting submitted when I press enter, even in the textarea which should not be. So is there any way that I can not submit the page if it is pressed in the text area?
This happens only in IE7 and IE8; it works properly in all the other browser.
you could probably detect if any of the textarea, etc is not filled out/emtpy/unset. if all of them are filled out properly, send the form.
Did you attach the "key event" to the whole form? The whole DOM? if you did that's a normal behavior.
If you want the "Enter key" to submit the page when the focus is on the submit button then apply this functionality in the onsubmit event - there of course you can perform all the validation you need.
If you just want to exclude the enter key event from the text area - perform a simple check if the the focus is in the textarea that momemnt.
The default behaviour of a form is to submit if the user hits enter inside the form unless the focus is on a textarea, so what you want is the default behaviour. Remove whatever code you have that currently handles keypresses for the form and you'll have what you want.
I'm not sure if this will suit your needs, but you can disable the enter key inside the textarea with something like this:
$(document).ready(function(){
$('textarea').keypress(function(e){
var key = (window.event) ? e.keyCode : e.which;
if ( key == 13 ) {
return false;
} else {
return true;
}
})
})