I have the following issue:
I have a foreach within a form, within this form I have a number type input that receives various data depending on the result of the query in the DB (normally they give results of 3 to 4 data) I have the code structured as follows :
<form autocomplete="off" action="somewhere.php" method="post" onsubmit="return validator();">
<?php
foreach($data["users"] as $dato){
$pco_user= $dato["pco_user"];
?> <p class="card-text"><strong><?php echo $pco_user; ?></strong></p>
<label>Number:</label>
<input type="number" name="votation[]" class="votation"></input><?php
}
?>
<button type="submit" id="submit3" name="button1" class="btn btn-secondary" value="Save" type="button">Save</button>
</form>
In the form tag I have the following code for onsubmit:
<script>
function validator()
{
const controls=document.querySelectorAll('.votation');
let ids=[];
controls.forEach(function(control)
{
event.preventDefault();
if(ids.includes(control.value))
{
alert('Duplicate values');
return true;
}
ids.push(control.value);
return false;
});
}
</script>
Basically what I am achieving at this moment is that the data that is being inserted is read before redirecting to the action of the form reading if there are equal values, but I cannot get that in the event that there are no equal values, I can redirect without problems, Any solution or can you tell me where I'm wrong?
You can prevent form submission by using event.preventDefault() but if the onsubmit function is assigned inline then the event must be passed to the function as a parameter.
You can use Array.every() to find duplicates as explained in this answer.
<form action="script.php" method="post" onsubmit="validator(event)">
<input type="number" class="votation">
<button type="submit">Save</button>
</form>
<script>
function validator(event) {
// get all control input values
const values = document.querySelectorAll('.votation').map(control => control.value);
// check if there are any duplicates
if (!values.every((element, index, array) => array.indexOf(element) === index) {
alert("Duplicate values found");
// prevent form submission
event.preventDefault();
}
}
</script>