I’m facing a slight problem when testing how to retreive user’s input into a function to be used later on.
Specifically, in the line: decimalNum = document.getElementById("decimalNum").value;
there is the problem with the ‘value’ method – it says that the element’s value is null. It says so, even if I run the code and input a number.
What am I doing wrong? How do I get to use the user’s input in a function?
Problem resolved, I will accept the asnwer as sooon as I can (cooldown).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1> Converter from Decimal to Binary</h1>
<label for ="decimalNum"> Decimal (natural number): </label>
<input type = "number">
<button id="mySubmit"> Submit </button>
<p id="binaryNum"> </p> <!-- Placeholder for the printed form in the Binary system.-->
<button id="testing"> Test</button>
<script>
let decimalNum;
document.getElementById("mySubmit").onclick = function() {;
decimalNum = document.getElementById("decimalNum").value;
document.getElementById("binaryNum").textContent = `Here is your number in the Binary system: ${decimalNum}`;
};
document.getElementById("testing").onclick = console.log('test was a success')
</script>
</body>
</html>
3
Answers
The input element is missing the id attribute, which is needed to correctly identify the element.
You can try the following way:
add
id="decimalNum"
to your input:<input type="number" id="decimalNum">
Two changes in your code is required.
Like other answers says:
Add ID to the input field.
Second is the prevent the event like below: