1

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?

0

2 Answers 2

1

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.

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

1 Comment

Always specify the base argument of parseInt: parseInt(product_price, 10) - otherwise things like leading zeroes cause trouble as they turn the value into an octal number.
1

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

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.