Attempting to make enter button 'clickable' - javascript

I want to make a 'search' button clickable upon clicking enter.
This is my html:
<input type="text" runat="server" id="txtSearch" onkeypress="searchKeyPress(event);"
<input type="button" runat="server" style="padding:5px;" id="butSearch" onserverclick="butSearch_Click" value="Search" disabled/>
This is the JavaScript I am using:
function searchKeyPress(e) {
if (typeof e == 'undefined' && window.event) { e = window.event; }
if (e.keyCode == 13) {
document.getElementById("butSearch").click();
}
}
I am however getting an error
'Uncaught TypeError:Cannot call method click of nul'
Advice perhaps on why I get this error and is there a better alternative at achieving this?

are those runat="server" required? you get the error because when searchKeyPress gets called, your button doesn't exist (yet). Either it's being triggered before DOMContentLoaded, or asp.net is doing funky things with your button, keeping it out of the DOM entirely.
Also some general JavaScript tips:
function searchKeyPress(e) {
// a much cleaner "use var, or assign if not defined":
e = e || window.event;
// strict comparison:
if (e.keyCode === 13) {
// verify we have a button:
var btn = document.getElementById("butSearch");
if (btn) {
btn.click();
} else {
// btn does not exist. arbitrary code goes here
}
}
}

Try instead type="submit" inside input tag.

You can do it like that:
function searchKeyPress(e) {
e = e || window.event;
var key = e.keyCode || e.which;
if (key == 13) {
document.getElementById("butSearch").click();
}
}

In ASP.NET, ids generated client side are not those you see in your ASP.NET markup (have a look at the generated source)
You will need to invoke the ClientID property of your control to access it through javascript or jQuery.
You may try :
function searchKeyPress(e) {
if (typeof e == 'undefined' && window.event) { e = window.event; }
if (e.keyCode == 13) {
document.getElementById('<%=butSearch.ClientID%>').click();
}
}
If you understand how ASP.NET Ids are generated, you may also play with the ClientIDMode of your control, setting it to static.

Related

Whats wrong with this JavaScript if statement?

The function runs when the user presses enter in the textbox (KeyCode === 13) but i cant get it to work with searchButton
function myFunction(e) {
if(e.keyCode === 13 || document.getElementById("searchButton").click()){
e.preventDefault();
var searchValue = document.getElementById("mySearch").value;
for(var i = 0; i < users.length; i++){
if(users[i]['last_name'] === searchValue){
document.getElementById("return").innerHTML = JSON.stringify(users[i]);
return;
}
}
}
}
<input type="search" id="mySearch" onkeypress="myFunction(event)" />
<button id="searchButton" onclick="myFunction(e)">SEARCH</button>
Is the problem the || expression? The function should run either when the user presses searchButton or presses enter.
The call to document.getElementById("searchButton").click() is a programmatic way to simulate a click.
What you probably mean to do is:
function myFunction(e) {
if((e.target.id === 'mySearch' && e.keyCode === 13) || e.target.id === 'searchButton'){
}
}
Ok so when you press the enter key myFunction is called with an event which has the keyCode property, so that is all good.
When you click the button though, the event does not have a keyCode property, and therefore the right side of your conditional document.getElementById("searchButton").click() runs. click is a method that simulates a mouseclick, returning undefined. So the conditional resolves to false, and the rest of the function body will not be run.
You could instead check the type of the event.

How can I disabling backspace key press on all browsers?

