JQuery keyup event not triggering

2019-08-03 21:38发布

问题:

I'm trying to create a keyup event for 3 fields so that when any one of these 3 fields is typed in it triggers a function. I'm working in IE since this is the only browser our application officially supports. This is the important bits of the html It will be using.

<input title="Buy Price (Cannot be used in conjunction with Percentage Price)" name="BuyRate" size="3" id="BuyRate" type="text" />
<input title="Sell Price (Cannot be used in conjunction with Percentage Price)" name="SellRate" size="3" id="SellRate" type="text" />
<input title="Percentage Price (Cannot be used in conjunction with Buy/Sell Price)" name="PercentagePrice" id="PercentagePrice" type="text" id="PercentagePrice" maxlength="9" size="5" />

And here is the JQuery I currently have.

$("#BuyRate").keyup(function() {
alert("1");
    checkBuySellPercentage();
});

$("#SellRate").keyup(function() {
alert("2");
    checkBuySellPercentage();
});

$("#PercentagePrice").keyup(function() {
alert("3");
    checkBuySellPercentage();
});

function checkBuySellPercentage()
{
alert("4");
    var buyrate = $.trim($("#BuyRate").val());
    var sellrate = $.trim($("#SellRate").val());
    var percentageprice = $.trim($("#PercentagePrice").val());
    if (buyrate !== "" || sellrate !== "")
    {
        $("#PercentagePrice").attr("disabled", "disabled");
    }
    else if (percentageprice !== "")
    {
        $("#BuyRate").attr("disabled", "disabled");
        $("#SellRate").attr("disabled", "disabled");
    }
    else
    {
        $("#BuyRate").removeAttr("disabled");
        $("#SellRate").removeAttr("disabled");
        $("#PercentagePrice").removeAttr("disabled");
    }
}

Why isn't this working correctly?

回答1:

It looks working for me in IE 8 and Google Chrome. When do you execute those script lines? DOM may not be in ready state when you are trying to add event listeners. So, putting such event bindings in jquery's document.ready block is always helpful!

document.ready block example:

$(document).ready(function(){
    // keyup event bindings should be in this block
});