user71812
user71812

Reputation: 457

How to assign two conditions to an input in Javascript?

I have a HTML and JS code that will prompt user to input two values and then the system will show the byproduct of the two numbers. The Javascript code looks like this:

function multiplyBy()
{
    num1 = document.getElementById("firstNumber").value; 
    num2 = document.getElementById("multiplier").value;
    document.getElementById("result").innerHTML = num1 * num2;
}

Now, for num1 input, the user can choose whether he wants to manually input the number or use a slider that will allow him to click on a specific value. The slider is built using html, and here I post the slider code in JS:

The Javascript code for num1 is:

var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;         
num1 = slider.value;

My question is, what code should I add to allow the user choose between manually input or use the slider? Right now I can only assign one input to num1.

Thanks in advance for the help!

Upvotes: 0

Views: 60

Answers (1)

Barmar
Barmar

Reputation: 781503

Use change event listeners to update num1 whenever the user changes either the slider or the manual input.

function save_num1() {
  document.getElementById("demo").innerHTML = this.value;
}
document.getElementById("myRange").addEventListener("change", save_num1);
document.getElementById("firstNumber").addEventListener("change", save_num1);
<input type="range" id="myRange" min="0" max="100">
<br>
<input type="number" id="firstNumber" min="0" max="100">
<br> Result: <span id="demo"></span>

Upvotes: 1

Related Questions