0

I'm trying to create a JavaScript to modify the number in my input field.

Example:

<input value="0">

And then a simple button or div with a JavasSript click function.

<button>Add +10</button>

After clicking on the button:

<input value="10">

Does someone have a place I can read and learn to create this, or any tips to get me started. I know very little JavaScript, but I wish to learn.

Codey93
  • 129
  • 2
  • 12
  • 4
    SO is not the right place for such questions, but take a look at [MDN EventTarget.addEventListener()](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) and [addEventListener vs onclick](http://stackoverflow.com/questions/6348494) – t.niese Jul 10 '16 at 10:34
  • Do you want a solution for your question or tips on finding good tutorials/courses for learning JS? – Chris Satchell Jul 10 '16 at 10:35
  • I would like the solution, I just hope to understand how it works too. – Codey93 Jul 10 '16 at 10:53

3 Answers3

2

Try this or fiddleLink.

ParseInt helps in converting the string value to numbers and add them instead of concatenating. Let me know if you still have some trouble.

var tag1Elem = document.getElementById("tag1");
// The callback function to increse the value.
function clickFN() {
    tag1Elem.value = parseInt(tag1Elem.value, 10) + 10;
  }
  // Reset the value back to 0

function resetFN() {
    tag1Elem.value = 0;
  }
  // Callbacks can be attached dynamically using addEventListener
document.getElementById("btn").addEventListener("click", clickFN);

document.getElementById("reset").addEventListener("click", resetFN);
#wrapper {
  margin: 20px;
}
<p>This is a basic tag input:
  <input id="tag1" value="0" />
  <button type="button" id="btn">Add +10</button>
  <button type="button" id="reset">Reset</button>
</p>
Ayan
  • 2,300
  • 1
  • 13
  • 28
1

You can try this

<input value="0" id="id">

give a id to input field

on button click call a function

<button onclick="myFunction()">Add +10</button>

<script>
    function myFunction() {
        document.getElementById("id").value = parseInt(document.getElementById("id").value) +10;
    }

</script>
shivam
  • 511
  • 3
  • 13
  • Hello, thank you for the quick answer. This seems to do half the job, is it possible to add another 10 when clicking it again. So it hits 20, 30 and so on? – Codey93 Jul 10 '16 at 10:51
0

You can use a click counter like this

and edit it replacing += 1 with += 10. Here my code,

var input = document.getElementById("valor"),
    button = document.getElementById("buttonvalue");
    var clicks = 0;

button.addEventListener("click", function()
                        {
          clicks += 10;
        input.value = clicks;
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Script</title>
</head>
<body>
<input id="valor" value="0">
<button id="buttonvalue">10</button>
</body>
</html>
Community
  • 1
  • 1
Blind
  • 85
  • 1
  • 1
  • 9