【问题标题】:Unique name for Add More input添加更多输入的唯一名称
【发布时间】:2019-12-24 09:24:20
【问题描述】:

我正在尝试创建一个添加更多按钮,它将创建一个新的输入字段。但是,我想为它设置一个唯一的名称。

我试图寻找答案,but this does not answer my question

所以,基本上我尝试让我的名称字段独一无二的是使用 php 方法rand()。这个概念是 - 当点击添加更多按钮时,它会在rand()给我的号码上附加一个名称。

但是,发生的情况是它采用rand() 生成的值并将其应用于生成的所有输入的所有名称。

这是我的代码和我尝试过的:

HTML:

<div class="field_wrapper">
    <div>
        <input type="text" name="field_name[<?php echo rand(); ?>]" value=""/>
        <a href="javascript:void(0);" class="add_button" title="Add field">Add More</a>
    </div>
</div>

JQUERY / JAVASCRIPT:

<script type="text/javascript">
$(document).ready(function(){
    var maxField = 100; //Input fields increment limitation
    var addButton = $('.add_button'); //Add button selector
    var wrapper = $('.field_wrapper'); //Input field wrapper
    var fieldHTML = '<div><input type="text" name="field_name[<?php echo rand(); ?>]" value=""/><a href="javascript:void(0);" class="remove_button">Remove</a></div>'; //New input field html 
    var x = 1; //Initial field counter is 1

    //Once add button is clicked
    $(addButton).click(function(){
        //Check maximum number of input fields
        if(x < maxField){ 
            x++; //Increment field counter
            $(wrapper).append(fieldHTML); //Add field html
        }
    });

    //Once remove button is clicked
    $(wrapper).on('click', '.remove_button', function(e){
        e.preventDefault();
        $(this).parent('div').remove(); //Remove field html
        x--; //Decrement field counter
    });
});
</script>

如您所见,第一个字段按预期生成数字。如果单击“添加更多”,则第二个字段会创建一个唯一编号。但是,如果您再次单击添加更多,第三个字段将复制与第二个字段相同的名称。

我该如何实现我想要的,为什么rand() 没有生成新代码?

另外,rand() 是否向我保证它将是一个唯一的 ID,或者它是否有机会重复相同的数字?

如果它确实重复,那么最好的方法是使它尽可能独特?

【问题讨论】:

  • php 在服务器端 - 所以它在服务器上运行一次...... javascript 有 Math.random()
  • 所以我会像var x = Math.random();一样使用它?
  • 当然,如果可行的话。 x 将是 0...1 之间的十进制数 - 当然,不能保证唯一性 - 但是,考虑到 16 位数字,可能性很小

标签: javascript php jquery


【解决方案1】:

如果您使用 PHP 生成随机名称,它会在服务器上完成一次。然后,您的 JS 代码会复制相同的元素。你需要的是用js生成唯一的名字。

如果可以的话,尽量避免随机,理论上,你可以碰到相同的数字并遇到神秘的错误。

var generateField = function(name)
{
     return '<div><input type="text" name="'+name+'" value=""/><a href="javascript:void(0);" class="remove_button">Remove</a></div>'; //New input field html 
}

//Once add button is clicked
$(addButton).click(function(){
    //Check maximum number of input fields
    if(x < maxField){ 
        x++; //Increment field counter
        $(wrapper).append(generateField('field_name['+x+']' ) ); //Add field html
    }
});

【讨论】:

  • 感谢您的解释,是的,我现在明白为什么 php rand 不起作用了。 PHP 是服务器端,因此需要再次单击。干杯人..
【解决方案2】:

随机并不一定意味着唯一,即使碰撞极为罕见。这个解决方案简单地增加一个totalFieldsCreated 变量以获得下一个唯一数字(直到 JavaScript 可以提供的最大值。)

新字段是动态创建的,而不是使用固定的 HTML 字符串。 (这种技术更灵活。)

