Vilas
Vilas

Reputation: 837

Get value of input field in td tag using javascript

I'm trying to get value of input field which is present in <td> tag.

<td class="edit_td1" id="<?php echo $id; ?>">
    <div class="form-group">
        <div class="col-lg-3 inputContainer">
            <input class="form-control cls-quantity" id="quanti_<?php echo $id; ?>" name="number" type="text" />
        </div>
    </div>
</td>
//...some code here
<a href="customer_details.php?shop=<?php echo $_GET['shop'];?>" class="btn btn-info" role="button" onclick="return td_validation();">Generate Bill</a>

and javascript code is:

function td_validation()
{
    //alert("tds validation");
    var tds = document.getElementById('table_id').getElementsByTagName('td');
    var sum = 0;
    //alert(tds.length);
    for(var i = 0; i < tds.length; i ++)
    {
        if(tds[i].className == 'edit_td1' && tds[i].innerHTML==0)
        {
            //alert(tds[i].innerHTML);
            sum +=i;
        }
    }
    if(sum !=0)
    {
        alert("Enter quantity for "+sum+" fields");
        return false;
    }
    else
    {
        return true;
    }
}

Here I want to get value in input field and if this value is 0 then do sum +=i.

Upvotes: 1

Views: 890

Answers (2)

Vilas
Vilas

Reputation: 837

@toivin's answer is correct, I did some modifications in it,

function td_validation()
{
    var tds = document.getElementById('table_id').getElementsByTagName('td');
    var sum = 0;
    for(var i = 0; i < tds.length; i ++)
    {
        if(tds[i].className == 'edit_td1' )
        {
            var a = parseInt(tds[i].querySelector('input.cls-quantity').value);
            if(a==0)
            {
                sum +=i;
            }
        }
    }
    if(sum !=0)
    {
        alert("Quantity should not be zero...!!!");
        return false;
    }
    else
    {
        return true;
    }
}

Upvotes: 0

torvin
torvin

Reputation: 7141

Here is a shorter version of what are you trying to do:

function td_validation()
{
    var tds = document.querySelectorAll('#table_id td.edit_td1');
    var sum = 0;
    for(var i = 0; i < tds.length; i++)
    {
        if (tds[i].querySelector('input.cls-quantity').value === "0") {
           sum +=i;
        }
    }

    if(sum !=0)
    {
        alert("Enter quantity for "+sum+" fields");
        return false;
    }
    else
    {
        return true;
    }
}

Upvotes: 2

Related Questions