【问题标题】:Why won't JS / JQuery read the text box values?为什么 JS / JQuery 不会读取文本框的值?
【发布时间】:2015-11-18 01:42:33
【问题描述】:

我查遍了为什么这段代码不起作用的原因,我很困惑。

我有一个带有 C# 代码的 ASPX 页面。 HTML 标记有一个运行正常的 JQuery 对话框。单击提交按钮时,对话框关闭,数据被传递到 Web 公开的方法并写入数据库。为 ddl 和 chkbox 控件保存所有值,但文本框的字符串值为空。对于文本框正在填充并且数据正在保存的字段,数据库设置为 NOT NULL,因此我知道正在传递数据,但它不是输入到文本框中的值。

文本框 ID 为 txtCategoryName,客户端 ID 模式设置为静态。我尝试使用以下方法获取值:

var CategoryName = $('#txtCategoryName').val();
var CategoryName = $('#txtCategoryName').text();
var CategoryName = $(document.getElementById('txtCategoryName')).text();
var CategoryName = $(document.getElementById('txtCategoryName')).val();
var CategoryName = document.getElementById('txtCategoryName').value;

所有这些都返回相同的空白字段。我一次尝试了一个。 目前我正在使用这个 JS 代码:

$(document).ready(function () {

var CategoryDialog = $(".EditCategories");
var BtnNew = $("#btnNew");
var CatDDL = document.getElementById("ddlCategoryParent3");
var CatChk = $("#chkCatActive").val();
var CategoryID = 0;
var CategoryName = $("#txtCategoryName").val();
var ParentID = CatDDL.options[CatDDL.selectedIndex].value;
if (CatChk) { CatChk = 1; } else { CatChk = 0; }



var CatDialog = $(CategoryDialog.dialog({

    maxHeight: 1000,
    closeOnEscape: true,
    scrollable: false,
    width: 650,
    title: 'Category Editor',
    autoOpen: false,


    buttons: [
        {
            width: 170,
            text: "Save",
            icons: {
                primary: "ui-icon-disk"
            },
            click: function () {
                $(this).dialog("close");
                window.alert(PageMethods.saveCat(CategoryName, ParentID, CategoryID, CatChk));

            }

        },

        {
            width: 170,
            text: "Delete",
            icons: {
                primary: "ui-icon-circle-minus"
            },
            click: function () {
                $(this).dialog("close");
            }

        },
        {
            width: 170,
            text: "Cancel",
            icons: {
                primary: "ui-icon-circle-close"
            },
            click: function () {
                $(this).dialog("close");
            }

        }
    ]
})






);



BtnNew.click(function () {
    $(CatDialog).dialog('open');
    $(CatDialog).parent().appendTo($("form:first"));

});




});

aspx 页面的代码标记 (categories.aspx)

<div class="EditCategories">
    <div class="Table">
        <div class="TableRow">

                <div class="TableCell">
                           <div class="TextBlock220">Category Name </div>
                </div><!-- End Table Cell -->
                <div class="TableCell">
                    <input id="txtCategoryName" class="ControlTextBox" />
                    <!--<asp:TextBox ID="txtCategoryName" CssClass="ControlTextBox" runat="server" ClientIDMode="Static"></asp:TextBox>-->
                 </div><!--End Table Cell-->
             </div><!-- End Row 1 -->
         <div class="TableRow">
               <div class="TableCell">
                           Parent Category
               </div><!-- End Table Cell -->
               <div class="TableCell">
                    <asp:DropDownList ID="ddlCategoryParent3" runat="server" CssClass="ControlDropDownList" ClientIDMode="Static"></asp:DropDownList>
               </div><!--End Table Cell-->
         </div>
         <div class="TableRow">
                    <div class="TableCell">
                          Active
                    </div><!-- End Table Cell -->
                    <div class="TableCell">
                          <asp:Checkbox ID="chkCatActive"      CssClass="ControlCheckBox" runat="server" ClientIDMode="Static"></asp:Checkbox>
                    </div><!--End Table Cell-->
         </div><!-- End Row 3-->


        </div>
</div>

ASPX 页面的 C# 代码隐藏方法:

