Problem with KeyPress Javascript function - javascript

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)"

Related

Attempting to make enter button 'clickable'

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.

Javascript character restriction and calling a function with getElementById

I have a JS function that checks and restricts certain characters typed in input forms.
The code look like this:
var alphaOnly = /[sA-Za-z\söÖäÄüÜ]/g;
var alphaextraOnly = /[A-Za-z\-&/'"\öÖäÄüÜ]/g;
var alphadigitsOnly = /[sA-Za-z\söÖäÄüÜ\s1234567890]/g;
var digitsOnly = /[1234567890]/g;
var integerOnly = /[0-9\.]/g;
var mailOnly = /[a-z\.#]/g;
function restrictCharacters(myfield, e, restrictionType) {
if (!e) var e = window.event
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
// if they pressed esc... remove focus from field...
if (code==27) { this.blur(); return false; }
// ignore if they are press other keys
// strange because code: 39 is the down key AND ' key...
// and DEL also equals .
if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
if (character.match(restrictionType)) {
return true;
} else {
return false;
}
}
}
It works when I add onkeypress to input like this:
<input type="text" class="span4 register_input" id="firma" name="firma" onkeypress="return restrictCharacters(this, event, alphaOnly);" />
But I want to do that with getElementById in the script. I tried to add this:
window.onload = function() {
document.getElementById("firma").onkeypress = restrictCharacters(this, event, alphaOnly);
}
But it didn't work... Help please.
You can't pass the arguments like that to onkeypress you would need to use a wrapper function
document.getElementById("firma").onkeypress = function (e)
{
return restrictCharacters(this,e,alphaOnly);
};
jsFiddle http://jsfiddle.net/BjU2e/5/
You are assigning to onkeypress the result of restrictCharacters(this,event,alphaOnly) instead of a function delegate. A correct version is in the following jsFiddle : http://jsfiddle.net/xL47r/1/
For future reference :
document.getElementById("firma2").onkeypress = function(e) {
return restrictCharacters(this,e,alphaOnly);
};
You can get this from e.target
document.getElementById("firma").onkeypress = function(e) {
restrictCharacters(e.target,e,alphaOnly);
}
document.getElementById("firma").onkeypress = function(){
return restrictCharacters.call(this/*becauseof 'this.blur()' */, this,event,alphaOnly);
};
You have wrong syntex to bind event with dom .here it is : window.onload = function () {
var ab = document.getElementById("firma");
ab.setAttribute("onkeypress", "restrictCharacters(this,event, true)");
}

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

KeyDown event gets invoked twice

I've got this Prototype code to detect Enter pressing in textarea.
document.observe('keydown', function(e, el) {
if ((e.keyCode == 13) && (el = e.findElement('.chattext'))) {
e.stop();
// foo bar
}
}
And html
<textarea id="chattext_17" class="chattext" cols="20" rows="3"></textarea>
But the problem is, that event gets invoked twice. I even tried to rewrite it to jQuery
$('.chattext').live('keydown', function(e) {
if (e.keyCode == 13) {
e.preventDefault();
// foo bar
}
});
But even then the event gets invoked twice.
When I try to debug it with FireBug, it always jumps here after completing the event handler
function createWrapper(element, eventName, handler) {
var id = getEventID(element);
var c = getWrappersForEventName(id, eventName);
if (c.pluck("handler").include(handler)) return false;
var wrapper = function(event) {
if (!Event || !Event.extend || // always false here
(event.eventName && event.eventName != eventName))
return false;
Event.extend(event);
handler.call(element, event); // here the event gets called again
};
wrapper.handler = handler;
c.push(wrapper);
return wrapper;
}
I'm no Prototype guru, so I don't know where the problem could be.
Why is the keydown event invoked twice?
Works for me. See for yourself at http://jsbin.com/ibozo/edit
<textarea id="chattext_17" class="chattext" cols="20" rows="3"></textarea>
<div id="dbg"></div>
script:
document.observe('keydown', function(e, el) {
if ((e.keyCode == 13) && (el = e.findElement('.chattext'))) {
e.stop();
$('dbg').insert('<div>enter pressed</div>')
}
})
Each debug statement gets inserted exactly once on each press of the [Enter] key. The jQuery version (not posted) behaves exactly the same.
You're doing something else wrong. Perhaps running the function that does the binding twice?
Alternatively this should work:
document.observe('keydown', function(e, el) {
if ((e.keyCode == 13) && (el = e.findElement('.chattext'))) {
e.die();
$('dbg').insert('<div>enter pressed</div>')
}
})

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);
}
};
};

Categories