Javascript input onkeypress function do not work - javascript

I put the script in head tags
function check(e, regexp) {
if(navigator.userAgent.indexOf('Gecko') != -1) {
charCode = e.which;
} else {
charCode = e.keyCode;
}
if(charCode > 31) {
znak = String.fromCharCode(charCode);
return regexp.test(znak);
}
}
When I use this function in input
<input id='pole2' name=nip style='WIDTH: 300px;' onkeypress='return check(event, /[0-9-]/i);'>
it works great with HTML.
But when I create in javascript input with id='odbiorca' and if I try to use onkeypress with the same code
document.getElementById("odbiorca").onkeypress = function() {myfunction()};
function myFunction(){
return check(event, /[0-9- ]/i);
}
It does not want to work. What is wrong?

The last line of the script should be written like this:
document.getElementById("odbiorca").onkeypress = function(event) {return check(event, /[0-9- ]/i);}
As you see the typo was not a main problem. Keep this solution for others.
Thanks to Merijn for suggestion with browser console.

The problem is that you mispelled myFunction:
document.getElementById("odbiorca").onkeypress = function() {myfunction()};
function myFunction(){
return check(event, /[0-9- ]/i);
}
myFunction is with a capital F but you call it with a small f (myfunction instead of myFunction) beside that it should work!
EDIT: try to check your browser console first next time. You could have seen the very clear error:
Uncaught ReferenceError: myfunction is not defined
at HTMLInputElement.document.getElementById.onkeypress

Related

How to match anything between < & > in regex?

