0

How to set value into input that place next from function javascript ?

When tested this code, input id="yyy" will get value = 123 It's ok.

And input id="xxx" will blank result and show error. It's ok. i understand.

But if i want to get value = 123 to input id="xxx" with this code (input id="xxx" place next from function javascript)

How can i do that ? It's possible ?

<form>
    <input type="text" name="yy" id="yy"/> 
</form> 
  
<script>
    var test = "123";
 document.getElementById('yy').value = test;
 document.getElementById('xx').value = test;
</script>
  
<br>
<form>
    <input type="text" name="xx" id="xx"/> 
</form>
j08691
  • 190,436
  • 28
  • 232
  • 252
mamiw
  • 123
  • 1
  • 9
  • 1
    You're running the JS code *before* the `xx` element exists in the DOM. Either move the – Rory McCrossan Dec 12 '17 at 15:45

1 Answers1

1

You are loading the script before the element gets loaded that's y it is giving you undefined. Placing it after the element will solve your problem

<form>
  <input type="text" name="yy" id="yy" />
</form>

<br>
<form>
  <input type="text" name="xx" id="xx" />
</form>
<script>
  var test = "123";
  document.getElementById('yy').value = test;
  document.getElementById('xx').value = test;
</script>
Sanchit Patiyal
  • 4,716
  • 1
  • 12
  • 31