0

How to compare two input values when type is number and need get the value from a string? and why type=number can't parse values from php strings?

Error: The specified value "'.$total2.'" cannot be parsed, or is out of range.

I found this code at this amazing answer: Enable submit button if value greater or equal to the specified value

But in this example the input get value from input. For something reason the type=number can't handle correctly when an value stored as string is specified.

There is the code ready to copy and paste:

<?php
$total2 = "50"; 
?>
<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>

      <script type="text/javascript">
$(document).ready(function(){
let $form = $('form');
let $total1 = $('#total1');
let $total2 = $('#total2');
let $submitButton = $(':submit');

$form.on('submit', function(event) {
  let val1 = Number($total1.val());
  let val2 = Number($total2.val());
  if (val1 < val2) { // If condition is NOT met.
    event.preventDefault(); // Default submit from happening.
    return false; // Stop function.
  }
});

$form.on('input', function(event) {
  let val1 = Number($total1.val());
  let val2 = Number($total2.val());
  console.log(val1, val2)
  let isDisabled = val1 < val2; // Will return true or false.
  $submitButton.prop('disabled', isDisabled);
});
});
</script>
<form method="post" action="order.php">
  <label for="total1">First Number</label>
  <input type="number" id="total1" value="0" />
  <br>
  <label for="total2">Second Number</label>
  <input type="number" id="total2" value="'.$total2.'" hidden />
  <br>
  <input type="submit" value="submit" disabled title="Not Relevant">
    </form>  
<?php echo $total2;?>
</body>
</html>

I can print string $total2 echo successfully. How to bypass this?

Any hint is welcome Thanks

1 Answer 1

1

PHP opening/closing tags are missing from the HTML input.

<input type="number" id="total2" value="'.$total2.'" hidden />
// should be
<input type="number" id="total2" value="<?php echo $total2; ?>" hidden />

If you don't use the opening/closing tags, PHP won't know that it should treat the $total2 code as PHP code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.