I have a form where people enter elements and it autogrows. I wanted to do some math on the data being entered but I’m having problems capaturing the contents of the input field. Here’s the original program I’m working with ( http://jsfiddle.net/doktormolle/WaL84/ ) and I did some reading and believe .eq is the command I need to get the second last element of the auto growing list(I can’t get the last element because its always blank on a auto growing list).
My end goal would be to take all the numbers and return the total or average,etc…
I tried var from = $("#siblings").eq(-1).val(); and -2 but it keeps giving me the value of only the first cell(for example if I enter 1,2,3,4,5 on each cell then I’ll keep getting 1).
If it helps here’s the code:
$(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>
First, the condition in the
if()clause is confusing if not actually wrong.Second, I think you want to get the value from the input element on which the keydown event fired, in other words simply
thisor$(this), inside the handler. There’s no point getting the value from the freshly cloned element because it has been deliberately emptied.Try this :