简体   繁体   中英

@Html.TextBoxFor text changed event

I have an @Html.TextBoxFor as below :

@Html.TextBoxFor(u => u.SomeProperty, new { @class = "jtb", @id = "TrajName", placeholder = "Traj Name" })

Now what I want to achieve is I want to know when a new character is added to this textbox at the same time it is entered. I want to change a button state to active at this time. I tried blur and change event. But it is fired only when the focus changes.

$(document).ready(function () {
    $('#TrajName').val("");
    $('#StartLocation').val("-Select Location-");
    $('#EndLocation').val("-Select Location-");

    document.getElementById("BtnAddTraj").disabled = true;

    $("#TrajectoryName").blur(function () {
        if ($('#TrajName').text != "")
            document.getElementById("BtnAddTraj").disabled = false;
        else
            document.getElementById("BtnAddTraj").disabled = true;
    });
});

I have a scenario where user can directly try to click on the button after entering some text(ie cursor still inside textbox and focus is not changed).

So is there any event that gives live trigger when a character is added instead of firing on focus change?

You need to bind an event handler to the keyup JavaScript event.

Further more, I recommend you to use .prop for set disabled property.

Please try this:

@Html.TextBoxFor(u => u.SomeProperty, new { @class = "jtb", @id = "TrajName", placeholder = "Traj Name" }) 

 $("#TrajectoryName").keyup(function () {
    if ($('#TrajName').val() != "")
        $("#BtnAddTraj").prop('disabled',false);
    else
        $("#BtnAddTraj").prop('disabled',true);
});

Another solution is to trigger the input event to the TrajectoryName textbox. This would fire every time your input changes.

$("#TrajectoryName").on('input',function () {
    if ($('#TrajName').val() != "")
        $("#BtnAddTraj").prop('disabled',false);
    else
        $("#BtnAddTraj").prop('disabled',true);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM