I want to disable the submit if the sum of all select values is bigger than one. And pass if the value < 1.
<?php
$options = array( "0.00","0.05","0.10","0.15","0.20","0.25","0.30","0.35","0.40","0.45","0.50","0.55","0.60","0.65","0.70","0.75","0.80","0.85","0.90","0.95","1" ); // ◄■■ OPTIONS ARE STATIC (ALWAYS THE SAME).
while ( $row_menuid = mysqli_fetch_array( $dat_menuid ) ) // ◄■ DISPLAY
<SELECT>
s.
{ echo "
<select name='corp_resp&{$row_menuid['menuId']}&{$_SESSION['UtilizadorID']}&{$dateTime}&{$toEchosave}'>
"; // ◄■■ CORP_RESP&1,CORP_RESP&2.
foreach ( $options as $opt ) // ◄■■ DISPLAY OPTIONS.
echo "<option value='$opt'>$opt</option>
";
echo "</select>
"; // ◄■■ SELECT END.
}
?>
<br>
<br>
<br>
<br>
<script>
$('select').change(function(){
var sum = 0;
$('select :selected').each(function() {
sum += Number($(this).val());
}
);
$("#sum").html(sum);
if (sum > 1) {
alert('Block!')
}
else {
alert('Give the value !')
}
}
);
</script>
<?php
if ($idfilho == 1)
{
echo "<td align=\"center\" bgcolor='FFFFFF'> <a href='avaliacoes2.php?menuId=".$id."'>Seleccionar</a> </td>";
}
else
{
echo "";
}
echo '</tr>';
}
}
echo"</table>";
echo "<div id='sum'>SUM OF SELECTED OPTIONS</div>";
echo "<br><br><br>";
echo ('<input type="submit" value="Submeter" class="link-style2" />'); ?>
The variable to get the value in each select option value is working but i want to get only in the final sum and compare. If sum > 1 then block the submit if not then you can submit the value. I was trying with alerts but is not the correct way to do.
Thank you.
<script>
var sum = 0;
$('select').change(function(){
$('select :selected').each(function() {
sum += Number($(this).val());
});
$("#sum").html(sum);
}
$('form').on('submit', function(e) {
if(sum > 1) {
e.preventDefault();
}
});
</script>
Here, you need to make the variable sum
global and add an event handler submit
of form
element. In the event handler, you can check the condition if the sum
is greater than 1
or not. If it is greater than 1
, you can prevent the form from being submitted by e.preventDefault()
which stops the event from running.
You can also provide alert box or do something when it is exceeds 1
like this one:
$('form').on('submit', function(e) {
if(sum > 1) {
e.preventDefault();
alert("Blocked!");
}
});
Hope it helps!
Attach a submit event handler to the form in question, then within that handler use code much like you've shown for your change event. If the sum is too big cancel the submit and show a message, otherwise do nothing:
$('#idOfYourFormHere').on('submit', function(e) {
var sum = 0;
$('select :selected').each(function() {
sum += Number(this.value);
});
$("#sum").html(sum);
if (sum > 1) {
e.preventDefault();
alert('You cannot submit unless the sum of your selections is less than or equal to 1.');
} // else do nothing and submit will continue
});
Note that you don't need the change handler unless you want to show the running total, just recalculate the total when the user tries to submit.