如何计算动态添加的输入

How to count dynamically added inputs?

本文关键字:动态 添加 输入 计算 何计算      更新时间:2023-09-26

我有一个简单的表单,其中有两个文本框:一个用于人名,另一个用于姓。在页面上,你可以点击,它会在下面添加两个文本框,同样是"姓名"answers"姓氏"。所以基本上你可以添加任意多对你想要的名字和姓氏

我如何计算输入的("姓名"answers"姓氏")对/行数?

您可以在这里看到演示:http://poostudios.com/jstest2.html

代码如下:

<html>
<head>
<script type="text/javascript" src="nutrition/jquery-3.1.1.js"></script>
<style type="text/css">
        div{
        padding:8px;
        }
</style>enter code here
</head>
<body>
<form action="results.php" method="get">

<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
var newTextBoxDiv = $(document.createElement('div'))
 .attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Name : </label>' +
  '<input type="text" name="textbox' + counter +
  '" id="textbox' + counter + '" value="" ><label> Surname : </label>' +
  '<input type="text" name="textbox' + counter +
  '" id="textbox' + counter + '" value="" >');

newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
counter--;
$("#TextBoxDiv" + counter).remove();
});

});
</script>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Name : </label><input type='textbox' id='textbox1' >
<label>Surname : </label> <input type='textbox' id='textbox2' >
</div>
</div>
<input type='button' value='Add' id='addButton'>
<input type='button' value='Remove' id='removeButton'>
<input type="submit" value="Go">
</form>

</body>
</html>

有很多方法可以做到这一点。@Tibrogargan和我在你的问题上发表了各种各样的评论,这些评论将在任何给定的时间返回元素的数量。

然而,每次你想检查计数时,你都需要调用这些方法来获得一个"实时"计数—因此,如果你只打算检查一次输入的数量,例如,当表单提交时,你所需要做的就是,在提交处理程序中,检查计数或将计数存储在一个变量中:

$('form').on('submit',function(e){
  e.preventDefault();
  // store the current count in a variable (this will not change if the user adds another input)
  var current_count = $('#TextBoxesGroup input').length / 2;
  // do what you want with the current_count variable
  console.log("The user has submitted the form with " + current_count + " input fields");
});

然而,也许您不打算只计算一次输入字段的数量。也许你正在监控用户的行为。在这种情况下,您可以定义一个函数,使事情变得不那么冗长。

不使用递增/递减的计数器,只需按以下方式定义counter函数:

function counter(){
    return $('#TextBoxesGroup input').length / 2;
    /* 
      This could also be: 
        return document.getElementById('TextBoxesGroup').getElementsByTagName('input').length / 2;
    */
}

现在,当您需要检查有多少个输入对时,只需调用counter(),就会返回值。那么,让我们想象一下,当用户点击某个东西时,你正在检查输入的数量—您的代码可能看起来像这样:

$('body').on('click', 'input[type=button]', function(){

  // conditionally pass the current count straight to a function which uses the data
  if ( counter() > 0 ) processMyData( counter() );
  // or, if you process the data here, then pass it on to another function
  // store the current count
  var current_count = counter();
  // do nothing if there are no input fields
  if ( current_count < 1 ) return;
  // do what you want with the count now that you have it
  myAnalytics.inputs.save( current_count );
  // do something else with it
  processMyData( current_count );      
  // etc.
});

由于您已经使用jquery,这就是您将如何获得长度。除以2,因为每个人都有一组名字和用户名。

<script>
    var len = $('#TextBoxesGroup').find('input').length / 2;
    // Do whatever you wanted to do with the len
</script>

这是活塞样品

首先,在你的代码中,id不是唯一的,所以我修改了一点,只是看到下面的演示(我使用append()函数为你的标记创建)。

其次,因为你使用了一个计数器变量,只是用它除以2 (counter / 2)来计算配对的数量。

var counter = 2;
$("#addButton").click(function() {
    $('<div>', {
    	id : 'TextBoxDiv' + counter
    }).append(
    	$('<label>', {
            text: 'Name : '
        }),
        $('<input>', {
            type: 'text',
            name: 'textbox' + (++counter), // increment counter for name
            id: 'textbox' + counter,
            value: ''
        }),
        $('<label>', {
            text: 'Surname : '
        }),
        $('<input>', {
            type: 'text',
            name: 'textbox' + (++counter), // increment counter for surname
            id: 'textbox' + counter,
            value: ''
        })
    ).appendTo('#TextBoxesGroup');
    
    // just divide the counter by 2 to get the pairs
    console.log('input text pairs: ' + counter/2);
});
$("#removeButton").click(function() {
    // if counter === 2 (initial) then remove nothing
    if (counter === 2) {
    	return false;
    }
    // decrement counter by 2
    // and remove the textbox container
    counter-=2;
    $("#TextBoxDiv" + counter).remove();
    console.log('input text pairs: ' + counter/2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="results.php" method="get">
    <div id='TextBoxesGroup'>
        <div id="TextBoxDiv1">
            <label>Name : </label>
            <input type='textbox' id='textbox1'>
            <label>Surname : </label>
            <input type='textbox' id='textbox2'>
        </div>
    </div>
    <input type='button' value='Add' id='addButton'>
    <input type='button' value='Remove' id='removeButton'>
    <input type="submit" value="Go">
</form>

$("#textbox1")。Length将为您提供name文本字段出现的次数。