take value from a JS variable and put in an input value

Asked

Viewed 9,356 times

1

I am wanting to take a value of a javascript variable and put inside a input value to send via get.

My JS is like this:

$(window).load(function() {
  var count = 10;

  $('a[name=alex]').click(function() {
    document.getElementById("resultado").innerHTML = "" + count + "";
    count += 10;
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="contador">
  <div class="cont_sub0">
    <h4>Pontuação</h4>
  </div>
  <div class="cont_sub1"><span id="resultado">000</span>
  </div>

  <input type="text" value="resultado" id="resultado">

</div>

I’m not able to put the result in value, this showing perfect, but, no input undesirable.

1 answer

2

The estate innerHTML serves to write or return the contents of an HTML element, in case the attribute you want to change is the value

document.getElementById("resultado").value = count;

See working

$(window).load(function() {
  var count = 10;

  $('a[name=alex]').click(function() {
    document.getElementById("span").innerHTML = "" + count + "";
    document.getElementById("input").value = count;
    count += 10;
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="contador">
  <div class="cont_sub0">
    <h4>Pontuação</h4>
  </div>
  <div class="cont_sub1"><span id="span" name="resultado">000</span>
  </div>

  <input type="text" value="resultado" id="input" name="resultado">
  <a name="alex" href="#">teste</a>
</div>


Other addenda:

  • The attribute id is linked to only one item on each page html;
  • If you want to work in the same way with elements of the same type, you should use document.getElementsByName("name_do_elemento") or document.getElementsByClassName("name_da_class") which are more generic means of picking up multiple elements having the same name or class, respectively;
  • You should also take into account that each element works in a way, inputs the text type changes the value to obtain the expected result, not the content, already elements of the type div, or span, changes the content, for example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.