Skip to content Skip to sidebar Skip to footer

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:

<divdata-ng-controller="myController"><inputtype="text"data-ng-model="number"/></div><script>var myController = function($scope) {
        $scope.number = 10000;  
    };
</script>

http://jsfiddle.net/L3hrv/

You could also change the javascript to the following:

<script>var number=10000;
window.onload = function() { //is executed when the window finished loadingdocument.getElementById('my-id').setAttribute('value', number);  //changes the value of the specified element
}
</script><inputid="my-id"type="text"value="">

http://jsfiddle.net/k3G44/

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

varnumber=10000;
    $('input').attr('value' , number);

    <inputtype="text">

Add an ID to just target one

var number2=50000;
    $('#yourId').attr('value' , number2);

    <inputid="yourId"type="text">

Add a Class to target as many as you like

    var number3=70000;
    $('.yourClass').attr('value' , number3);

    <inputclass="yourClass"type="text">  
    <inputclass="yourClass"type="text">  
    <inputclass="yourClass"type="text">  
    <inputclass="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><inputid = "myInput"type="text"value="" /><script>document.getElementById("myInput").value = number;
    </script>

Post a Comment for "Accesing The Javascript Variable In Html Tag"