我有一个表单,人们输入元素并自动增长。我想对输入的数据进行一些数学计算,但是我在输入字段的内容时遇到了问题。这是我正在使用的原始程序(http://jsfiddle.net/doktormolle/WaL84/),我做了一些阅读并相信.eq是我需要获取自动增长列表的第二个最后一个元素的命令(我无法得到最后一个元素因为它在自动增长列表中总是空白的)。
我的最终目标是获取所有数字并返回总数或平均数等...
我尝试了var from = $("#siblings").eq(-1).val();
和-2但是它一直给我只有第一个单元格的值(例如,如果我在每个单元格上输入1,2,3,4,5那么我将继续获得1 )。
如果有帮助的话,那就是代码:
$(document).ready(function () {
$("input[name='siblings']").on('keydown',
function()
{
//is it the last input?
if(this==$("input[name='siblings']:last",this.form)[0])
{
//insert an empty clone of the current input
$(this).after($(this).clone(true).val(''));
var from = $("#siblings").eq(-1).val();
$("div#total").append("value = " + from + "<br>");
}
});
});
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script type="text/javascript" src="input.js">
</script>
<style type="text/css">
input{display:block}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<p> test </p>
<form>
<div id="inputform" name="inputform">
<input id="siblings" name="siblings">
</div>
</form>
<div id="total">
hello
</div>
</body>
</html>
答案 0 :(得分:1)
首先,如果实际上没有错误,if()
子句中的条件会令人困惑。
其次,我认为您希望从处理程序中触发keydown事件的输入元素中获取值,换句话说只需this
或$(this)
。从新近克隆的元素中获取价值是没有意义的,因为它是故意清空的。
试试这个:
$("input[name='siblings']").on('keyup', function(e) {
if(e.which === 9) return;
var $this = $(this);
if (this == $this.siblings().andSelf().last().get(0)) {
//insert an empty clone of the current input
$this.clone(true).val('').insertAfter(this);
$("div#total").append("value = " + $this.val() + "<br>");
}
});
答案 1 :(得分:0)
您应该使用.last()
:
var from = $('input[name="siblings"]').last().val();
此外,如果您使用类和名称来识别元素会更容易,因为键入.siblings
要简单得多。