kavitha vemula kavitha vemula - 6 months ago 58
Javascript Question

Increasing the label value by one on button click using javascript

I have three labels named major 1.0 and 0 with a button and on but click i need to increment the value 0 to 1 on first click and 1 to 2 on second,2 to 3 on third click below is my JavaScript code which works fine if i have a textbox but i need to increment the label value which is 0 now

<script>
function incrementValue() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('number').value = value;
}
</script>

<input type="text" id="number" value="0"/>
<input type="button" onclick="incrementValue()" value="Increment Value" />


how can I take the labels and increase the third label by 1 on every click of button

Answer

Use textContent to get and update the text content inside label. Then get last digit using match(), increment and update the content.

<script>
  function incrementValue() {
    var value = parseInt(document.getElementById('number').textContent.match(/\d+$/)[0], 10);
    value = isNaN(value) ? 0 : value;
    value++;
    document.getElementById('number').textContent = 'major 1.0 ' + value;
  }
</script>

<label id="number">major 1.0 0</label>
<input type="button" onclick="incrementValue()" value="Increment Value" />


It can be more simplified

<script>
  function incrementValue() {
    var label = document.getElementById('number');
    label.textContent = 'major 1.0 ' + ((parseInt(label.textContent.match(/\d+$/)[0], 10) || 0) + 1);
  }
</script>

<label id="number">major 1.0 0</label>
<input type="button" onclick="incrementValue()" value="Increment Value" />


In case the the may vary, then you can do something like this

<script>
  function incrementValue() {
    var label = document.getElementById('number');
    var m = label.textContent.match(/^(.*)(\d+)$/);
    label.textContent = m[1] + ((parseInt(m[2], 10) || 0) + 1);
  }
</script>

<label id="number">major 1.0 0</label>
<input type="button" onclick="incrementValue()" value="Increment Value" />


With your own simple ternary operator

<script>
  function incrementValue() {
    var label = document.getElementById('number');
    var m = label.textContent.match(/^(.*)(\d+)$/);
    var value = parseInt(m[2], 10);
    value = isNaN(value) ? 0 : value;
    label.textContent = m[1] + (value + 1)
  }
</script>

<label id="number">major 1.0 0</label>
<input type="button" onclick="incrementValue()" value="Increment Value" />

Comments