Ok so, what I need to do is change some numbers on the screen when keys are pressed, i have it working but I'm not happy with it.
I have a input field and a div that is being updated when the value of the input filed changes. I did that so that I would not be constrained by the input field's blinking carat etc. I don't want to display the input field at all but when I hide it with CSS or type="hidden" it no longer works. I was trying to get this working with JS variables but so far have been unsuccessful.
Any ideas?
HTML
<html>
<head>
<link rel="stylesheet" type="text/css" href="number.css" />
</head>
<body onLoad="focus();myText.focus();changeNumber()">
<div id='number'>
</div>
<input type="text" id="myText" value="1"/>
</body>
<footer>
<script type="text/javascript" src="number.js"></script>
</footer>
</html>
JAVASCRIPT
var myText = document.getElementById("myText");
function changeNumber(){
var userInput = document.getElementById('myText').value;
document.getElementById('number').innerHTML = userInput;
}
// Capture keyDown events
myText.onkeydown = function(e) {
// "34" is the up arrow key
if (e.keyCode == 34) {
// increment the value in the text input
myText.value++;
changeNumber()
// "33" is the down arrow key
} else if (e.keyCode == 33 && myText.value > 1) {
// decrement the value in the text input
myText.value--;
changeNumber()
}
}
HERE IN THE FINAL FIXED CODE * THANKS GUYS! **
HTML
<html>
<head>
<link rel="stylesheet" type="text/css" href="number.css" />
</head>
<body onLoad="focus();number.focus();changeNumber()">
<div id='number' value="1">
</div>
</body>
<footer>
<script type="text/javascript" src="number.js"></script>
</footer>
</html>
JAVASCRIPT
var i = parseInt(1);
function changeNumber(){
var userInput = i;
document.getElementById('number').innerHTML = userInput;
}
// Capture keyDown events for document
document.onkeydown = function(e) {
// "34" is the PGUp key
if (e.keyCode == 34) {
// increment the value in the text input
(i++);
changeNumber()
// "33" is the PGDown key
} else if (e.keyCode == 33 && i > 1) {
// decrement the value in the text input
(i--);
changeNumber()
}
// "66" is the b key
if (e.keyCode == 66){
window.location.reload()
}
}
The problem with your code is this:
myText.value--;
and
myText.value++;
myText is a DOM element, and the value property has a string, not an integer, I'd recommend doing:
var i = parseInt(myText.value);
myText.value = (i++);
Related
I am pretty bad at JS but I need some help at a task in order to prepare for a small exam on web technology.
The task:
I have to write a code where two input fields have to be displayed. The sum of both of the input fields have to be 100. So the input fields will be mainly used for typing in some numbers.
When I type a number in the first input field between 0 - 100 there should be displayed the remaining amount of 100 in the second input field after typing the last number of the first number. This should be also working vice versa. So it should be irrelevant which input field I type in the number. Our professor suggests us to use the event handler "onkeyup".
One example:
First Input field: 3 -> typed in
Second Input field: 97 -> will be shown automatically after typing 3
Please don't laugh, here is my code:
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<script>
function calc() {
var firstnum = document.getElementById("firstprop").value;
var secondnum = document.getElementById("secondprop").value;
var firstresult = 100 - parseInt(secondnum);
var secondresult = 100 - parseInt(firstnum);
if(firstnum >=0){
secondnum = secondresult;
}
if(secondnum >=0){
firstnum = firstresult;
}
}
</script>
<head>
<body>
<input type="text" onkeyup="calc()" id="firstprop"/>
<input type="text" onkeyup="calc()" id="secondprop"/>
</body>
</html>
Thank you very much for your help. I appreciate it, really :)
Here you are
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<script>
function calc(value, index) {
if (index == 1) {
document.getElementById("secondprop").value = 100 - value;
} else if (index == 2) {
document.getElementById("firstprop").value = 100 - value;
}
}
</script>
<head>
<body>
<input type="text" onkeyup="calc(this.value, 1)" id="firstprop" />
<input type="text" onkeyup="calc(this.value, 2)" id="secondprop" />
</body>
</html>
function calc(e) {
if (e.target.id === "firstprop") {
var secondElement = document.getElementById("secondprop");
var value1 = e.target.value ? e.target.value : 0;
secondElement.value = 100 - (parseInt(value1));
}
if (e.target.id === "secondprop") {
var secondElement = document.getElementById("firstprop");
var value2 = e.target.value ? e.target.value : 0;
secondElement.value = 100 - (parseInt(value2));
}
}
</script>
How can i get the latest inputs I entered in order. For example:
I declared an array with 20 elements and when I input something I delete the first element of the array and add at the end the input I just entered.
So when I press the upArrow button the last element of the array will appear as the new input. If I press one more time the upArrow I want my input to change to my second last element and so on.
It doesn't work in my jsfiddle link. It outputs another element from the array.
var singleValues;
var theInputsNumber = 19;
var latestInputs = new Array(20);
latestInputs.fill("Latest");
function clickMe(){
singleValues = $( "#input" ).val();
var c = latestInputs.shift();
latestInputs.push(singleValues);
$( "#output" ).append( singleValues);
$("#input").prop('value', '');
}
$(document).on('keypress',function(e) {
$('#input').bind('keydown', function(e) {
if (e.which === 38) {
$("#input").prop('value', latestInputs[theInputsNumber]);
theInputsNumber--;
}
});
if(e.which == 13) {
theInputsNumber=19;
clickMe();
}
});
<!DOCTYPE html>
<html>
<head>
<title>Think Fast Trivia</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="jqueryScript.js"></script>
<link rel="stylesheet" href="styles.css">
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="output" class="item1"></div>
<input autofocus type="text" name="input" id="input" />
<button id="send" onclick="clickMe()">Send</button>
</body>
</html>
You've missed the idea that you must determine (logic test) the value of the counter (theInputsNumber) in order to reset at the top (and the bottom) of the stack.
I renamed theInputsNumber counter and provided the UP key and DOWN key feature. I also did not limit the array size to 20 as that won't make a difference anyway (array size is not restricted in size as it is in other languages).
EDIT (based on comment): I've placed everything within the HTML so you can save this content into an HTML file and open with your browser. It will work just fine with no server.
<!DOCTYPE html>
<html>
<head>
<title>Think Fast Trivia</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="output" class="item1"></div>
<input autofocus type="text" name="input" id="input" />
<button id="send" onclick="clickMe()">Send</button>
<script>
var counter = 0;
var latestInputs = [];
function clickMe() {
let input = $("#input").val();
latestInputs.push(input);
$("#input").prop('value', '');
}
$('#input').bind('keydown', function(e) {
if (e.which === 38) {
$("#input").prop('value', previous());
} else if (e.which == 40) {
$("#input").prop('value', next());
} else if (e.which == 13) {
clickMe();
}
});
function previous() {
counter = (counter === 0) ? latestInputs.length - 1 : --counter;
return latestInputs[counter];
}
function next() {
counter = (counter === latestInputs.length - 1) ? 0 : ++counter ;
return latestInputs[counter];
}
</script>
</body>
</html>
it looks like your function on upArrow was triggered multiple times (3) every time you pressed that key, I moved it outside of the "keypress" binding and it stays on its own, and the problem no longer exists when i run the code
var singleValues;
var theInputsNumber = 19;
var latestInputs = new Array(20).fill("Latest");
function clickMe() {
singleValues = $("#input").val();
latestInputs.shift();
latestInputs.push(singleValues);
theInputsNumber = 19;
$("#output").append(singleValues);
$("#input").prop("value", "");
}
$(document).on("keypress", function (e) {
if (e.which === 13) {
clickMe();
}
});
$("#input").bind("keydown", function (e) {
var x = e.which || e.keyCode;
if (x === 38) {
$("#input").prop("value", latestInputs[theInputsNumber--]);
if (theInputsNumber === -1) {
theInputsNumber = 19;
}
}
});
<!DOCTYPE html>
<html>
<head>
<title>Think Fast Trivia</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="jqueryScript.js"></script>
<link rel="stylesheet" href="styles.css">
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="output" class="item1"></div>
<input autofocus type="text" name="input" id="input" />
<button id="send" onclick="clickMe()">Send</button>
</body>
</html>
I have some troubles to validate user input while they are typing.
For example: the valid range is 600-800 and user is trying to type 700
When textbox is empty: show nothing
When textbox is 7: show red
When textbox is 70: show red
When textbox is 700:show nothing
I hope I can do it in js, can anyone help me?
Here is an example:
<input type="text" id="myTextBox" onKeyUp="checkInput()" />
<script>
var myTextBox = document.getElementById('myTextBox');
function checkInput() {
var value = myTextBox.value;
if (!value || isNaN(value) || parseInt(value, 10) < 700 || parseInt(value, 10) > 800) {
myTextBox.style.backgroundColor = 'red';
} else {
myTextBox.style.backgroundColor = 'green';
}
}
</script>
The on keyUp event can be used for this, have a look here
Keyp up event
Here is another example, looks like your question was already answered as I was writing this.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset = "utf-8">
<style>
.red {
background-color: red;
}
</style>
</head>
<body>
<form id="myForm">
<input type="text" id="validate" class=""/>
</form>
<script>
function pressHandler(e) {
console.log(this.value);
if (parseInt(this.value) <= 700) {
this.className = "red";
} else {
this.className = "";
}
}
document.getElementById("validate").addEventListener("keyup",pressHandler);
</script>
</body>
</html>
Sounds like you are using the onchange event.
If you try onkeypress it should do what you are after.
You could use both the input and change events. Input will fire when a key press results in a character input. Change will fire when the focus of the text field is lost after the value of the field has changed, and I think in most browsers also after text is pasted into it from the clipboard.
document.getElementById('validate').addEventListener('input', pressHandler);
document.getElementById('validate').addEventListener('change', pressHandler);
I want to know how to detect if a textbox does not contain certain words. For example if the textbox did not contain 'who', 'what', 'why', 'when' or 'where' some sort of function would run.
JavaScript:
function command() {
var srchVar = document.getElementById("srch");
var srch = srchVar.value;
var t = srch;
if (srch == '') {
alert('Please do not leave the field empty!');
}
else if (srch.indexOf('time') != -1) {
alert('The current time according to your computer is' + ShowTime(new Date()));
}
else if (srch.indexOf('old are you') != -1) {
alert("I am as old as you want me to be.");
}
else {
if (confirm('I am sorry but I do not understand that command. Would you like to search Google for that command?') == true) {
window.open('https://google.co.uk/#q=' + srch, '_blank');
}
else { /* Nothing */ }
}
}
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="script.js" type="text/javascript"></script>
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<div class="ui-widget">
<input class="search-field" id="srch" onkeypress="searchKeyPress(event);" placeholder="ask me anything" spellcheck="false">
</div>
</body>
</html>
You will want to call that function when you press a button.
Try something in your HTML like:
<input class="info" onclick="contains();" type="button">
And in your JS
function contains() {
var srchVar = document.getElementById("srch");
var srch = srchVar.value;
if (
(srch.indexOf('who')==-1) &&
(srch.indexOf('what')==-1) &&
(srch.indexOf('why')==-1) &&
(srch.indexOf('when')==-1) &&
(srch.indexOf('where')==-1)
) {
alert("That is not a question");
}
}
You will want to merge this with your command() function in the future.
Also, what does info(); do ?
I'm writing a simple javascript form that checks the input value against the value "blue". Now if you enter "blue", it says it's incorrect, but then if add any additional character, it says correct. It seems like there's a one-character delay, so when I enter "blue" it's only getting "blu". Here is the code:
<html>
<head>
<title>Favorite Color</title>
</head>
<body>
<h1>Quiz Time</h1>
<h2>What is your favorite color?</h2>
<p>Your Answer: <input type="text" id="txtinput" /></p>
<p id="message"></p>
<script type = "text/javascript">
function init() {
var inp = document.getElementById("txtinput");
inp.onkeypress=checkAnswer;
checkAnswer();
}
onload = init;
function checkAnswer() {
var text = document.getElementById("txtinput");
var msg = document.getElementById("message");
var sol = "blue";
var ans = text.value;
ans = ans.toLowerCase();
if (ans.length <=0) {
msg.innerHTML="<span style=\"color:blue;\">Enter Something.</span>";
}
else if (ans == sol) {
msg.innerHTML="<span style=\"color:green;\">Correct!</span>";
} else {
msg.innerHTML="<span style=\"color:red;\">Wrong!</span>";
}
}
</script>
</body>
</html>
Change the event to onkeyup instead of onkeypress
inp.onkeyup=checkAnswer;
Use the HTML5 input event with a fallback to the propertychange event in IE < 9. I've written about this many times on SO; here are two examples:
jQuery keyboard events
Catch only keypresses that change input?