【问题标题】:Pass span value to a hidden input将跨度值传递给隐藏的输入
【发布时间】:2021-05-08 21:33:05
【问题描述】:

我的跨度是一个动态值(整数)。我需要将 span 中出现的值传递给我的输入。

这应该可以用 jquery 实现,但我不知道怎么做。

<span class="id-label"></span>
<input type="hidden" id="label" name="label" value="" />
$(document).ready(function() {
  var table = $('#example').DataTable();
  
  $('#example tbody').on('dblclick', 'tr', function() {
    if ($(this).hasClass('selected')) {
      $(this).removeClass('selected');
    } else {
      table.$('tr.selected').removeClass('selected');
      $(this).addClass('selected');
      $('.id-label').text($(this).closest('tr').find('td:first').text());
      $('#classModal').modal('hide');
    }
  });
});

【问题讨论】:

  • 在代码中设置span文本的位置,在input中设置value
  • 你说的看起来很简单,但我看不懂。 span 中显示的值是从表中选择的 id。
  • 您说整数值动态添加到span。在代码中设置跨度文本的完全相同的位置,设置input 中的值。如果您需要帮助,请显示设置 span 值的代码。
  • 感谢您的澄清。为了将来参考,您应该编辑问题以包含代码。在这种情况下,我已经为您完成了。我还在下面添加了一个答案。

标签: html jquery asp.net-mvc


【解决方案1】:

鉴于问题中的代码您正在检索一个值并将其设置为.id-labeltext(),您可以使用相同的值并将其设置为目标输入的val()

$(document).ready(function() {
  var table = $('#example').DataTable();
  
  $('#example tbody').on('dblclick', 'tr', function() {
    let $tr = $(this);

    if ($tr.hasClass('selected')) {
      $tr.removeClass('selected');
    } else {
      table.$('tr.selected').removeClass('selected');
      $tr.addClass('selected');
      $('#classModal').modal('hide');

      let targetValue = $tr.find('td:first').text();
      $('.id-label').text(targetValue);
      $('#label').val(targetValue);
    }
  });
});

请注意,我删除了.closest('tr'),因为this 已经引用了tr

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多