ilhan
ilhan

Reputation: 8995

How to replace a javascript variable's value to a form field?

I have

<script type="text/javascript">
    var battery = navigator.battery || navigator.mozBattery || navigator.webkitBattery;
</script>
<input name="battery" type="hidden" value="">

And I want to replace the battery's value to the input but how?

Upvotes: 1

Views: 3369

Answers (3)

Tom
Tom

Reputation: 4180

<script type="text/javascript">
    var battery = navigator.battery || navigator.mozBattery || navigator.webkitBattery;
</script>
<input name="battery" type="hidden" value="">

<script type="text/javascript">
    document.getElementsByName("battery")[0].value = battery.level;
</script>

this only works if your input is the first with the name battery. If you can give it an id (the input), you can use document.getElementById("id"), wich always exactly returns one element; multiple elements with the same id are not "allowed".

Upvotes: 3

Matt Fellows
Matt Fellows

Reputation: 6532

Put an id on the input and get/set it's value with document.getElementById(inputId).value

e.g.

<script type="text/javascript">
    var battery = navigator.battery || navigator.mozBattery || navigator.webkitBattery;
    document.getElementById("batt").value = battery;

    //and the other way round
    var batt = document.getElementById("batt").value;
</script>
<input id="batt" name="battery" type="hidden" value="">

Upvotes: 1

lvil
lvil

Reputation: 4336

Use DOM functions like this :

var el = document.getElementById(yourId);  
el.value=battery;

You may use some other functions to get the element

Upvotes: 1

Related Questions