<!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>
<input type="text" id="Username" />
<input type="button" id="tutorial" value="Click" onclick="repeatvalue()" />
<hr />
<label id="label"></label>
<script>
function repeatvalue() {
var txtName = document.getElementById("Username");
var lblName = document.getElementById("label");
if (label = "BE20R") {
result = '5layer';
} else {
result = '3layer';
}
lblName.innerHTML = result;
}
</script>
</body>
</html>
This is just my first steps in JS, so I want to ask for help. What I want is that depending on what value I put in the textbox, JS will show the converted value. For example, if I enter "BE20R" I want it to show me "5layers", if I enter another value – "3layers".
4
Answers
I have added a variable called result to store the converted value.
I have added an if statement to check if the value of the input box is equal to "BE20R". If it is, then the value of result is set to "5layer". Otherwise, the value of result is set to "3layer".
I have updated the innerHTML property of the label to set it to the value of result.
This code will now show the converted value depending on what is entered in the input box. For example, if you enter "BE20R", the label will show "5layer". If you enter another value, the label will show "3layer".
You’re very close with this method. Just a little typo, see the Snippet below.
You want to evaluate the
value
of theinput
(txtName
)And evaluating the equivalency values is done with "
===
" in JavaScript (you can use "==
" but "===
" is stricter, MDN Docs and Stack Question discussing the differences)There are other methods, such as Event Listeners, see below: