【问题标题】:Using javascript to prevent duplicate values of dynamically generated input text boxes使用javascript防止动态生成的输入文本框的重复值
【发布时间】:2015-08-20 20:55:25
【问题描述】:

我有一个 3 步(3 页)的表格。第一个页面要求用户检查最多 5 种最喜欢的音乐流派。第二页动态显示选中的流派,然后要求对其进行排名,第三页按顺序显示他们的音乐流派偏好。

我的问题是如何使用javascript来防止第二页上动态生成的输入文本框的重复值?

我发现此代码 (http://jsfiddle.net/zHJSF/) 如果我的文本框字段已设置但文本框字段是动态生成的,则该代码将起作用。调整该代码或执行涉及循环的不同操作可能会更容易。我不确定。

下面是三个页面的代码:

第 1 页

<form id="genre" name="genre" method="post" action="musicsell.php">
  <input type="checkbox" name="genre[]" id="Rap" value="Rap"/>Rap<br />
  <input type="checkbox" name="genre[]" id="HipHop" value="HipHop"/>HipHop<br />
  <input type="checkbox" name="genre[]" id="RnB" value="RnB"/>RnB<br />
  <input type="checkbox" name="genre[]" id="Rock" value="Rock"/>Rock<br />
  <input type="checkbox" name="genre[]" id="Jazz"value="Jazz"/>Jazz<br />

  <p>
    <input type="submit" value="Next">
    <br />
  </p>
</form>

第 2 页

<form id="form1" name="form1" method="post" action="musicresults.php">
<?php
$name = $_POST['genre'];

if(isset($_POST['genre'])) {
foreach ($name as $genre){

?>

<input type="number" required="required" id="<?php echo $genre ?>" name="music[<?php echo $genre ?>]" max="3" min="1" /><?php echo $genre ?><br /> 

<?php
    }
} 
?>

<input type="submit" name="button" id="button" value="Submit" /></form>

第 3 页

<?php
//Get the form results (which has been converted to an associative array) from the $_POST super global
$musicgenres = $_POST['music'];

//Sort the values by rank and keep the key associations.
asort($musicgenres, SORT_NUMERIC );

/*
//Loop over the array in rank order to print out the values.
foreach($musicgenres as $music => $rank)
{
   echo "$music is your $rank choice";
   echo "<br>";
}*/

foreach($musicgenres as $music => $rank)
{
   array_push($musicstring, $music); 
   echo "$music is your $rank choice";
   echo "<br>";
}

$musicstring = implode(", ", $musicgenres);
 echo $musicstring;
?>

【问题讨论】:

  • 你可以在 PHP 中使用array_unique$name = array_unique($_POST['genre']);
  • 根据 W3schools 的说法,array_unique 函数将删除重复项,但不会阻止它们。w3schools.com/php/func_array_unique.asp

标签: javascript php jquery html forms


【解决方案1】:

向输入添加一个类我将使用类test 我正在使用 jquery,所以在添加代码之前添加 jquery 库

$(document).ready(function(){
  $('.test').change(function(){
    var theinput=$(this);
    var value=theinput.val();
    $('.test').each(function(){
      if($(this).val()==value){
        theinput.val('');//to remove the value
        alert('you choose a duplicate');//notify the user why the value removed
      }
    });
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-15
    • 2012-03-29
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多