Executing JavaScript on Key Press - javascript

I'm doing some very rudimentary javascript work and seem to hit a bump. For the life of me, I can't seem to find what should be a very basic answer on Google.
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">
function lowerCase(){
var input = document.send.inputText;
input.toLowerCase();
document.write(input);
alert(input);
}
</script>
</head>
<body>
<h1>Test Page</h1>
<form name="send">
<input type='text' name="inputText" onkeypress="lowerCase()"/>
</form>
</body>
</html>
My intent is that the function lowerCase is executed on entering information into the textbox and pressing enter. However, I can never seem to get the function to execute.

How about...
HTML:
<input type='text' name="inputText" onkeypress="lowerCase(this)">
JavaScript:
function lowerCase ( input ) {
setTimeout( function () {
input.value = input.value.toLowerCase();
}, 0 );
}
Live demo: http://jsfiddle.net/vXpj8/3/
function lowerCase ( e ) {
if ( e.keyCode === 13 ) {
this.value = this.value.toLowerCase();
e.preventDefault();
}
}
document.send.inputText.onkeypress = lowerCase;
Live demo: http://jsfiddle.net/vXpj8/1/
Notice, how I bind the event handler with JavaScript. I do this because I want to have the event object available in the function.

There's a space between the onkeypress attribute and equals sign. Remove that; it should work.

Fiddle: http://jsfiddle.net/iambriansreed/jEnxH/
<form name="send">
<input type='text' name="inputText">
</form>
<script>
document.send.inputText.onkeypress = function(event){
if(event.keyCode != 13) return;
this.value = this.value.toLowerCase();
alert(this.value.toLowerCase());
event.preventDefault();
};
</script>

If you want it to work when the enter key is pressed, then you'll need to deal with the form being submitted, since pressing enter in a text input element that is a form control submits the form.
More likely you want to change the value to lower case on some other event, such as keup, e.g.
<input onkeyup="this.value = this.value.toLowerCase();" ... >
Doing this sort of thing is a bit annoying for users though, since upper case letters are magically changed to lower case. If there is a back-end requirement for lower case letters, better to deal with it there than confuse users entering text.

a few issues with your code
first var input is a input box not the string, toLowerCase() is a string method, you need input value
var input = document.send.inputText;
alert(input.value);
second, onkeypress is excuted before text is entered, maybe you should consider change onkeypress to onkeyup
try if this helps
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">
function lowerCase(){
var input = document.send.inputText;
input.value = input.value.toLowerCase();
}
</script>
</head>
<body>
<h1>Test Page</h1>
<form name="send">
<input type='text' name="inputText" onkeyup="lowerCase()">
</form>
</body>
</html>

Related

issue with using innerHTML() and inserting javascript variable values into HTML

I am working on a small word counter for a school assessment and can't see what is wrong with this code. The idea is when you hit the submit button, it displays "Word Count: " and the amount of character put into a text box. I have showed the teacher my code and he agrees that he doesn't see a problem with it.
Javascript:
window.onload = function(){
var input = document.getElementById(userInput).value;
if(submit.onclick) {
document.getElementById("wordCount").innerHTML = "Word Count: " + input.length;
};
};
HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<h1 style='font-family:verdana;text-decoration:underline;'>Word Counter</h1>
<p>Please input text into the text box below:</p>
<input type='text' id='userInput'/>
<button id='submit'>Submit</button>
<p id='wordCount'></p>
<script type='text/javascript' src='script.js'></script>
</body>
</html>
document.querySelector('#submit').addEventListener('click', function(e) {
const input = document.querySelector('#userInput');
const inputValue = input.value;
const wordsArray = inputValue.split(' ');
document.querySelector('#wordCount').innerText = `Word Count: ${wordsArray.length}`;
})
<h1 style='font-family:verdana;text-decoration:underline;'>Word Counter</h1>
<p>Please input text into the text box below:</p>
<input type='text' id='userInput'/>
<button id='submit'>Submit</button>
<p id='wordCount'></p>
First on window load there is likely no information inside the #userInput, meaning
var input = document.getElementById(userInput).value; will be undefined or ''.
Second, you have no click event bound to your submit button so
submit.onclick will return false;
Binding DOM events
Lastly I switched from using .innerHTML to .innerText as there is no HTML being added into it. Also you your original code was not getting the word count, but would have returned the character count of the input text. To get word count I split the input text on spaces and returned the length of that array as the word count.
Try putting quotes around your userInput inside your getElementById. Right now you're trying to get an element by an ID of undefined because the userInput variable doesn't exist.

How to ignore whitespacing in input boxes

