Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts
Saturday, January 27, 2024
Real time chat
In a web application, real time chat, i.e. sending/receiving messages without database polling and refreshing the page, can be implemented with socket.io as follows:
Wednesday, December 13, 2023
Chrome hard reload
When you are modifying a JavaScript file like bootstrap-maxlength.js locally, after modification, press shift+reload (or press F12, then long press reload button and select Hard Reload) in Chrome.
Otherwise Chrome will use the previous version in cache and you will scratch your head in confusion why your latest changes are not reflected to the web page.
Sunday, December 3, 2023
PHP string to JavaScript number
I had the following JS/PHP code:
<?php $maxSalePrice = 20000; ?>
const salePrice = $('#product-price').val();
const maxSalePrice = "<?php echo $maxSalePrice; ?>";
if(salePrice > maxSalePrice) {
alert("Sale price can be at most " + maxSalePrice);
}
I tested the code with salePrice of 200, 2000, 20000, the code allowed it and when I used 200000, the code showed the alert message, as it should. However, when I entered 500, it alerted again, but 500 is clearly less than 20000, right?
The problem is that salePrice is a string because it is obtained from a form input and form inputs are strings by default. echo $maxSalePrice also returns a string. Therefore the comparison is not 500 > 20000 but "500" > "20000", which is a lexicographical comparison. Since the first character '5' is larger than '2', "500" is larget than "20000". We should use the JS Number() function to convert strings to numbers:
const salePrice = Number($('#product-price').val());
const maxSalePrice = Number("<?php echo $maxSalePrice; ?>");
if(salePrice > maxSalePrice) {
alert("Sale price can be at most " + maxSalePrice);
}
Subscribe to:
Posts (Atom)