Somenath Sinha
Somenath Sinha

Reputation: 1214

Function pointer assignment not working

My jQuery is :

$("#qf").change = calc;
$("#sellers_price").change = calc;

function calc()
{
    var data="";
    $qnty = $("#calQnty");
    $unit = $("#calUnit");
    $price = $("#calPrice");

    var value = this.value;
    if(($("#price_based_on").val()=="Kilos")&&($("#unit").val()=="kg"))
    {
        if(this.value<1)
        {
            $qnty.val((this.value*1000).toFixed(2));
            $unit.val("gm");
            $price.val(($("#sellers_price").val()*value).toFixed(2));
        }
        else if(this.value>=1)
        {
            $qnty.val((this.value*1).toFixed(2));
            $unit.val($("#unit").val());
            $price.val(($("#sellers_price").val()*value).toFixed(2));
        }
    }
    else if(($("#price_based_on").val()=="Kilos")&&($("#unit").val()=="gm"))
    {
        var calQnty = this.value*$(this).parents("tr").find('.qnty').text();
        if(calQnty>=1000)
        {
            $qnty.val((calQnty/1000).toFixed(2));
            $unit.val("kg");
            $price.val(($("#sellers_price").val()*value).toFixed(2));
        }
        else
        {
            $qnty.val(calQnty.toFixed(2));
            $unit.val($("#unit").val());
            $price.val(($("#sellers_price").val()*value).toFixed(2));
        }
    }
    else
    {
        $qnty.val((this.value*1).toFixed(2));
        $unit.val($("#price_based_on").val());
        $price.val((json.price*value).toFixed(2));
    }
}

Now, due to the lines $("#qf").change = calc; and $("#sellers_price").change = calc;, whenever the value of either qf or sellers_price changes, the function calc() should be called, right? But when I try it out, it's not working. What am I getting wrong?

I've ensure that the code works when I write it as $("#qf").change(calc); but not when it's written the other way as shown in the code. Why does that happen?

Upvotes: 0

Views: 47

Answers (1)

Pointy
Pointy

Reputation: 413757

The statement

$("#qf").change = calc;

assigns a reference to the calc() function to the "change" property of the jQuery object created by $("#qf"). The correct way to set up an event handler is by calling .change() as you note in your question.

A jQuery object is just an object, and jQuery doesn't set up any fancy getter/setter APIs that could work the way your code is written. Your code constitutes a simple JavaScript property assignment that happens not to have any effect as far as event handling goes.

Upvotes: 3

Related Questions