Javascript - 用复选框值填充文本框

时间:2010-07-29 18:07:53

标签: javascript jquery html

在我的网络应用程序中,我设置了一些复选框,在选中时会在其上方填充一个文本框。(如果选中了多个复选框,则它们的值将显示在以逗号分隔的文本框中)。

这些复选框在我的HTML表格中显示为行。

这是我的HTML代码。

<input type="text" id="newContactComment<%=rCount %>" name="newContactComment" size="45">

<input type="checkbox" id="commentText<%=rCount %>" name="commentText" value="<%=c.getComment_text() %>" 
        onclick="javascript:updateTextArea(<%=rCount%>);"> 

相应的JS函数如下:

function updateTextArea(rCount) {
    var allVals = new Array();          
    $("#contactInfo input['commentText' + rCount]:checked").each(function() {
        (allVals).push($(this).val());
    });

    $("#newContactComment" + rCount).val(allVals);
}

上述函数中的 rCount 变量是我表的行#。 使用上面这个,我没有得到预期的行为..
对于前者如果对于我的表的第1行,我检查chkbox 1和2,它正确地填充了这些复选框的值。现在,对于我的2个表,我只检查chkbox 3,它会填充值1,2和3,而不仅仅是我预期的3个。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

您正尝试在引用的字符串中使用rCount变量。试试这个:

$("#contactInfo input['commentText" + rCount + "']:checked")

答案 1 :(得分:0)

最好使用jQuery设置事件处理程序,而不是将其设置为内联。

您想使用onchange事件而不是onclick事件。

如果您向复选框添加复选框的类名(或任何您想要的名称),则以下内容将起作用:

$("input.checkboxes").change(function(){ //when checkbox is ticked or unticked


   var par = $(this).closest("tr")[0];
   var parID = par.id;
   var patt1=/([0-9]+)$/g;
   var rCount = parID.match(patt1); //Gets number off end of id

   var allVals = new Array(); 

   //Get all checkboxes in current row that are checked         
   $(par).find("td input.checkboxes:checked").each(function() {
      allVals.push($(this).val());
   });

   $("#newContactComment" + rCount).val(allVals);

   allVals = null; //empty array as not needed

});

我相信这些或类似的东西会做你想做的事情

相关问题