SCS SCS - 2 months ago 6x
jQuery Question

set all negative -1 values into 0 on table load

When the table is loaded i want to set all the values of -1 to 0...

I tried the code below but it is not working.

added the snippet, even with the suggestions is not working...

$(document).ready(function() {
$('#error-ageGroup tbody').each(function() {
var row = $(this).closest("tr");
var bothSexes = row.find(".bothSexesError2").val();
var femaleErorr = row.find(".femaleSexesError2").val();
var MaleError = row.find(".maleSexesError2").val();
if (bothSexes === -1) {

<script src=""></script>
<table id="error-ageGroup" class="table table-bordered table-striped dataTable">
<thead class="heading">
<th>Age Group</th>
<th class="centerTD">Both Sex</th>
<th class="centerTD">Male Count</th>
<th class="centerTD">Female Count</th>
<tbody class="whitebg">
<td class='bothSexesError bothSexesError2'>
<input class="centerTD" name="bothSexesError" type="text" value="-1" readonly/>
<td class='maleSexesError maleSexesError2'>
<input class="centerTD" name="maleError" type="text" value=" -1" />
<td class='femaleSexesError femaleSexesError2'>
<input class="centerTD" name="femaleError" type="text" value="-1" />


Note that val() returns a string, yet you are comparing it to an integer. You need to either convert both to the same data type:

if (parseInt(bothSexes, 10) === -1) { // or (bothSexes === "-1")

Or use a type-insensitive comparison, where the types are automatically coerced to match:

if (bothSexes == -1) { // note '=='. The string will be coerced to a Number for you

Personally I'd use the former as the latter can occasionally lead to unexpected results.


Now that you've added your HTML I can see that there's several issues here.

  • You have duplicated id attributes. You should change them to classes or remove them entirely if they aren't needed.
  • Your code is in a load() event handler, which is redundant as you already run in a document.ready handler, and the element is not an img, iframe etc.
  • You have additional space around the value which can have an effect depending on which comparison method I mentioned above you use. Remove the spaces.

Here's a working example with all the above fixes in place:

Working example