开发者

How do I pass a textbox value to this $.ajax() call?

The following code works if I hardcode a value for task. That's not very useful in the real world so I'd like to pass the value of a textbox. Unfortuneately, I can't get the value of the textbox, with an id="txtTask", passed to the querystring. The hardcode开发者_开发问答d value is passed but when I uncomment the top inputData assignment and run it, the querystring is null.

Any suggestions? Thanks!

   function btnAddTask_onclick() {
                    //var inputData = { task: $("#txtTask").val() };
                    var inputData = { task: "hard-coded test data"};

                    $.ajax({
                        "url": "AddTask.aspx",
                        "type": "get",
                        "data": inputData, 
                        "success": function (response) {
                            alert(response);
                            $("body").append(response);

                        },
                        "error": function (response) {
                            alert("Error: " + response);
                        }
                    })
                }

And here's the markup...

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>
        To-Do List
    </h2>
    <p>
        <asp:TextBox ID="txtTask" runat="server"></asp:TextBox>
        <input id="btnAddTask" type="button" value="button" onclick="btnAddTask_onclick()" />
    </p>
    <div id="tasks"></div>
</asp:Content>


Since this appears to be asp.net webforms I would use ClientIDMode="static" on the textbox or just define a class and use the class as the selector. My guess is you aren't correctly selecting the textbox because of asp.net webforms id assignments.

<asp:TextBox ID="txtTask" runat="server" ClientIDMode="Static"></asp:TextBox>

If you aren't using .net 4.0 then you will need to add a CSS class to the textbox and reference it by class name as the 'ClientIDMode' is a 4.0 feature.

<asp:TextBox ID="txtTask" runat="server" CssClass="myTaskClass"></asp:TextBox>

var inputData = { task: $(".myTaskClass").val() };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