1

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() ?

Lewis
  • 3,479
  • 25
  • 40
Filipe Pinto
  • 311
  • 3
  • 17

1 Answers1

1

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 in JavaScript.

Hope I pushed you further.

ThS
  • 4,597
  • 2
  • 15
  • 27
  • How does this improve upon the OPs example? – Lewis Jul 18 '19 at 16:21
  • I'd argue that it's considerably more complicated - seeing as they just want to change the value to a fixed one on click. It's also unrelated to the OPs problem as their code works. Don't get me wrong, I haven't downvoted you - I just don't think this is relevant to the question that was asked. – Lewis Jul 18 '19 at 16:23
  • just for the demo purposes I did use a generated number. The OP can build on my attempt with any "values" he would like to use. Also, I just meant to illuminate his way, so using `value` attribute of the `HTMLInputElement` is more robust than using `setAttribute` function By the way, having such conversations would, without any doubt, make SO better. – ThS Jul 18 '19 at 16:26