在JS / JQuery中显示javascript输入文本

时间:2018-02-22 03:43:18

标签: javascript jquery html

这是我的HTML代码,

$(".slide").each(function() {
  var a = $(this).find(".input-field"),
    b = $(this).find("a");

  b.click(function() {
    console.log(a.value());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" class="step-form d-flex">
  <div class="slide">
    <h3>Enter your code1</h3>
    <input type="text" class="input-field" placeholder="ZIP CODE">

    <p><a href="#" class="btn-start">Start now!</a></p>
  </div>

  <div class="slide">
    <h3>Enter your code2</h3>
    <input type="text" class="input-field" placeholder="ZIP CODE">

    <p><a href="#" class="btn-start">Start now!</a></p>
  </div>
</form>

我想在点击按钮时在输入上显示输入的文字。

我一直在尝试这段代码。但我总是导致未定义;

3 个答案:

答案 0 :(得分:1)

在jQuery中,您需要使用val()而不是value()API):

$(".slide").each(function() {
  var a = $(this).find(".input-field"),
    b = $(this).find("a");

  b.click(function() {
    console.log(a.val());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" class="step-form d-flex">
  <div class="slide">
    <h3>Enter your code1</h3>
    <input type="text" class="input-field" placeholder="ZIP CODE">

    <p><a href="#" class="btn-start">Start now!</a></p>
  </div>

  <div class="slide">
    <h3>Enter your code2</h3>
    <input type="text" class="input-field" placeholder="ZIP CODE">

    <p><a href="#" class="btn-start">Start now!</a></p>
  </div>
</form>

答案 1 :(得分:0)

您可以尝试:

Enter a value (0 to end): 110
Enter a value (0 to end): 60
Enter a value (0 to end): abc
Invalid input. Type a legit integer.
Enter a value (0 to end): 50
Enter a value (0 to end): 90
Enter a value (0 to end): 40
Enter a value (0 to end): hanbagui
Invalid input. Type a legit integer.
Enter a value (0 to end): 0
Min: 40
Max: 110
Avg: 64.3
$(".btn-start").click(function() {
    console.log($(this).closest('.slide').find('.input-field').val());
  });

答案 2 :(得分:0)

应该 .val()而不是 .value()

$(".slide").each(function() {
  var a = $(this).find(".input-field"),
  b = $(this).find("a");
  b.click(function() {
    console.log(a.val());
  });
});