JS or PHP Add Leading Zero to Decimals - php

I have a form that I'm trying to automatically enforce decimals in some of the input fields. Basically I would like for the users to not worry about format, but simply have the fields format themselves onBlur.
Here are a few examples of what I'm hoping to achieve:
1.) If a user enters "0.95" nothing is done, because this is the ultimate format I'm going for in the end.
2.) If a user enters ".95" I would like for the field onBlur to change to the above format "0.95". (likewise if they enter ".9" etc)
I have been scouring around on the internet all night long looking for a solution, so this is my last resort! Any help and feedback I can get would be more than appreciated!
Thank you!

Something like this would do it:
document.getElementById('amount').onblur = function() {
if(this.value && !isNaN(this.value)) {
this.value = parseFloat(this.value).toFixed(2);
} else {
this.value = 0;
}
};
jsFiddle

This is nice and concise:
function blurFormatDecimal (e) {
var val = isFinite(this.value) ? +this.value : 0;
this.value = val.toFixed(2);
}
myInput.onblur = blurFormatDecimal;
Use isFinite() instead of !isNaN() because isNaN("Infinity") returns false, but you certainly don't want to accept "Infinity" as valid input.
http://jsfiddle.net/gilly3/NjeQD/

If you need to do this with PHP try:
$formattedAmount = sprintf("%05.2f",$amount);

Here is the php solution:
$formattedAmount = sprintf("%01.2f",$amount);

Related

How to create input number

