jquery获取子输入元素的html

时间:2017-05-22 06:40:07

标签: jquery

我试图将html作为输入组中第一个输入的变量,当一个" addInput"点击链接:



$(".addInput").click(function() {
  var input = $(this).closest(".input-group").children().first().html();
  alert(input);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label for="phone">Phone</label>
  <div class="input-group">
    <input type="tel" class="form-control" id="phone" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="Format: 555-555-5555" name="phone" value="419-555-1212" disabled required>
    <div class="input-group-addon"><a href="#" class="addInput"><span class="fa fa-plus"></span></a></div>
    <div class="input-group-addon"><a href="#" class="deleteInput"><span class="fa fa-minus"></span></a></div>
  </div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

需要在运行时获取元素的HTML有点奇怪。从代码的上下文来看,似乎您在单击.addInput时尝试添加其他输入?如果是,请使用clone(),然后您可以insertAfter()将新输入直接放在原始文件之后:

&#13;
&#13;
$(".addInput").click(function() {
  var original = $(this).closest(".input-group").find('input:first');
  original.clone().insertAfter(original);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label for="phone">Phone</label>
  <div class="input-group">
    <input type="tel" class="form-control phone" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="Format: 555-555-5555" name="phone" value="419-555-1212" disabled required>
    <div class="input-group-addon"><a href="#" class="addInput"><span class="fa fa-plus">+</span></a></div>
    <div class="input-group-addon"><a href="#" class="deleteInput"><span class="fa fa-minus">-</span></a></div>
  </div>
</div>
&#13;
&#13;
&#13;

但有两点需要注意。首先,我删除了要克隆的元素上的id="phone"。如果你不这样做,你最终会遇到多个因id而无效的元素。您可以改为使用class

其次,如果要清除克隆的值,请使用val('')

答案 1 :(得分:0)

只需在输入元素中添加一个id并获取该值

即可
set.seed(24)
tmp_dt <- as.data.frame(matrix(sample(c('Case', 'Student', 'OF', 'week'),
          5*6, replace = TRUE), 5, 6), stringsAsFactors=FALSE)

JS

<div class="form-group">
<label for="phone">Phone</label>
<div class="input-group">
    <input id="your-id-here" type="tel" class="form-control" id="phone" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="Format: 555-555-5555" name="phone" value="419-555-1212" disabled required>
    <div class="input-group-addon"><a href="#" class="addInput"><span class="fa fa-plus"></span></a></div>
    <div class="input-group-addon"><a href="#" class="deleteInput"><span class="fa fa-minus"></span></a></div>
</div>