【问题标题】:jQuery get / set value of textbox value in a repeaterjQuery在转发器中获取/设置文本框值的值
【发布时间】:2015-08-06 16:33:54
【问题描述】:

我在 ascx 页面中有一个带有文本框 ID="txtBomName" 的转发器,其值从页面加载时的数据表中检索到。 最终用户可以更改值,不能为空/空。 我有 jquery 来检查更改或模糊时是否为空/空,如果为空则产生警报,然后我希望将空值设置回用户输入时的原始 else 设置值。 如果我使用生成的控件 ID,这确实有效,即:

$("#p_lt_ctl02_pageplaceholder_p_lt_zoneMainContent1_BOM_rptBoms_ctl00_txtBomName)"

这显然只适用于页面上的第一个文本框,因为每个框的 ID 的“ct100”部分都会发生变化。 代码:

   $(document).ready(function () {
    $("#p_lt_ctl02_pageplaceholder_p_lt_zoneMainContent1_BOM_rptBoms_ctl00_txtBomName").change(function () {
        var oldVal = this.getAttribute('value');
        if (this.value == null || this.value == "") {
            alert("Please ensure the name is not empty");
            $("#p_lt_ctl02_pageplaceholder_p_lt_zoneMainContent1_BOM_rptBoms_ctl00_txtBomName").val(oldVal);
        }
        else {
            $("#p_lt_ctl02_pageplaceholder_p_lt_zoneMainContent1_BOM_rptBoms_ctl00_txtBomName").val(this.value);
        }
    });
    });

所以,我更改了代码以查找 id$=txtBomName 并设置警报(this.id)每个框的 id 正确显示,我该如何设置文本框的值使用 (this.id).val(oldVal);

【问题讨论】:

  • 你可以为你的文本框使用一个类名,并将事件附加到这个类的所有元素上。

标签: javascript jquery


【解决方案1】:

你需要使用:

 $(this).val(oldVal);

'this' 是对当前对象的引用,即 textArea 上面的代码将设置 textArea 的值

【讨论】:

    【解决方案2】:

    试试这个代码

    $(document).ready(function () {
    
     // The simplest way is to save the original value using data() when the    
     // element gets focus. 
       $("input[id$='txtBomName']").on('focusin', function(){
            $(this).data('val', $(this).val());
        });
    
        $("input[id$='txtBomName']").change(function () {
            var txtBox=$(this);
            var prev = txtBox.data('val');
            var current = txtBox.val();
            if (current) {
                 txtBox.val(current);
            }
            else {
               alert("Please ensure the name is not empty");
                txtBox.val(prev);
            }
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多