[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static string saveCat(string _Name_, int _parent_id_, int ID, int _Status_)
{
    Category eCT = new Category();
    eCT.CategoryName = _Name_;
    eCT.ParentID = _parent_id_;
    eCT.ID = ID;
    eCT.Status = _Status_;
    eCT.Save();
    return eCT.resultMessage; 
}

还有保存方法:

/// <summary>
/// If the ID = 0 the data is written as a new category.
/// If the ID is greater than 0 the data is updated.
/// </summary>
/// <returns>The objects result value will hold the result of the attempt to update data as type Boolean.  The objects resultMessage value will contain the string result of the attempt to add data.</returns>
public void Save()
{

    result = dl.CategoryExists(this);
    if (result) { resultMessage = "The parent category already contains a category named " + CategoryName.Trim(); }
    else { 
        if (ID > 0)
        {
            if (!result) { resultMessage = "There was an unexpected error updating " + CategoryName.Trim() + ". No changes were saved."; }
        }
        else
        {
            result = dl.InsertCategory(this);
            if (!result) { resultMessage = "There was an unexpected error creating the Category."; }
        }
    }
    if (result) { resultMessage = "New Category Successfully Created"; }

}

非常感谢任何帮助。

【问题讨论】:

    标签: javascript c# jquery html asp.net


    【解决方案1】:

    这里的问题是您试图在页面加载后立即获取正确的值,然后再填写输入字段。将此代码放在按钮单击函数中:

    var CategoryName = document.getElementById('txtCategoryName').value;
    

    它应该适合你。如果没有,请告诉我们。

    您的代码应如下所示:

           click: function () {
                // note: CategoryID not used yet.
                var CategoryName = $("#txtCategoryName").val();
                var CatChk = $("#chkCatActive").val();
                var CatDDL = document.getElementById("ddlCategoryParent3")
                var ParentID = CatDDL.options[CatDDL.selectedIndex].value;
                if (CatChk) { CatChk = 1; } else { CatChk = 0; }
                $(this).dialog("close");
                window.alert(PageMethods.saveCat(CategoryName, ParentID, CategoryID, CatChk));
            }
    

    【讨论】:

    • 他们不会在创建元素之前尝试获取值。该元素位于页面的 HTML 中,它们的代码位于 document.ready() 中,因此该元素存在得很好。问题是他们在编辑之前获得了值,因此他们获取的值不是用户编辑的值。您的解决方案会起作用,但您对问题发生原因的解释不正确。
    • 谢谢,我以为那些 DOM 元素是在调用 .dialog() 时才创建的。
    【解决方案2】:

    您在页面启动时从对话框中获取值,然后再对其进行编辑。

    看起来像这样:

    var CategoryName = $("#txtCategoryName").val();
    

    在页面被编辑之前的页面启动时运行。这将获取输入字段的默认值,并且永远不会反映在页面上进行的任何编辑。上面的代码行不会与页面上的输入字段创建“实时”连接。它只是在该行代码运行时获取值,从那时起,与对该字段所做的任何编辑都没有任何联系。

    我认为只有在您真正需要为某些东西赋值时才想获取该值。通常,您不想缓存这样的值,因为缓存的值与页面上实际字段中的值不同步。只需在您需要它的那一刻获取它,它就永远不会有陈旧的价值。

    如果您使用此值的位置在对话框单击处理程序内,则在此处获取它,以便您获得最新值:

            click: function () {
                $(this).dialog("close");
                var CatChk = $("#chkCatActive").val() ? 1 : 0;
                var CategoryName = $("#txtCategoryName").val(); 
                var CatDDL = document.getElementById("ddlCategoryParent3");
                var ParentID = CatDDL.options[CatDDL.selectedIndex].value;               
                window.alert(PageMethods.saveCat(categoryName, ParentID, CategoryID, CatChk));
    
            }
    

    【讨论】:

    • 很好的解释,我认为这与我获取价值的方式有关。我最终删除了变量并将 $("#txtCategoryName").val() 作为传递给我的页面方法的参数放入 click 函数中。我还添加了验证以确保有文本。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2022-08-14
    • 2021-08-07
    • 2013-12-25
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多