How to create an input type number using this format?
Example :
when I start writing this number 1000, it should be generated to 1'000.
Example 2: 10000 to 10'000
I think this is it.
$(document).ready(function(){
$('#num').keyup(function(){
var numbers = $(this).val().replace("'","");
var newNum = "";
var digitCount = 0;
for(var i = numbers.length-1; i>=0; i--){
if(digitCount==3){
newNum+="'";
digitCount=0;
}
newNum += numbers.charAt(i);
if($.isNumeric(numbers.charAt(i)))
digitCount++;
}
$(this).val(newNum.split("").reverse().join(""));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<input type="text" id="num">
i'm using this plugin to make the number field auto masking. Very easy to use. Try this one. Give feedback if you can't implement it.
Jquery number masking plugin repository
Examaple usage. After download plugin file, add this code into your js section code.
$('selector_element_to_mask').number(true, 0);
Try this It will surly help you:
var num = 1000000;
console.log(formatNumber(num))
function formatNumber (num) {
return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1'")
}
DEMO with textfield
http://jsfiddle.net/65y2bbrm/1/
I think you are looking for input masking posting a similar question though a bit different but I am sure it will point you in the right direction.
javascript or jquery Input text number only and auto masking

How to prevent a "space" from searching MySQL database?

Currently, when someone just hits the space key and hits enter it will go to the next page but not search anything - I want to prevent the search altogether. What is the best way to accomplish this? I don't want to prevent spaces from being used (ie: How do I fix this?) - I just dont want spaces themselves to allow a search.
Wrap your query variable in an empty condition:
if(!empty(trim($_POST['searchterm']))
{
// do search
}
Use JavaScript and trim leading spaces in the submit (onsubmit) event handler:
var searchField = document.getElementById('search'); // or whatever the id of the field is
if(searchField.value.replace(/^\s+/, '').length === 0) {
return false; // or evt.preventDefault().
}
It should be okay to rely on client-side validation here because if the user wants to fool the search engine then they won't mind being brought to a blank page. If there's an actual server-side problem in allowing this, then perform the same check server-side:
if(!isset($_REQUEST['search']) || !trim($_REQUEST['search'])) {
// Don't perform the search
}
In addition to #AlienWebguy answer you can use JavaScript to do client side validation in order to stop the page from even getting to the back end. Its definitely a good practice to do the validation on the client side AND server side.
Live Demo
form.onsubmit = function(){
if(input.value.replace(/^\s/,"").length === 0){
return false;
}
}
Just take the string, trim the initial and final spaces and check the length; if length is 0, don't submit the form.
If you are procecssing it with php on the backend you can just use trim($input), but for a better user experince use javascript. Set a form validator so it won't submit unless there is something other than whitespace.
<form onsubmit="return verify()">
<input id="foo" name="foo" />
<input type="submit" />c
</form>
<script type="text/javascript">
function verify() {
if (document.getElementById("foo").value.match(/[^\s]/) == null) {
alert('only whitespace');
return false;
} else {
alert('found substance');
return true;
}
}
</script>

need a script to split and assign values Jquery

I am trying to separate and reassign values in a variable. What I have is
#&first=1&second=2
can anyone help with a script that will separate and assign this values to another variable so it would be like
var first= val.(first);
var second= val.(second);
I am new to jquery so I am not even sure if I am using the correct syntax.
Thanks
You could do something like this:
var val = "#&first=1&second=2";
var first = gup(val, "first");
var second = gup(val, "second");
function gup(str, name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(str);
if (results == null) return "";
else return results[1];
}
Checkout the example on jsfiddle: http://jsfiddle.net/WxnJq/
Here's the one that breaks down the GET variables in to key/value pairs, which I believe is what you're after: http://snipplr.com/view/12208/javascript-url-parser/
Also, you can take a look at parseURI, a javascript function that can dissect a URL with GET parameters and grab sections.
Sorry for being quick to post, I thought I found the right function the first time.
JQuery has no builtin way of dealing with querystrings, so I use a plugin for this. You can get it here, works great.

how to avoid enduser from giving urls in textarea jquery

I want to avoid user from submitting website URLs in text-area using (JQuery) client side validation. I am using Validation plug-in.
Example:
http://www.example.com
I need to validate when user types http:// or www in text-area
You could use a custom function with a matching regex like this:
$.validator.addMethod('no_url', function validatePositionNummer(value){
var re = /^[a-zA-Z0-9\-\.]+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU)$/;
var trimmed = trim(value);
if( trimmed == ''){
return true;
}
return trimmed.match(re);
},"No URLs allowed!");
Then you just add your new custom validation method to the element:
$("#your_form").validate({
textarea: no_url
});
You would have to fine-tune the regex ofcourse.
URLs or Links? There is a difference.
However, in either case, don't forget to check on the backend too. You can't trust client side validation. It should only be used to make the user's life easier.
#BernardMarx Thanks for the solution.
Here i used extra regex to validate protocols according to my requirement. Now i need to validate at the end. suggestion please..
For Example:
http://www.example.com/index.php
http://www.example.php/home/
$.validator.addMethod('no_url', function validatePositionNummer(value){
var re = /^[a-zA-Z0-9\-\.\:\\]+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU)$/;
var re1 = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
var trimmed = $.trim(value);
if( trimmed == '' ){
return true;
}
if( trimmed.match(re) == null && re1.test(trimmed) == false){
return true;
}
},"No URLs allowed!");

Compare array of words to a textarea input with javascript

I have a textarea inside a form.
Before the form is submitted, the textarea is validated and checked so it is not empty, not over 2000 characters, not contain forbidden characters etc...
I am working on the last part of the validation, which would need the textarea to be compared to an array of "bad words".
This to help me maintain and keep a good "language" on my site.
I am not very good on js, so does anybody know of a way to compare each word of the textarea to the array of bad words?
Also, would this slow down the validation much? (the array contains at most 100 words).
Thanks
If you wanted to check for the presence of "expletive1" and "expletive2" you'd do the following:
my_textarea = document.getElementById('textarea_id');
if (/\b(?=\w)(expletive1|expletive2)\b(?!\w)/i.test(my_textarea.value)) {
// we found bad words! do something
} else {
// no bad words found, carry on, nothing to see here
}
And you'd just add more words to the list in the same manner (expletive1|expletive2|expletive3|expletive4)
Keep in mind that to keep the words out of your app entirely you'll also need to do server-side filtering.
var bad_words = ['stupid', 'dang']; // watered down
for (var i = 0; i <= bad_words.length; i++) {
if (document.getElementById('my_textarea').value.match(bad_words[i])) {
// has bad word!
}
}
This will keep your code a bit neater, because you don't have to have 100 words in one regex match.
This code replaces bad words with *****
// creating regex
var words = ['bad', 'words'];
var wordsStr = "";
for(var i=0; i<words.length; i++) {
wordsStr += words[i];
if (i < words.length -1) {
wordsStr += "|";
}
}
// wordsStr is "bad|words"
var regex = new RegExp(wordsStr, "gi"); // g: replace all; i:insensitive
// replacing
var text = "I cant say bad words!";
text = text.replace(regex, "****");
// text is "I cant say **** ****!"
See in jsfiddle
var bad_words = new Array('word1', 'word2');
var user_words = document.getElementById('textarea').split(/\W+/);
for( var i in bad_words)
{
if( user_words.indexOf( bad_words[i] ) != -1 )
{
alert( 'The textarea has bad word!');
break;
}
}
You can downvote me if you want, but maybe just don't make the clbuttic mistake of trying to filter in the first place :D

Categories