从用户输入字段中获取值

时间:2013-08-21 20:31:23

标签: jquery html

我对用户输入字段问题有疑问。

我试图在用户输入内容后从输入字段中获取数据。

我的HTML:

<div>texts here <input type='text'></input></div>

<div>
  <table>
     <tr>
        <td>cell here</td>
        <td>cell here</td>
     </tr>
     <tr>
        <td>another cell here</td>
        <td><input type='text'></input></td>
     </tr>

  </table>
</div>

我的js

var test = $('input).val();
var test2 = $('input).html();

console.log(test)
console.log(test2)

它们都会显示在第一个输入字段中输入的第一个文本,但不会显示在表格中输入的第二个文本。

有人可以帮我解决一下吗?非常感谢!

6 个答案:

答案 0 :(得分:2)

为输入提供唯一ID,您的问题就解决了。

<div>texts here <input id="input_one" type='text'></input></div>
 <div>
  <table>
     <tr>
        <td>cell here</td>
        <td>cell here</td>
     </tr>
     <tr>
        <td>another cell here</td>
        <td><input id="input_two" type='text'></input></td>
     </tr>
  </table>
</div>

然后使用:

var test = $('#input_one').val();
var test2 = $('#input_two').val();

console.log(test)
console.log(test2)

另一个选项,如果您不想使用ID但知道他们在DOM树中的位置,您可以使用:

var test3 = $('input').eq(0).val();
var test4 = $('input').eq(1).val();

演示here

答案 1 :(得分:2)

$('input')是指具有多个元素的jQuery对象,调用val()html()之类的函数将返回仅第一个匹配元素的值。

要获取所有值,您需要遍历对象中的每个元素:

$('input').each(function(){
    console.log($(this).val());
});

答案 2 :(得分:1)

嗯,你抓错了。由于你没有使用id或类或类似内容识别它们,jQuery在两种情况下都将其解释为“第一个输入”。

var test  = $('input').val();
var test2 = $('table input').val(); // Grabs the value of the
                                    // input inside the table

console.log(test);
console.log(test2);

答案 3 :(得分:1)

将id添加到输入字段,然后提取.like

<td><input type='text' id='abc'></input></td>

提取物

var test = $('#abc').val();

答案 4 :(得分:0)

你真的应该在输入中添加类或标识符。这会让事情变得更容易。例如:

<input type='text' class='name'/>

然后在jQuery中:

$(".name").val();

其次,您可以在不更改HTML的情况下获取单个值:

var test = $("div > input").val();
var test2 = $("table input").val();

您的代码无法正常工作的原因是使用简单的$(“输入”)将获得所有的输入值。所以,$(“input”)。val()返回选择器找到的第一个.val(),这是第一个输入。

答案 5 :(得分:0)

$('input').each(function(){
    var value = $(this).val();
    console.log(value);

});
相关问题