I need your help,
Normally when a user inputs data, how can the code be modified below so as to program it to ignore any whitespacing, i.e. "a blank keyboard space" ?
Here is the HTML markup in question:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload = function() {
$("#fileno").bind("input", function(e) {
$('#save').prop('disabled', false)
});
}
</script>
</head>
<body>
<input type="button" value="save" id="save" disabled>
</body>
</html>
Use the Trim function
https://www.w3schools.com/jsref/jsref_trim_string.asp
fieldName = element.property.Trim()
You can try adding a pattern attribute with regex to check or you can add a simple check in javascript when clicking the button to submit it.
regex pattern like:
pattern="[A-Za-z0-9]"
javascript jquery check like:
if($('#inputId').text()) this check will not pass if the value is undefined, null or empty string

External JavaScript file issues

Now this is just for reference for a future project but I am trying to call a function that reads in a string but displays a float after. So I first check the string then display a random number. The problem I am having, I think, is with the document.getElementById part. Any suggestions??
HTML File:
<html>
<body>
<input type="text" id="letter" value=""/><br/>
<input type="button" value="LETS DO THIS!" onclick="floatNum();"/></br>
<script type="text/javascript" src="letNum.js"></script>
</body>
</html>
External JS File:
function floatNum()
{
var val1 = document.getElementById("letter");
if (isNaN(val1)
{
alert(Math.random())
}
}
the following code is working:-
in your code,you missed closing parenthesis ")" near to "if condition"
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>demo</title>
<script type="text/javascript">
function floatNum()
{
var letter = document.getElementById("letter");
if (isNaN(letter.value))// using input fields value not the whole object
{
alert(Math.random());
}
}
</script>
</head>
<body>
<input type="text" id="letter" value="" /><br />
<input type="button" value="LETS DO THIS!" onclick="floatNum();" />
</body>
</html>
Yes, you want to pass in the element in the function, like so:
<input type="button" value="LETS DO THIS!" onclick="floatNum(document.getElementById('letter'))"/></br>
And in your JS
function floatNum(el)
{
if (isNaN(el)
{
alert(Math.random())
}
}
In case of a reusable function - try not to make it dependent on your DOM. Think about what would happen if you rename your element or want to use this function again. You couldn't before - now you can.
The problem is on this line:
var val1 = document.getElementById("letter");
It should be:
var val1 = document.getElementById("letter").value;
The first sets val1 to the DOM element representing the input tag, the second sets it to the text value of the input tag (its contents).
You need to process the value of input field not the input field itself.
function floatNum()
{
var letter = document.getElementById("letter");
if (isNaN(letter.value) // using input fields value not the whole object
{
alert(Math.random())
}
}
You don't grab the value of the input, but the input itself.
Correct code would be :
var val1 = document.getElementById("letter").value;

How show values using JavaScript?

I am new with JavaScript, I have a value in an input field, like 0 or 1 and then when this value changes a word is changed to 'Off' or 'On' respectively.
I know this is pretty simple but I'm new with JavaScript as I said.
How does your code look like currently?
What have you tried so far?
EDIT
I'm working in the code right now so nothing great so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function change(value) {
if (value == 1)
return "ON";
else
return "OFF";
}
</script>
</head>
<body>
<input type="text" value="1" />
<p>ON OR OFF RIGHT HERE</p>
</body>
</html>
What difficulties are you encountering?
I need this values keep been updating all the time, if the value of the input field change the word must change either.
If you are new to javascript what tutorials/articles/books did you read so far in order to get started?
Not a specific tutorial right now, I'm googling.
EDIT 2
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function change(){
toggler = document.getElementById('toggler');
onoff = document.getElementById('onoff');
toggler.onChange = function(e){
onoff.innerHTML = (toggler.value==1)? 'on' : 'off';
}
}
</script>
</head>
<body>
<input type="text" id="toggler" value="1" onkeyup="change()" />
<div id="onoff"></div>
</body>
</html>
I'm trying to following the suggestions but still not working, what am I doing wrong here guys ?
You don't posted any code but here it goes some general code:
Your input:
<input type='text' id='myinput' onkeyup='contentChanged(this)' />
Look for other key events: http://unixpapa.com/js/key.html
Then, your function:
function contentChanged(myinput)
{
var myvalue = myinput.value;
if (myvalue == "1")
{
// Do something with value = 1
}
else if (myvalue == "0")
{
// Do something with value = 0
}
// And so on...
}
EDIT:
Now that you've posted your code, you can do like as I said:
<input type="text" value="1" onkeyup="change(this.value)" />
EDIT 2:
You're setting two events to your object and onChange just works to select object. Because of this I suggested you to use onkeyup or another key event. Just remove your onChange event out of your function.
Change to this and try:
function change(){
toggler = document.getElementById('toggler');
onoff = document.getElementById('onoff');
onoff.value = (Number(toggler.value)==1)? 'on' : 'off';
}
Number function is important to cast your input data and be sure that is a number.
Plus add an maxlength attribute on your textfield to limit user input data:
<input type="text" id="toggler" value="1" onkeyup="change()" maxlength="1" />
You need to add an onChange handler to your input field, this can be done in many ways. for example, let's say your input has an id of #toggler, and the element where either on or off needs to be shown has an id of #onoff
toggler = document.getElementById('toggler');
onoff = document.getElementById('onoff');
toggler.onChange = function(e){
onoff.innerHTML = (toggler.value==1)? 'on' : 'off';
}

FireFox capture autocomplete input change event

I'm trying to subscribe to change events on an input tag for an ajax auto complete form. These change events are not firing when the user clicks an autocomplete suggestion from FireFox.
I've seen fixes for IE, but not FireFox. You can view this behavior here
Steps to recreate:
type any input in one of the boxes and click submit.
Start typing the value again in the same box.
You should see the autocomplete suggestion box appear below the input box. Notice that clicking the suggestion does not fire the change event (it also doesn't fire the click event)
Currently my only option is to disable autocomplete on this field, but I do not want to do that.
Firefox 4+ fire 'oninput' event when autocomplete is used.
Here's some jQuery to make this more actionable:
$('#password').bind('input', function(){ /* your code */});
I've had the same problem.
Apparently, there is password manager debugging available
https://wiki.mozilla.org/Firefox:Password_Manager_Debugging
So I've found that for me DOMAutoComplete event got triggered and
I've managed to attach it sucessfuly to a field via jQuery's bind like
$('#email').bind('DOMAutoComplete',function() { ...
If it makes you feel better, it is a known bug
Proposed workaround: (Not mine, from here
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Mozilla Firefox Problem</title>
<script type="text/javascript">
function fOnChange()
{
alert('OnChange Fired');
}
var val_textBox;
function fOnFocus()
{
val_textBox = document.getElementById('textBox').value;
}
function fOnBlur()
{
if (val_textBox != document.getElementById('textBox').value) {
fOnChange();
}
}
</script>
</head>
<body>
<form name="frm">
<table>
<tr>
<td><input type="text" id="textBox" name="textBox" onFocus="fOnFocus()" onBlur="fOnBlur()"></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</form>
</body>
</html>
Another Suggested work around. This time using polling, you can work it in exactly
the same way, checking for "changes" to your field. Tweak the poll value (default to
375ms for your own taste).
I've used jQuery and a jquery plugin someone wrote:
https://github.com/cowboy/jquery-dotimeout/
Git Hub Src: https://raw.github.com/cowboy/jquery-dotimeout/master/jquery.ba-dotimeout.js
<html>
<head>
<meta charset="utf-8">
<title>onChange() for Firefox / IE autofil get-around</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="/~dsloan/js/ba-dotimeout.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var val;
var count=0; // used to illustrate the "poll count"
// when focusing on the element and typing
// (vs not focused)
// set a focus function to poll the input
$("#myname").focus(function() {
// start polling
$.doTimeout('checkname', 375, function() {
++count;
// no changes, just exit this poll
if($("#myname").val() == val) {
return true;
// store the value
} else {
val = $("#myname").val();
}
var str;
// do stuff here with your field....
if($(document.activeElement) &&
($(document.activeElement).attr('id') ==
$("#myname").attr('id'))) {
var len = $("#myname").val().length;
if(len == 0) {
str = 'Timer called, length 0...';
} else if(len < 2) {
str = 'Timer called, length < 2...';
} else {
str = 'Timer called, valid!';
}
}
// show some debugging...
$("#foo span").html(str+' (count: '+count+'): '+
$(document.activeElement).attr('id')+
', val: '+$("#myname").val());
return true;
});
});
// set a blur function to remove the poll
$("#myname").blur(function() {
$.doTimeout('checkname');
});
});
</script>
</head>
<body>
<form action="#" method=post>
Name: <input type="text" name="name" value="" id="myname" />
Scooby: <input name="scooby" value="" id="scooby" />
<input type="submit" value="Press Me!" />
</form>
<div id="foo"><span></span></div>
</body>
</html>
A possibly alternative: could you simply use a timer to tell when the value of the text box changes?
You're going to have to blur the input field and reset the focus to it. That's going to require a little trickeration though.

Categories

Resources