简体   繁体   中英

How to get text from a textbox using javascript

i have developed a web application using mvc4.

in this case i need to get a text box value(actually the text entered in the text box) using javascript.

here is the code i am using

    @model PortalModels.WholeSaleModelUser
    @using (Html.BeginForm("uploadFile", "WholeSaleTrade", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)

    <fieldset>
        <legend>WholeSaleModelUser</legend>
        <table>
            <tr>
                <td>
                    <div class="editor-label">
                        @Html.LabelFor(model => model.Name)
                    </div>
                </td>
                <td>
                    <div class="editor-field">
                        @Html.TextBoxFor(model => model.Name)
                        @Html.ValidationMessageFor(model => model.Name)
                    </div>
                </td>
            </tr>
</table>
        <div id="partial">
            <table>
                <tr>
                    <td>
                        <img id="blah" src="../../Images/no_image.jpg" alt="your image" height="200px" width="170px" />
                    </td>
                </tr>
</table>

    <script type="text/javascript">
        function loadUserImage() {
            var userImg = document.getElementById("blah");
            var imgNm = $("#Name").value;
            userImg.src = "D:/FEISPortal/FortalApplication/Img/" + imgNm + ".png";
            alert(imgNm);
            alert(userImg.src);
        }
    </script>

in that case alert gives the value as "undefined" and if do the following modification alert gives nothing.

var imgNm = document.getElementById("Name").value; 

for

var imgNm = $("#Name").value;

how to get the text entered in the text box?

您应该为此使用val()函数:

var imgNm = $("#Name").val();

If you're using native javascript you should use this:

var userImgNameElement = document.getElementById("userImgNameId");
var userImgNameValue = userImgNameElement.getAttribute("value");

With "onChanged" event:

addEvent(document.getElementById('userImgNameId'), 'change', function(event) {
    var userImgNameValue = event.target.getAttribute("value");
});

In an input element, the value of can be found in a value property of that element. It can therefore be retrieved via document.getElementById('idOfElement').value .

In an textarea element has it's value between the starting and the closing tag. Therefore, the value property is empty. In raw javascript, you would be able to retrieve the contents with document.getElementById('idOfElement').innerText .

If you are however using jQuery, Ufuk's solution with .val() is much easier to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM