如何从动态创建的表单字段中获取值并将其引用到其他表单函数中?

时间:2012-09-21 23:01:29

标签: forms jquery dynamic-values

这是我到目前为止所拥有的......

<html>
<head>
<title>addForm</title>
<link href="css/addForm.css" rel="stylesheet" type="text/css">
<link href="favicon.ico" rel="icon" type="image/x-icon" />
<script type="text/javascript" src="../lib/jquery/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="../lib/jquery/jquery.autocomplete.min.js"></script>
</head>

<body>
<div>
<form id="addForm" name="addForm" method="post" action="">
...
<div id="container">
<p id="add_field">
<label><a href="#">Add A Class Code</a></label>It may take a moment for your Class Code to appear in the dropdown box.
</p>
</div>
<label>Class Screens E: </label>
<select name="ClassScreenE" id="ClassScreenE" size="5"></select>
<br>
...
</form>
</div>

<script language="javascript" type="text/javascript">
$(function(){
var count = 0;

$('p#add_field').on('click', function(){
        count += 1;

$('#container').append(
'<label>ClassCode: </label>' + '<input type="text" class="autocomplete" name="ClassCode[]" id="ClassCode_' + count + '" size="34" maxlength="3">' + ' Payroll: ' + '<input type="text" name="Payroll[]" id="Payroll_' + count + '" size="10" onKeyPress="return numbersonly(this, event)">' + '<br>')
$(".autocomplete").autocomplete("scripts/findClassCode.php")
});
})

**//Edited in the following bit from Femi
//This seems to work when running 'jQuery("#ClassCode_" + i).val();' in Chrome's Inspector
//Now I need to get a solid value assigned when looping through so I can dynamically call each value to affect the a select box.
var val, i = 1, inp = jQuery("#ClassCode_" + i);
    while(inp.length > 0){
// get the value
val = inp.val();
    ++i;
inp = jQuery("#ClassCode_" + i);
}**

</script>

</body>
</html>

所有这一切都很完美。当我单击链接时,它会生成下一组字段,同时保持其属性,以便自动完成部分可以工作。我现在需要使用表单中每个“ClassCode_'+ count +'”的结果来确定在从MySQL中提取数据的另一个选择框中动态显示的内容。我的问题是将动态值转换为可以在不必提交表单的情况下使用的变量。我花了一天时间在网上搜索这个工作无济于事。有没有人有任何建议?

1 个答案:

答案 0 :(得分:0)

有点迂腐,但是:

var val, i = 0, inp = jQuery("#container").find("input").find("#ClassCode_" + i);
while(inp.length > 0){
   // get the value
   val = inp.val();
   ++i;
   inp = jQuery("#container").find("input").find("#ClassCode_" + i);
}

试试吗?