$(document).ready(function() {

  // Defines global identifiers
  let
    currentFieldCount = 1,
    totalFieldsCreated = 1;
  const
    maxFieldCount = 100,
    addButton = $('.add_button'),
    wrapper = $('.field_wrapper');

  // Calls `addField` when addButton is clicked
  $(addButton).click(addField);

  // Executes anonymous function when `Remove` is clicked, which removes
  //   the parent div, and decrements (and logs) `currentFieldCount`
  $(wrapper).on('click', '.remove_button', function(e) {
    e.preventDefault();
    $(this).parent('div').remove();
    currentFieldCount--;
    console.log(`currentFieldCount: ${currentFieldCount}`);
  });

  // Defines the `addField` function
  function addField(){

    // Makes sure that `currentFieldCount` and `totalFieldsCreated` 
    //   are not at maximum before proceeding
    if(
      currentFieldCount < maxFieldCount && 
      totalFieldsCreated < Number.MAX_VALUE
    ){

      // Creates an input element, increments `totalFieldsCreated`,
      //   and uses the incremented value in the input's `name` attribute
      const input = document.createElement("input");
      input.type = "text";
      input.name = "field" + ++totalFieldsCreated;
      input.value = "";

      // Creates an anchor element with the `remove_button` class
      const a = document.createElement("a");
      a.href = "javascript:void(0);";
      a.classList.add("remove_button");
      a.title = "remove";
      a.innerHTML = "Remove";
      
      // Adds the new elements to the DOM, and increments `currentFieldCount`
      const div = document.createElement("div");
      div.appendChild(input);
      div.appendChild(a);
      $(wrapper).append(div);
      currentFieldCount++;

      // Logs the new values of both variables 
      console.log(
        `currentFieldCount: ${currentFieldCount},`,
        `totalFieldsCreated ${totalFieldsCreated}`
      );
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field_wrapper">
  <div>
    <input type="text" name="field1" value="" />
    <a href="javascript:void(0);" class="add_button" title="Add field">Add More</a>
  </div>
</div>

【讨论】:

  • 这个真的很不错,我试过了,效果很好。是的,我同意随机性不等于唯一性。您的解决方案保证唯一的字段名称。
  • 我很高兴它有帮助
  • 这是一个很好的答案,我继续进行了进一步的测试,结果非常好。我尝试添加一个字段,将其删除,然后重新添加,它实际上确实跳过了删除的字段编号增量。干得好,非常感谢猫。
【解决方案3】:

尝试在 js 中使用 Math.random() 而不是在 php 中使用 rand()Math.floor(Math.random()*90000) + 10000 会生成一个五位数的随机数,希望对您有所帮助

$('.rand').attr('name',"fields["+Math.floor(Math.random()*90000) + 10000+"]")

$('.add_button').click(function(e){

$('.field_wrapper').append('<div><input type="text" name=fields['+Math.floor(Math.random()*90000) + 10000+'] value=""/><a href="javascript:void(0);" class="remove_button">Remove</a></div>')

})

$(document).on('click','.remove_button',function(e){

     $(this).parent().remove()

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="field_wrapper">
    <div>
        <input type="text" class="rand" value=""/>
        <a href="javascript:void(0);" class="add_button" title="Add field">Add More</a>
    </div>
</div>

【讨论】:

  • 感谢您的回答,但这仍然与第二个字段中的相同名称重复。只有默认字段和第一个添加更多字段是唯一的,但是当您再次添加更多时(现在总共 3 个字段),您会发现字段 2 和字段 3 具有相同的名称。
  • 这很奇怪,在您的 sn-p 上(在执行检查元素之后)我看到所有名称都是唯一的。但是当我在普通文件上执行此操作时,它显示从第 2 个字段开始,都复制了第 2 个字段的名称。 (添加更多字段都一样)
  • omg 我太粗心了,我将您的代码复制到 index2.php 中,并在 index.php 上对其进行了测试(这解释了为什么它没有向我显示正确的结果)。哈哈,是的,您的代码就像老板一样工作!非常感谢我的朋友!
  • 避免在字段名称中使用 random() 值,这会使您的代码更难测试,并且如果您两次点击相同的随机值,则可能会出现错误。
猜你喜欢
  • 2015-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-04
  • 2019-11-06
  • 2017-03-27
  • 1970-01-01
相关资源
最近更新 更多