locked
How to get and set value of @Html.TextBoxFor field using Javascript? RRS feed

  • Question

  • User-1651604128 posted

    I have a table on mvc razor view something like this:

    <table id="Table1">
            <tr>
                <td class="Label1">Name:*</td>
                <td >
                    
                    @Html.TextBoxFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                  
                </td>
            </tr>
    xxxx

    I need to find a way to get or set the "Name" field to empty by using javascript for validation purpose.

    Because the td data of this table are shared with more than tab tables, so I can not use $("#Name").val() to get the value, or use $("#Name").val("") to set it empty.

    So I need to get the set value by using the current table id "Table1",

    I tried this code:

    alert(document.getElementById("Table1").rows[0].cells[1].innerHTML); but it returns all elemnts of Input, I only need the Value of it.

    Any idea how to make it work? thanks in advance,

    Tuesday, January 29, 2019 5:39 PM

Answers

  • User2103319870 posted

    alert(document.getElementById("Table1").rows[0].cells[1].innerHTML); but it returns all elemnts of Input, I only need the Value of it.

    Change your code like below

    alert(document.getElementById("Table1").rows[0].cells[1].getElementsByTagName("input")[0].value);

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 29, 2019 7:34 PM
  • User1520731567 posted

    Hi Peter Cong,

    You could also use jq selector,like:

    $("#Table1 tbody tr td input").val()

    Best Regards.

    Yuki Tao

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 30, 2019 7:11 AM

All replies

  • User2103319870 posted

    alert(document.getElementById("Table1").rows[0].cells[1].innerHTML); but it returns all elemnts of Input, I only need the Value of it.

    Change your code like below

    alert(document.getElementById("Table1").rows[0].cells[1].getElementsByTagName("input")[0].value);

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 29, 2019 7:34 PM
  • User1520731567 posted

    Hi Peter Cong,

    You could also use jq selector,like:

    $("#Table1 tbody tr td input").val()

    Best Regards.

    Yuki Tao

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 30, 2019 7:11 AM