I'm trying to match anything that lies between < and >, and nothing seems to be working.
My current code is:
var regex = /\<(.*?)\>/
var targeting = $('#auto-expand').val //A text area
function validateText(field)
{
if (regex.test(field) == true)
{
alert(field.match(regex))
}
else
{
alert("fail")
}
}
It keeps returning fail, not sure why.
Any help would be so great! :)
It's not clear from your question how you are calling the validateText function. But it looks like are trying to set targeting outside the function, which means you are probably setting it before there's text in the box.
Below I change val to val() to call the function and looked up the value when the function runs rather than before. The regex itself works fine (keeping this in mind)
var regex = /<(.*?)>/
function validateText() {
var targeting = $('#auto-expand').val() //A text area
if (regex.test(targeting) == true) {
alert(targeting.match(regex))
} else {
alert("fail")
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="auto-expand"></textarea>
<button onclick=validateText()>Test</button>

RegExp for current character JavaScript

I'm trying to validate a character to make sure it's a letter (not a number, symbol, etc.) BEFORE it's allowed to be entered into the form field. How can I do that with JavaScript?
Here is something I tried:
<script type="text/javascript">
function checkTest() {
var letterValue = document.forms[0].test.value;
var letterCheck = /[a-z]/i;
var letterTest = letterValue.test(letterCheck);
}
</script>
<html>
<body>
<form>
<input type="text" name="test" onkeypress="checkTest();"/>
</form>
</body>
</html>
This code will check the string of the value. I've tried using var letterLeng= letterValue.length and then using var letterChar = letterValue.charAt(letterLeng) or even var letterChar = letterValue.charAt(letterLeng - 1) and all to no avail. Any advice would be much appreciated.
Ask the event for the key that was pressed then test it:
function checkTest(event) {
event = event || window.event;
if (!/[A-Za-z]/.test(String.fromCharCode(event.keyCode || event.which))) {
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
}
}
<input type="text" name="test" onkeypress="checkTest(event);"/>
I like Alex K's answer, but I could not get the 'onkeypress' handler to work so I tried something using Jquery. It doesn't keep the bad letters from appearing briefly, but it does keep them from being entered.
It uses the 'keyup' event, which actually makes checking for the key code much easier in this instance since you want to limit it to [a-zA-Z]
$("#myinput").on("keyup", function (e) {
// Ignore the shift key.
if (e.keyCode === 16) {
return true;
}
if ((e.keyCode < 65 || e.keyCode > 90)) {
var str = $("#myinput").val();
$("#myinput").val(str.slice(0, str.length - 1));
}
});
The working fiddle is here: http://jsfiddle.net/yaa9snce/
What you are looking for is the onkeypress event.
<input type="text" onkeypress="myFunction()">
<script>
function myFunction() {
alert("You pressed a key inside the input field");
}
</script>

jQuery sending event as parameter

I want to check the amount of typing characters in an input using keyup and keydown.
I've done it earlier but not as separate function and it was a big mess in a code. I use
event and when I did it without separate function everything worked great, but now I have a problem with send it through the functions. Maybe it's caused by totally wrong method to do this, so please give me some advice, how to do it properly.
This is my separate function:
function char_check($input_id, $div_id, $char_max, event)
{
if(($char_max-$($input_id).val().length)<=0)
{
var key = event.keyCode || event.charCode;
if(key!=8)
{
event.preventDefault();
}
}
if(($char_max-$($input_id).val().length)<0)
{
$($div_id).text("Your data will be cut short!");
}
else
{
$($div_id).text($char_max-$($input_id).val().length);
}
}
And this is the way I call this function:
$('input[name=author]').keydown(function(e){
char_check($(this), "#chars_auth", 50, e);
});
Problem: Event doesn't work.
As I understand it the code does not work, though I am not sure what does not work. Here are some suggestions. First I would create a function that builds your "check function". Something like:
var createCharCheck = function (div_id, char_max) {
return function (event)  {
if ((char_max - $(this).val().length) <= 0) {
var key = event.keyCode || event.charCode;
if(key != 8) {
event.preventDefault();
}
}
if((char_max - $(this).val().length) < 0) {
$(div_id).text("Your data will be cut short!");
} else {
$(div_id).text(char_max - $(this).val().length);
}
}
}
$('input[name=author]').keydown(createCharCheck('#chars_auth', 50));
This is not to be fancy, but save you some code and take advantage of closure. Now you have a function that you can use on any input. Hope this helps.

onkeyup handler not being called

I found a post on SO that was actually posted yesterday (I cannot find it now) that says my code below should work, but it does not -- the 'handleRtnKey(e)' function below is never called - why?
<input type="text" id="zer" onkeyup="handleRtnKey(e)"/>
// my javascript function -- by the way, I will not be using jquery.
function handleRtnKey(e)
{
alert("Just entered handleRtnKey()");
if (!e)
{
e = window.event; // resolve event instance for IE
}
alert("Just entered handleRtnKey(), e.keyCode is: " + e.keyCode);
alert("Just entered handleRtnKey(), e is: " + e);
if (e.keyCode == '13')
{
alert("handleRtnKey: got the RTN key up event.");
return false;
}
}
None of the alerts fire.
I found a SO post from yesterday that had this near exact code (without my alerts) that claimed to work fine (sorry I cannot re-find that SO post).
I need to use straight javascript (not jquery) to get the key code of the keyup event in my input text box -- that's all I need to do, and if it is the Return key, then I'll take some action, but for now I cannot get the above code to fire that handleRtnKey() function -- why?
EDIT
Damon introduced me to the keyword 'event' and the above code now works fine -- I simply renamed the argument in the html code from 'e' to 'event' and the javascript handler now works fine -- here is the only modification to the code above I had to make:
// OLD
<input type="text" id="zer" onkeyup="handleRtnKey(e)"/>
// NEW
<input type="text" id="zer" onkeyup="handleRtnKey(event)"/>
NOTE: the javascript function handleRtnKey(e) is unchanged, there was no reason for my to change that function's signature, it looks like below and works fine now:
function handleRtnKey(e)
{
alert("Just entered handleRtnKey()");
if (!e)
{
e = window.event; // resolve event instance for IE
}
alert("Just entered handleRtnKey(), e.keyCode is: " + e.keyCode);
alert("Just entered handleRtnKey(), e is: " + e);
if (e.keyCode == '13')
{
alert("handleRtnKey: got the RTN key up event.");
return false;
}
}
THANKS DAMON.
you don't need argument at all, just use event:
function handleRtnKey() {
event = event || window.event; // for cross-browsing
alert(event); // or do whatever you want with it
};
DEMO
The problem is that you call the method with parameter which you don't have. e is not declared. If you remove it it will work. This code worked for me:
<input type="text" id="zer"/>
<script>
window.onload = function () {
document.getElementById("zer").onkeyup = function(event) {
if (event.keyCode == 13) {
alert("Just entered handleRtnKey()");
}
};
};
</script>
The solution to my problem was as Damon pointed out in his comments above -- I was not aware there was a predefined 'event' keyword and when I used 'event' instead of 'e' in my code above, it worked fine.

.focusout() only reading through first if() statement

Why is this not reading through both if statements even though they are both true?
HTML
<textarea name="test">
Focus out to test prompts
</textarea>
jQuery
var disableA = 1;
var disableB = 1;
$('textarea[name="test"]').focusout(function() {
if (disableA == 1) {
disableX();
}
if (disableB == 1) {
disableY();
}
});
function disableX() {
alert('A is disabled');
}
function disabledY() {
alert('B is disabled');
}
Right now it will call for disableX(); but not disableY()
jsFiddle: http://jsfiddle.net/nCQQm/
In your second function you have called it disabledY, whereas you are calling back disableY()?
You spelled disableY wrong you need to rename it to disabledY()
There is no problem with the if statements.
Running your code gives the error:
ReferenceError: disableY is not defined
You have named the second function disabledY, and then you try to call disableY.

Categories