【问题标题】:Get Value of Table Row with Button Click Using jQuery - ASP.NET Core MVC使用 jQuery - ASP.NET Core MVC 通过单击按钮获取表格行的值
【发布时间】:2020-11-29 16:10:32
【问题描述】:

我的视野中有一张桌子。我想通过单击按钮从一行中获取文本。到目前为止,我没有任何成功。我取得的最大进展是得到响应“[object object]”和“Extras 1”。我的模型中有一个名为“Extras”的值,我不知道“1”是从哪里来的。 我见过其他人使用隐藏字段来获取值,但仍然没有运气。

我的目标是使用 jQuery 通过单击按钮从行中获取文本。感谢您的帮助!

我的观点:

<table>
    <thead>
        <tr>
            <td>Select</td>
            <td>
                @Html.DisplayNameFor(model => model.Extras)
            </td>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    <button class="btn btn-success" id="btnSelect">
                        @Html.HiddenFor(modelItem => item.Id)
                        Select
                    </button>
                </td>
                <td id="tdExtras">
                    @Html.DisplayFor(modelItem => item.Extras)
                    @Html.HiddenFor(modelItem => item.Extras);
                </td>
            </tr>
        }
    </tbody>
</table>

在我的 jQuery 中,我尝试使用 .val() 和 .text() 获取值 - 以“Extras”为目标:

$('#Extras').val();

据我了解,Extras 是 ID。在 Chrome 开发工具中,html 看起来像:

<button>
    <input id="#" value="the text that I want to select" />
</button>

我还尝试为按钮内的隐藏字段设置类和 ID。所有的值都在那里,但我无法访问它们。请帮忙。

【问题讨论】:

    标签: jquery asp.net-core model-view-controller asp.net-core-mvc tag-helpers


    【解决方案1】:

    您需要在这里使用class而不是id,然后在单击按钮时获取最接近的tr,然后使用jquery的.find()方法查找输入值。

    演示代码

    //on click of button
    $(document).on("click", ".btn", function() {
      //get closest tr then find .tdExtras > input 
      console.log($(this).closest('tr').find('.tdExtras  input').val());
      //or by class 
     console.log("By class -- "+$(this).closest('tr').find('.tdExtras  input.extras').val());
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
      <thead>
        <tr>
          <td>Select</td>
          <td>
            Abcd
          </td>
        </tr>
      </thead>
      <tbody>
    
    
        <tr>
          <td>
            <button class="btn btn-success" id="btnSelect">  Select </button>
          </td>
          <!--use class instead of id-->
          <td class="tdExtras">
    
            <input type="text" class="extras" value="something">
          </td>
        </tr>
        <tr>
          <td>
            <button class="btn btn-success" id="btnSelect">   Select</button>
          </td>
          <td class="tdExtras">
            <input type="text" class="extras" value="something1">
          </td>
        </tr>
    
      </tbody>
    </table>

    【讨论】:

    • 感谢您的回复。我必须做一些细微的修改才能让它工作,但总的来说,你的代码让我走上了正确的轨道。谢谢!
    猜你喜欢
    • 2021-05-01
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多