Retrieve value from asp:textbox with JQuery

后端 未结 6 1522
闹比i
闹比i 2020-12-06 16:29

I have a few asp:textbox controls in a form on a webpage, below is a snippet. The first is a field where the recipient is entered, the other is a larger textarea where the r

相关标签:
6条回答
  • 2020-12-06 16:57

    As far as I can tell doing

    var recipient = $(".recipient")
    

    Will select all dom elements with a CLASS of recipient. Your input box has a class of "inputBox".

    You need to select by its ID using the #

    So:

    var recipient = $("#recipient")
    

    But you are using ASP.NET controls, which give it a unique ID generated on the server so it's unique. (in your case it's ctl00_contentPlaceHolderRightColumn_recipient)

    To select you will need to do

    var recipient = $("#<%=recipient.ClientID%>")
    

    -edited out some syntax errors

    0 讨论(0)
  • 2020-12-06 16:57

    Through this you can also get asp button or any control for that matter.

    var txt_recipient = document.querySelector("input[id*='recipient']");
    alert(txt_recipient.Value);
    

    you can also try querySelectorAll() if you have multiple controls with same id in client side.

    jQuery Equalent is

    $("input[id*='recipient']").val()
    
    0 讨论(0)
  • 2020-12-06 17:04

    i guess the asp.net HTML controls must have ClientID="recipient" property to access the control using client id in client side. or i have no idea!

    <asp:TextBox ID="recipient" ClientID="recipient" runat="server" name="recipient" class="inputBox" onChange="addNames()" />
    

    try it this should work.

    0 讨论(0)
  • 2020-12-06 17:05

    If you set the clientID of the asp textbox, you should be able to use that in JQuery in the same way as you have, but witha hash instead of the dot.

    E.g.

    ClientID = "recipient"
    
    then
    
        var recipient = $('#recipient').innerHTML() 
    
    or
    
        var recipient = $('#recipient').text() 
    
    0 讨论(0)
  • 2020-12-06 17:12

    I think that jQuery selector returns you a list of objects. Have you tried:

    var recipient = $(".recipient")[0].val();
    

    UPDATE

    What about this then:

    var recipient = $(".recipient:first").val();

    It has a nice advantage as well - will brake on the first match.

    0 讨论(0)
  • 2020-12-06 17:12

    IN ASP.NET, you will need to write in this way:

    var recipient = $("#<%=recipient.ClientID%>").val();

    In MVC, then you can write in this way:

    var recipient = $("#recipient").val();

    0 讨论(0)
提交回复
热议问题