I'm trying to disable the backspace button on an order page in all cases except when a textarea or text input is an active element to prevent users from accidentally backing out of an order. I have it working fine in most browsers, but in IE (testing in IE9, both regular and compatibility mode) it still allows the user to hit the backspace and go to the previous page.
Here's the code:
$(document).keypress(function(e){
var activeNodeName=document.activeElement.nodeName;
var activeElType=document.activeElement.type;
if (e.keyCode==8 && activeNodeName != 'INPUT' && activeNodeName != 'TEXTAREA'){
return false;
} else {
if (e.keyCode==8 && activeNodeName=='INPUT' && activeElType != 'TEXT' && activeElType != 'text'){
return false;
}
}
});
Any advice on what I'm doing wrong here?
Thanks!
I think you're overcomplicating that. Rather than checking for an active element, find the event target instead. This should give you the information you need. It's also better to use keydown rather than keypress when there is no visible character. Finally, it's better to use e.preventDefault() for better granularity.
$(document).keydown(function(e) {
var nodeName = e.target.nodeName.toLowerCase();
if (e.which === 8) {
if ((nodeName === 'input' && e.target.type === 'text') ||
nodeName === 'textarea') {
// do nothing
} else {
e.preventDefault();
}
}
});
NB I could have done this the other way round, rather than an empty if block and all the code going in the else block, but I think this is more readable.
Instead of keypress, try the keydown function, it will fire before the actual browser based hook. Also, putting in a preventDefault() function will assist in this. IE :
$(document).keydown(function(e){
e.preventDefault();
alert(e.keyCode);
});
Hope this helps.
The most Simple thing you can do is add the following one line in the very first script of you page at very first line
window.history.forward(1);
Most examples seem to be for the JQuery framework - Here an example for ExtJS
(I've been getting a lot of downvotes for this recently as the question now has JQuery tag on it, which it didn't previously. I can remove the answer if you like as isn't for JQuery but it's proven to help others not using that framework).
To use this add this code block to your code base, I recommend adding it inside the applications init function().
/**
* This disables the backspace key in all browsers by listening for it on the keydown press and completely
* preventing any actions if it is not which the event fired from is one of the extjs nodes that it should affect
*/
Ext.EventManager.on(window, 'keydown', function(e, t) {
var nodeName = e.target.nodeName.toLowerCase();
if (e.getKey() == e.BACKSPACE) {
if ((nodeName === 'input' && e.target.type === 'text') ||
nodeName === 'textarea') {
// do nothing
} else {
e.preventDefault();
}
}
});
Use e.which instead of e.keyCode; jQuery normalizes this value across browsers.
http://api.jquery.com/keydown/
To determine which key was pressed,
examine the event object that is
passed to the handler function. While
browsers use differing properties to
store this information, jQuery
normalizes the .which property so you
can reliably use it to retrieve the
key code.
Then, use e.preventDefault(); to prevent the default behaviour of moving to the previous page.
<html>
<head>
<script type="text/javascript">
function stopKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 8) && (node.type!="text")) {return false;}
}
document.onkeypress = stopKey;
</script>
</head>
<body onkeydown="return stopKey()">
<form>
<input type="TEXTAREA" name="var1" >
<input type="TEXT" name="var2" >
</form>
</body>
</html
I had to add the onDownKey attribute to the body in order to get editing keys to go to the functions.
$(document).keydown(function(e) {
var elid = $(document.activeElement).is('input');
if (e.keyCode === 8 && !elid) {
return false;
}
});
Hope this might help you
Seems like the "backspace" will also act as "navigation back" if you have selected radio buttons, check-boxes and body of document as well. Really annoying for forms - especially when using post. All the form could be lost with one slip of the "backspace" key -_- ...
Honestly... who's idea was it to allow the "backspace as a navigational "back" button!!! really bad idea in my opinion.
I disable the "backspace" default on anything that is not a text area or text field - like this:
$(document).keydown(function(e){
console.log(e.keyCode+"\n");
var typeName = e.target.type;//typeName should end up being things like 'text', 'textarea', 'radio', 'undefined' etc.
console.log(typeName+"\n");
// Prevent Backspace as navigation backbutton
if(e.keyCode == 8 && typeName != "text" && typeName != "textarea"){
console.log("Prevent Backbutton as Navigation Back"+typeName+"\n");
e.preventDefault();
}
//
})
Not sure where else one would want the normal behavior of a back-button other than in these two areas.
document.onkeydown = KeyPress;
function KeyPress(e) {
if (!e.metaKey){
e.preventDefault();
}
}

How do i call a js function on pressing enter key

I'd like to know how I can initiate a javacsript function when pressing the enter key. I'm trying to create a function called handleEnter(event, fn).
I want to use the function on an input field eg:
onkeypress="return handleEnter(event, update_field(this));
For your function called onkeypress, check the event's .keyCode or .which value, and see if it is equal to 13.
function handleEnter(e, func){
if (e.keyCode == 13 || e.which == 13)
//Enter was pressed, handle it here
}
IIRC, IE uses event.which, and Firefox will use e.keyCode to see which key was pressed.
I think I've solved it.
On the input field I've got:
<input onkeypress="return handleEnter(event, update_field, this, 'task');" type="text" />
For my function I've got:
function handleEnter(e, callback, obj, field){
if(e){
e = e
} else {
e = window.event
}
if(e.which){
var keycode = e.which
} else {
var keycode = e.keyCode
}
if(keycode == 13) {
var tstid = $(obj).parent().find('input[type=hidden]').val();
callback.apply(this, [field, $(obj).val(), tstid ]);
}
}
and it seems to be working fine now.
You can try this shorthand
<input type=”text” onKeydown=”Javascript: if (event.keyCode==13) Search();”>
<input type=”button” value=”Search” onClick=”Search();”>
From http://www.techtamasha.com/call-javascript-function-on-pressing-enter-key/25

