Automatic change of input fields through Event Handler "onkeyup" - javascript

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>

Related

Button function calling another function

im just a beginner and i want to find the answer to this problem.
This is my html code.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type = "text" name = "step" id = "step">
<button onclick="myFunction()">Submit</button>
<p id = "demo"></p>
</body>
</html>
This is my javascript code.
var step = document.getElementById("step").innerHTML;
parseInt(step);
function matchHouses(step) {
var num = 0;
var one = 1;
while (num != step){
one += 5;
num++;
}
return one;
}
function myFunction(){
document.getElementById("demo").innerHTML = matchHouses(step);
}
What I did is to call the function matchHouses(step) by the click of the button. But the output is always 1. I also put parseInt to the step id as it is string but it is still doesnt work. I was expecting an output of 1+5 if the input is 1, 1+5+5 if the input is two and so on. How do I make it work?
The two key things are that a) parseInt won't do the evaluation "in place". It either needs to be assigned to a variable, or the evaluation done as you're passing it into the matchHouse function, and b) you should be getting the value of the input element, not the innerHTML.
Here are some additional notes:
Cache all the elements first.
Add an event listener in your JavaScript rather than using inline JS in the HTML.
No need to have an additional variable for counting - just decrement step until it reaches zero.
Number may be a more suitable alternative to parseInt which requires a radix to work properly. It doesn't always default to base 10 if you leave it out.
Assign the result of calling the function to demo's textContent (not innerHTML as it is just a simple string, and not a string of HTML markup.
// Cache elements
const step = document.querySelector('#step');
const demo = document.querySelector('#demo');
const button = document.querySelector('button');
// Add a listener to the button
button.addEventListener('click', handleClick);
function matchHouses(step) {
let out = 1;
while (step > 0) {
out += 5;
--step;
}
return out;
}
function handleClick() {
// Get the value of the input string and
// coerce it to a number
const n = Number(step.value);
demo.textContent = matchHouses(n);
}
<body>
<input type="text" name="step" id="step">
<button type="button">Submit</button>
<p id="demo"></p>
</body>
I rewrote your code like this:
let step = 0;
function handleInput(e){
step = e.value;
}
function matchHouses(step) {
var num = 0;
var one = 1;
while (num != step){
one += 5;
num++;
}
return one;
}
function myFunction(){
document.getElementById("demo").innerHTML = matchHouses(step);
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type = "text" name="step" id="step" onkeyup='handleInput(this)'>
<button onclick="myFunction()">Submit</button>
<p id = "demo"></p>
</body>
</html>

I am trying to update my number with current value get from textinput in JavaScript

I am trying to make a program in javaScript in which I want to update number with current
field.
Suppose the number in the field is 5 and then I enter 4 in textfield then the field is updated
with number 9
document.getElementById('btn').addEventListener('click', () => {
console.log("Button clicked")
var newTotal = 0
var input = parseInt(document.getElementById('text').value)
newTotal = input
if (newTotal) {
console.log(newTotal)
newTotal += input
}
console.log(newTotal)
document.getElementById('textField').innerHTML = newTotal
document.getElementById('text').value = ''
})
<input type="text" id="text">
<h3><span id="textField">0</span></h3>
<input type="submit" id="btn" value="Add Numbers">
Try this brother. You have to assign 0 to the newTotal outside of the function. Because if you put it inside the function, every time the function is called, the newTotal will become 0 and then will add the new input to itself.
Than you.
let newTotal = 0
document.getElementById('btn').addEventListener('click', () => {
const input = parseInt(document.getElementById('text').value)
if (input) {
newTotal += input
}
document.getElementById('textField').innerHTML = newTotal
document.getElementById('text').value = ''
})
<input type="text" id="text">
<h3><span id="textField">0</span></h3>
<input type="submit" id="btn" value="Add Numbers">
document.getElementById('text')
//onchange event to update the value
.addEventListener('change', () => {
//checking if the input is valid integer and alerting
var val = document.getElementById("text").value;
if ( +val !== +val) {
document.getElementById('text').value = '';
alert("Enter valid Number");
throw new Error("Enter valid Number");
}
//if the input in valid integer then adding
document.getElementById("textField").innerHTML =
parseInt(document.getElementById("textField").innerHTML) + parseInt(val);
document.getElementById('text').value = '';
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Check</title>
</head>
<body>
<input type="text" id="text">
<h3><span id="textField">0</span></h3>
</body>
</html>
Here throwing error and alerting are optional,

Cannot get raw value from (including dot(.)) from HTML input type number

When I click on the input <input type="number" id="n" /> ; type some key on keypress function of the input. Then typing . though it display on the input but I cannot get see . in $('#n').val().
For example after typing: 123. Then $('#n').val() only return 123.
Is there any attribute of <input type="number" /> that I can get its raw value which is 123. rather than 123?
$("#n").on("keypress", function(event) {
console.log($("#n").val());
});
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<input type="number" pattern="[0-9]{1,2}([\.][0-9]{1,2})?" id="n" step="0.01" />
JSbin demo
UPDATE:
input MUST have type number to allow it to showing number input only on softkeyboard on mobile web.
It should check for pattern 99.99 and work as below:
When type 9 OK // input: 9
type 9 OK // input: 99
type 9 NO, it not match pattern // input: 99
Then type 1 NO, it not match pattern // input: 99
..Free type typing anything rather than dot(.) here...
type dot(.) OK // input: 99.
type 9 OK // input: 99.9
type 9 OK // input: 99.99
type 9 NO // input: 99.99
Without detect the existance dot(.) how can I detect the case of typing multiple . consecutively ?
I've myself faced this issue earlier. Maybe this can help:
$("#n").on("keyup", function(event){
var val = $('#n').val();
if(event.keyCode == 190) {
val+='.';
}
console.log(val);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<input type="number" id="n" />
</body>
</html>
<input type="number"
min="0"
max="999"
step="0.000001"
pattern="[0-9]{1,2}([\.][0-9]{1,2})?"
id="n" />
This Should Solve your problem. Use FocusOut event to capture the value
In order to get a value from input with type numeric, when value ends with a dot, you need to use a hacky solution that requires you to listen to 'onKeyUp' event. This behavior is intentional since numeric input should only return valid numbers.
Here is my implementation of described solution:
const resultContainer = document.querySelector("#result");
let value = null;
const updateValue = (event) => {
const DOT_KEY_CODE = 190;
const BACKSPACE_KEY_CODE = 8;
let newValue = event.currentTarget.value;
if (newValue === "" || newValue === null) {
if (event.keyCode === DOT_KEY_CODE) {
newValue = value.toString() + ".";
} else if (event.keyCode === BACKSPACE_KEY_CODE) {
const valueParts = value.toString().split(".");
const DECIMAL_PART = 1;
const decimalPlaces = valueParts.length > 1 ? valueParts[DECIMAL_PART].length : 0;
const LAST_DECIMAL_PLACE = 1;
if (decimalPlaces === LAST_DECIMAL_PLACE) {
const REMOVE_ONE_CHAR = 1;
newValue = value.toString().substring(0, value.toString().length - REMOVE_ONE_CHAR);
}
}
}
value = newValue;
resultContainer.innerHTML = newValue;
};
<input type="number" onKeyUp="updateValue(event)" />
<div>Received value: <span id="result"></span></div>

How to validate textbox while user are typing values Using javascript

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

nothing happens when I click button

I am trying to make a simple webpage where the user enters in a number and the page tells the user whether the number they entered in is even or odd. I would like to display that in the textbox at the bottom of the screen.
However, when I click the button, nothing happens. I even tried to add an "alert" when the button is pressed, but even that doesn't happen. Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Compute the factors of a positive integer</title>
<script type = "text/javascript">
function oddOrEven(){
var userInput = document.getElementById('number');
var number = number.value;
var output = document.getElementById('display');
alert(number);
if(number % 2 == 0){
output.value = number + " is even!"
}else{
output.value = number + " is odd!"
}
}
</script>
</head>
<body>
<form>
Enter a number to check whether it is odd or even: <input type = "text" id = "number"><br>
<button type="button" onclick="oddOrEven()">Click here to check!</button>
<input type = "text" id = "display">
</form>
</body>
</html>
Take a look at these three lines here:
var userInput = document.getElementById('number');
var number = number.value;
alert(number);
You've retrieved a reference to the #number element and stored it in the userInput variable. Then, you've created a variable called "number," but the value you assigned to it is a property of the variable you just created.
However, this object reference stored in the number variable doesn't have this property, which is causing a runtime error. Try pressing F12 while in your browser with this script running and see what errors appear in the console.
Instead, try this out and see what reaction you get:
var userInput = document.getElementById('number');
var number = userInput.value;
number = parseInt(number);
I see a couple typos in your code, here's a modified version that I think ought to work:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Compute the factors of a positive integer</title>
<script type = "text/javascript">
function oddOrEven(){
var userInput = document.getElementById('number');
var number = userInput.value; // you originally had "number.value", but that doesn't make any sense.
number = parseInt(number); // number is initialy a string, we need to convert it to an integer
var output = document.getElementById('display');
alert(number);
if(number % 2 == 0){
output.value = number + " is even!"
}else{
output.value = number + " is odd!"
}
}
</script>
</head>
<body>
<form>
Enter a number to check whether it is odd or even: <input type = "text" id = "number"><br>
<button type="button" onclick="oddOrEven()">Click here to check!</button>
<input type = "text" id = "display">
</form>
</body>
</html>
You've made a mistake.
You wrote:
var number = number.value;
You should have written:
var number = userInput.value;

Categories