【问题标题】:JQuery .nextAll (trying to fetch value of next input in DOM) returns with "undefined"JQuery .nextAll(试图获取 DOM 中下一个输入的值)返回“未定义”
【发布时间】:2021-02-15 03:05:19
【问题描述】:

我尝试在使用 jQuery 更改选择字段后获取输入的值。

<div class="box">
<select class="howmuch">
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>

<div class="box">
<p>Some Text</p>
</div>

<div class="box">
<input class="entertext" type="text" placeholder="type something" />
</div>

如果用户更改了选择输入 (class=howmuch),我想获取下一个文本输入的值 (class=entertext)。

<script>
 $(".howmuch").change(function() {
   var fetchtext = $(this).nextAll(".entertext:first").val();
   // also tried .nextall("input:first")
 });
 </script>

总是返回“未定义” 有谁可以帮忙吗?

【问题讨论】:

  • select 没有兄弟姐妹。 nextAll 看兄弟姐妹
  • @Christoph 如果我的回答解决了您的问题,请考虑将其标记为已接受。

标签: html jquery dom


【解决方案1】:

去dom的正确方法是使用parent()nextAll()find()来找到你需要的输入值。

 $(".howmuch").change(function() {
   var fetchtext = $(this).parent().nextAll().find(".entertext:first").val();
   console.log(fetchtext);
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
<select class="howmuch">
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>

<div class="box">
<p>Some Text</p>
</div>

<div class="box">
<input class="entertext" type="text" placeholder="type something" />
</div>

【讨论】:

  • 仅供参考,您的链接和链接名称是混合的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-14
  • 1970-01-01
相关资源
最近更新 更多