Reputation: 1316
I have a text input field, which is populated by PHP at page load.
<?php
$product_price = 10000;
?>
<input type='text' name='product_price' value='<?=$product_price?>' >
I have some JavaScript code that checks if the product price is less than 12000. If it is, I will make an alert.
if(product_price <= 12000){
alert("product price must be above 12000");
}
The alert is working fine, but the problem is if I change the value of the input field product_price to 50000, it is still prompting me to that "product price must be above 12000"
Why the JS is not able to take the value I entered into the field? Why the PHP populated value is not changing?
Upvotes: 1
Views: 137
Reputation: 4470
You have to modify the input field so that, whenever the user presses a key, the javascript product_price
variable is updated with the current content of the input field.
<input type="text" name="product_price" onkeypress="product_price = this.value" value="<?=$product_price?>" >
It is better to delegate to a function the handling of the keypress event to validate the user input.
<input type="text" name="product_price" onkeypress="updateProductPrice(this)" value="<?=$product_price?>" >
function updateProductPrice(input) {
product_price = input.value;
}
Upvotes: 1
Reputation: 5268
The contents of the input box is a string. Use parseInt()
to convert it before checking if it's less than or equal to 12000.
if(parseInt(product_price, 10) <= 12000){
alert("product price must be above 12000");
}
This won't update the PHP variable, because there is no binding between the input field and the variable. The JavaScript is run on the client, while the PHP code is run on the server. If you wish to take input from the user, you'll have to either use either a form submit GET/POST or Ajax for updating without reloading the page.
Upvotes: 1