1

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?

3 Answers 3

3
<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".

Sign up to request clarification or add additional context in comments.

3 Comments

document.getElementsByName("battery")[0].value = battery.level;
why do we add .level with that ?
Battery.level returns the battery level
1

Use DOM functions like this :

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

You may use some other functions to get the element

Comments

1

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="">

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.