Accesing The Javascript Variable In Html Tag
I am new to 'html' and 'Javascript'. I have the following piece of code using 'html' and 'Javascript' as
Solution 1:
You could use the Framework AngularJS, which supports this exact use (http://angularjs.org/) It's called DataBinding. Your could would look like this:
<div data-ng-controller="myController">
<input type="text" data-ng-model="number"/>
</div>
<script>
var myController = function($scope) {
$scope.number = 10000;
};
</script>
You could also change the javascript to the following:
<script>
var number=10000;
window.onload = function() { //is executed when the window finished loading
document.getElementById('my-id').setAttribute('value', number); //changes the value of the specified element
}
</script>
<input id="my-id" type="text" value="">
Solution 2:
Similar to John Smiths answer, but with jQuery. I personally find it easier to work with. I know it's not necessarily what you're asking but it may help.
This will target all input tags
var number=10000;
$('input').attr('value' , number);
<input type="text">
Add an ID to just target one
var number2=50000;
$('#yourId').attr('value' , number2);
<input id="yourId" type="text">
Add a Class to target as many as you like
var number3=70000;
$('.yourClass').attr('value' , number3);
<input class="yourClass" type="text">
<input class="yourClass" type="text">
<input class="yourClass" type="text">
<input class="yourClass" type="text">
Here's an example with some brief explanations: http://jsfiddle.net/wE6bD/
Solution 3:
This can be done using jQuery
$('#inputID').val(number);
Just add an id tag to the input. (id='inputID')
Solution 4:
You can just use the DOM:
<script>
var number=10000;
</script>
<input id = "myInput" type="text" value="" />
<script>
document.getElementById("myInput").value = number;
</script>
Post a Comment for "Accesing The Javascript Variable In Html Tag"