Miro
Miro

Reputation: 1806

function in JavaScript

I'm learning basics of JS and I wrote this script but it doesn't work as I aspected. It should add or subtract 10 value inside tag and inside tag value atribute depending on button click.

<!DOCTYPE HTML>
<html>
<head>
<title>Meter</title>
<script type="text/javascript">
function f(a)
{
    document.getElementById("prog").value = document.getElementById("prog").value + a;
    var t = parseInt(document.getElementById("prog"),10);
    document.getElementById("prog") = t + a;
}
</script>
</head>
<body>
<form title="Meter">
<button type="button" onClick="f(-10);" >Subtract</button>
<button type="button" onClick="f(10);" >Add</button>
<meter  min="0" max="100" value="50" id="prog">50</meter>
</form>
</body>
</html>

Upvotes: -1

Views: 130

Answers (4)

JiminP
JiminP

Reputation: 2142

First of all, you should describe what doesn't work as I aspected means.

I think the value inside the <meter> tag not changing is the problem.

My solution is this, using innerHTML:

<!DOCTYPE HTML>
<html>
<head>
<title>Meter</title>
<script type="text/javascript">
function f(a)
{
    //changing the value
    document.getElementById("prog").value = document.getElementById("prog").value + a;
    //(next two lines) changing the innerHTML, which is the inner HTML of an element.
    var t = parseInt(document.getElementById("prog").innerHTML,10);
    //This makes t+a between 0 and 100.
    document.getElementById("prog").innerHTML = t+a<100?t+a>0?t+a:0:100;
}
</script>
</head>
<body>
<form title="Meter">
<button type="button" onClick="f(-10);" >Subtract</button>
<button type="button" onClick="f(10);" >Add</button>
<meter  min="0" max="100" value="50" id="prog">50</meter>
</form>
</body>
</html>

Upvotes: 0

Dogbert
Dogbert

Reputation: 222388

You need to get/set .innerHTML of the element.

function f(a)
{
    document.getElementById("prog").value = document.getElementById("prog").value + a;
    var t = parseInt(document.getElementById("prog").innerHTML, 10);
    document.getElementById("prog").innerHTML = t + a;
}

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 191037

You have to set the property instead the result of the function.

Upvotes: 0

neeebzz
neeebzz

Reputation: 11538

Change the following

var t = parseInt(document.getElementById("prog"),10);

to

var t = parseInt(document.getElementById("prog").value,10);

working version > http://jsfiddle.net/6wJGt/

Upvotes: 0

Related Questions