Reputation: 336
I'm trying to change the value of a html input element and I want to see the value change on screen. This seems to be a very simple task but it is not working using javascript (but it work with jQuery).
$("#btn1").click(function () {
$("#test1").val("10");
});
function bt() {
document.getElementById("test1").value = "3333";
document.getElementById("test1").setAttribute("value","4444");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Formula 1:
<input type="text" id="test1" value="1111">
</p>
<p>What the answers to these formulas?</p>
<br>
<button id="btn1">Hint</button>
<button id="btn2" onclick="bt()">Hint2</button>
Any suggestion with the javascript function bt() ?
Upvotes: 1
Views: 2280
Reputation: 4783
You can just use the value
property of the input
element after being selected/referenced in JavaScript
.
In the next example, every time you click on the button
with change value
text the input
value will change to New value:
followed by a random number
.
/** selecting the button and the input **/
const btn = document.getElementById('btn2'),
inp = document.getElementById('test1');
/** adding click listener **/
btn.addEventListener('click', () => inp.value = 'New value: ' + Math.ceil(Math.random() * 100)); /** for demo purposes a random number is generated every time the button is clicked. Change the affected value per your requirements **/
<input type="text" id="test1" value="1111">
<p>What the answers to these formulas?</p>
<br>
<button id="btn1">Hint</button>
<button id="btn2">change value</button>
Learn more on
input
element inJavaScript
.
Hope I pushed you further.
Upvotes: 1