how to check when field enter/return has been pressed on?

I have multiple fields, typically enter will be pressed on one of the two main ones. I want to know which field enter has been pressed on, how do i do this? (i dont know much JS)
its simple to add an "onkeypress" event to each of the fields, and then in the event handler to examine the keycode that is attached to the event. For example, consider the following code:
form.elements['fieldone'].onkeypress = function(evt) {
if (window.event) evt = window.event; // support IE
if (evt.keyCode == 13) alert("Enter was pressed!");
return true;
}
Please note that under most browsers, pressing ENTER in a form field would post that form. If you don't want that to happen, you can simply return false from the onkeypress handler and that would tell the browser to ignore that key.
Check for enter and set some hidden field (example uses JQuery):
$('#input_text').keyup(function(e) {
//alert(e.keyCode);
if(e.keyCode == 13) {
alert('Enter key was pressed.');
}
});
Include this in your page, it should fire automatically when you hit any key and tell you which html element had focus when it happened.
<script>
document.onkeypress = KeyPressed;
function KeyPressed(e)
{
if (!e) e = window.event;
f ((e.charCode) && (e.keyCode == 13))
alert('Yay! Enter was pressed while field ' + document.activeElement.id + ' had focus!');
}
</script>
You can check from which element the event bubbled from using something like the following
var text1 = document.getElementById('text1');
var text2 = document.getElementById('text2');
text1.onkeypress = keyPresser;
text2.onkeypress = keyPresser;
function keyPresser(e) {
// to support IE event model
var e = e || window.event;
var originalElement = e.srcElement || e.originalTarget;
if (e.keyCode === 13) {
alert(originalElement.id);
}
}
Here's a Working Demo
I would recommend taking a look at the differences in Browser event models and also at unobtrusive JavaScript .
QuirksMode - Introduction to Events
The IE Event Model
Pro JavaScript Techniques - Unobtrusive Event Binding
Use event delegation to avoid attaching event handlers to a large number of elements:
window.onload = function () {
document.onkeyup = function (e) {
e = e || window.event;
var target = e.target || e.srcElement,
keyCode = e.keyCode || e.which;
if (target.tagName.toLowerCase() == 'input' && keyCode == 13) {
alert('Enter pressed on ' + target.id);
}
};
};

Problem with KeyPress Javascript function

I call a javascript function from a textbox by using OnKeyPress="clickSearchButton()"
Here is my function:
function clickSearchButton()
{
var code = e.keyCode || e.which;
var btnSearch = document.getElementById("TopSubBanner1_SearchSite1_btnSearchSite");
if(code == 13);
{
btnSearch.click();
return false;
}
}
My problem is that this function fires when the user hits the enter button in any textbox, not just the one that calls the function. What am I missing?
EDIT: Still not working correctly. So I'll throw my HTML out there if that helps.
<input name="TopSubBanner1:SearchSite1:txtSearch" type="text" id="TopSubBanner1_SearchSite1_txtSearch" OnKeyPress="clickSearchButton(this)" /><input type="submit" name="TopSubBanner1:SearchSite1:btnSearchSite" value="Search" id="TopSubBanner1_SearchSite1_btnSearchSite" />
Also, this is an ASP.NET page if that makes a difference.
The event is by default passed as an argument to your function, but your not capturing it as a parameter. If you capture it, the above should work correctly.
function clickSearchButton(e)
{
e = e || window.event //for IE compliane (thanks J-P)
//etc
or
function clickSearchButton()
{
var e = arguments[0];
e = e || window.event;
Also you have an extra semicolon as Kevin pointed out.
function clickSearchButton(e)
{
var code;
if(window.event)
code = e.keyCode;
else
code = e.which;
var btnSearch = document.getElementById("TopSubBanner1_SearchSite1_btnSearchSite");
if(code == 13)
{
btnSearch.click();
return false;
}
}
and your calling method should be:
onkeypress="clickSearchButton(event)"

Categories