开发者

How to add an increment(1) to the value of an element with JQuery

<span id="shortfal开发者_运维技巧l" style="color:black">$row[shortfall]</span>

How to increase $row[shortfall] to $row[shortfall]+1 with JQuery?


You need parseInt to handle strings as numbers.

$("#shortfall").text(parseInt($("#shortfall").text()) + 1);


By the time it gets to the browser, your expression will have been evaluated and turned into a number. To use jQuery you'd simply get the text value of the span, convert it to a number, then replace the text value. You will need to convert the value to a number before doing the addition or it will do string concatenation.

$("#shortfall").each( function() {
    $(this).text( Number($(this).text()) + 1 );
});

Updated: I'm using each to show how you would do this using a generic selector that might accept a collection of inputs. In your case, if you know it matches exactly one element, you might optimize it at the risk of having to rewrite it if you wanted the code to apply to multiple elements.

var span = $("#shortfall");
span.text( Number( span.text() ) + 1 );

Updated: need to use text() (or html()) since the element is a SPAN, not an input.


$(document).ready(function(){
  $("#increment").click(function(){
    $(".sl-no").html(function(){
      $(this).html(parseInt($(this).html())+1);
    }); 
  });
});
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <button id='increment'>Click to Increment</button>
<table>
  <tr>
    <th>Sl</th>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td class='sl-no'>1</td>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td class='sl-no'>2</td>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td class='sl-no'>3</td>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td class='sl-no'>4</td>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td class='sl-no'>5</td>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td class='sl-no'>6</td>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
</table>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