2

I am attempting to write a variable from my javascript document test.js, inside my HTML input tag's value attribute. I have this at the top of my document and want to write the test variable inside an input tag. How can I accomplish this?

test.html

<input type="text" id="my_var" value= document.write(test)> <!--I tried this but have had no luck, want to write inside value. -->

test.js

var test = "hello world";
1
  • I don't think you can execute JS code in HTML without such framework. If you use Angular.js for example, then you can. There are other MV* frameworks that can also complete this task, but a pure HTML cannot execute JS code from the inside of an element Commented Aug 6, 2014 at 15:30

2 Answers 2

1

In javascript you can find your element in various ways. document.getElementById is a function that (like the name suggests) finds your html element by the id attribute. In javascript you can set the value of your html element like this:

test.html

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

test.js

var test = "hello world";
document.getElementById('my_var').value = test;

I can also recommend jQuery if you want to do more html-element manipulations. jQuery is very easy if you know a little CSS, you can select element with the same way, with jQuery you can manipulate the HTML instead of the style. It would look something like this:

test.html

<script src="path-to/jquery.js"></script>
<script src="path-to/test.js"></script>
....
<input type="text" id="my_var" value="">

test.js

var test = "hello world";
jQuery('#my_var').val( test );
Sign up to request clarification or add additional context in comments.

1 Comment

I was able to get it with jQuery. Thanks!
0

Try this

<input type="text" id="my_var" value= document.write(test)>
<script type="text/javascript">document.getElementById("my_var").value=test;</s

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.