使用javascript来防止动态生成的输入文本框的重复值

时间:2015-08-20 20:55:25

标签: javascript php jquery html forms

我有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;
?>

1 个答案:

答案 0 :(得分:0)

在输入中添加一个类我将使用类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
      }
    });
  });
});
相关问题