How to capture the value of a textbox from an OnChange event

末鹿安然 提交于 2019-12-31 07:41:32

问题


In my C# MVC app, I have a series of textboxes that are generated as such...

@foreach (object item in items) 
{ 
    @Html.TextBox(....)
}

The rendered result is a series of text boxes that look like this....

<input class="item-quantities valid" data-bomid="1939" data-rid="2054" id="AddedItemIDs_1939_" name="AddedItemIDs[1939]" onchange="ChangeItemQuantity(156,78)" onkeypress="return isNumberKey(event)" type="text" value="7" aria-invalid="false">

<input class="item-quantities valid" data-bomid="1940" data-rid="1055" id="AddedItemIDs_1940_" name="AddedItemIDs[1940]" onchange="ChangeItemQuantity(159,90)" onkeypress="return isNumberKey(event)" type="text" value="1">

Now, I need a javascript / jquery function in which I can capture three values:

  1. bomid
  2. rid
  3. the new value of the textbox

I am just fine capturing the value when the textbox loses focus (tab out, etc.)

I have tried this (WITHOUT onchange="ChangeItemQuantity()" in the textbox), but for some reason I can never get this event to fire. Plus, I'd rather NOT do it this way, because then I am forced to be rigid on what classes I assign to the textboxes....

    $(function () {
        $('.item-quantities.valid').change(function () {
            var value = $(this).val(); 
            var bomid= $(this).data('bomid');
            var rid= $(this).data('rid');
        });
    });

And I have tried this (WITH onchange="ChangeItemQuantity(159,90)" in the textbox). I would RATHER do it this way, as it allows me to be flexible with the classes in the text box...

function ChangeItemQuantity(bomid, rid) {
    // no idea how I would capture the value here.
}

回答1:


Add another argument to the function to pass the element in and get it's value:

 onchange="ChangeItemQuantity(156,78, this)"

function ChangeItemQuantity(bomid, rid, el) {
    alert(el.value)
}



回答2:


You could fetch the attribute's value like this,

function getValues(){
var actual=$(this).value;
var bomid=$(this).attr('bomid');
var rid=$(this).attr('rid');
}


来源:https://stackoverflow.com/questions/40734094/how-to-capture-the-value-of-a-textbox-from-an-onchange-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!