简体   繁体   中英

HTML Form Number Type Unique User Input with Javascript and PHP

This question is a follow up to what I previously asked ( HTML Form Number Type Unique User Input ) but now I'm making the form more dynamic.

The following form asks users to list there 3 favorite genres of music:

<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>

From there, I am using the following code to make sure that they only use numbers 1,2, and 3 and a foreach loop to list what they have checked but how can I make sure they do not use the same number twice?

<body>
 The genre(s) you selected are: <br />
 <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>
</body>

This was the old javascript code from the previous question but now the id="" is generated by PHP above:

 <script type="text/javascript">
    function item() {
        cake = Number(document.getElementById('cake').value);
        twizlers = Number(document.getElementById('twizlers').value);
        taffy = Number(document.getElementById('taffy').value);
        if (cake == twizlers) {
           alert("Some alert cake or twizlers");
        return false;
    } else if (twizlers == taffy) {
        alert("Some alert taffy or twizlers");
        return false;
    } else if (taffy == cake) {
        alert("Some alert taffy or cake");
        return false;
    } else {
        return true;
    }
  }
 </script>

How can this be done now? Does it have to be in a foreach loop? Any suggestions will be appreciated.

Unless they hack the form or build their own POST submission, they can't "use" the same checkbox twice. But you can easily check for duplicate values:

$counts = array_count_values(array_values($_POST['genre']));
foreach($counts as $form_value => $cnt) { 
    if ($cnt > 1) { 
        echo "$form_value was entered more than once";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM