Round the textbox value javascript - javascript

I have a radtextbox with double type mode. And i have set round as 1. So it is giving the result as
20.6 => 20.5
20.7 => 20.5
20.9 => 21.0
But all i need is like this (few samples)
20.6 => 21.0
20.5 => 20.5
20.4 => 20.0
20.29 => 20.0
20.53 => 20.5
20.59 => 21
I tried to fix this by restricting the more than one decimal value. but the code is not working properly.
Code:
<script type="text/javascript">
function GetIndex(sender, args) {
var textbox = $find('<%= CPDPointsTextBox.ClientID %>');
var val = textbox.get_value();
var dsds = val.toString();
if (dsds.indexOf(".") > -1) {
if (dsds.length - (dsds.indexOf(".") + 1) > 1) {
alert(dsds.length - (dsds.indexOf(".") + 1));
args.set_cancel(true);
}
else
return true;
}
else {
if (parseInt(dsds) > 0) {
return true;
}
else
args.set_cancel(true);
}
}
<telerik:RadNumericTextBox ID="CPDPointsTextBox" Width="39px" runat="server" MaxLength="5"
MaxValue="999" MinValue="0">
<NumberFormat DecimalDigits="1" KeepNotRoundedValue="false" />
<ClientEvents OnValueChanged="CPDPointsTextBox_ValueChanged" OnKeyPress="GetIndex" />
</telerik:RadNumericTextBox>

You may use Jquery for this
var num = parseFloat(document.getElementById('textbox').value);
var new_num = Math.round(num).toFixed(2);
try here JsFiddle

I am using the following code. (May be bulkier).
function convertFloatDecimal (num, nDecimal)
{
var s;
if (nDecimal == null)
nDecimal = 1;
if (nDecimal == 1)
{
if (num < 0)
{
num= Math.abs (num);
s = ((Math.round (parseFloat (num) * 10)/10 ) * -1);
}
else
s = (Math.round (parseFloat (num) * 10)/10);
s = s.toString();
if (s.indexOf (".") == -1)
s+= ".0";
}
else if (nDecimal == 2)
{
if (num < 0)
{
num= Math.abs (num);
s = ((Math.round (parseFloat (num) * 100) / 100) * -1);
}
else
s = (Math.round (parseFloat (num) * 100) / 100);
s = s.toString();
if (s.indexOf (".") == -1)
s+= ".00";
if (s.indexOf (".") == s.length-2) // Add leading 0
s+= "0";
}
else if (nDecimal == 0)
{
if (num < 0)
{
num= Math.abs (num);
s = (Math.round (num) * -1);
}
else
s = (Math.round (num));
}
else
{
s = parseInt (s);
}
return s;
}

The following code meets the expectation. Thank you for all your replies.
Code:
function change(lnk, evt) {
var textbox = $find('<%= CPDTextBox.ClientID %>');
var val = lnk.value.toString();
if (val != '') {
if (val.indexOf(".") > -1) {
var values = new Array();
values = val.split(".");
var rouDec = round(parseFloat('.' + values[1]), 1);
if (rouDec > .5) {
val = parseInt(values[0]) + 1;
}
else if (rouDec == .5) {
val = parseInt(values[0]) + .5;
}
}
}
textbox.set_value(val);
}
function round(n, dec) {
n = parseFloat(n);
if (!isNaN(n)) {
if (!dec) var dec = 0;
var factor = Math.pow(10, dec);
return Math.floor(n * factor + ((n * factor * 10) % 10 >= 5 ? 1 : 0)) / factor;
} else {
return n;
}
}

Related

(Codility binary gap error) Problem : Cant convert octal code into expected array

Its works well when converting to string except binary with prefix 0.
My code:
function dec2bin(dec) {
return dec.toString(2);
}
function getRndInteger(min, max) {
return Math.floor(Math.random() \* (max - min + 1)) + min;
}
const min = 1;
const max = 2147483647;
const nilai = dec2bin(getRndInteger(min, max));
function solution(N) {
**const nilaiArr = Array.from(String(N), Number);**
let temporer = 0;
let save = \[\];
for (let i = 0; i \< nilaiArr.length - 1; i++) {
if (nilaiArr\[i\] == 1 && nilaiArr\[i + 1\] == 0) {
for (let j = i + 1; nilaiArr\[j\] == 0; j++) {
temporer++;
if (nilaiArr\[j + 1\] == 1) {
save.push(temporer);
temporer = 0;
} else if (nilaiArr\[j + 1\] == undefined) {
break;
}
}
} else {
continue;
}
}
if (save.length === 0) {
console.log(0);
} else {
save.sort();
save.reverse();
console.log(save\[0\]);
}
}
solution(nilai);
Problem sample : 010000010001 became 1073745921.
Expected output same as origin binary number. I cant find the answer as long as I scroll in this forum lol. I

Why when I am submiting an answer javascript is always displaying false?

I have problem with displaying true/false after submiting an answer to question.
I need to display true when answer is true e.g.( 14+1=15 true), but my code is always displaying false and never displays true.
Hope you will understand my code.
p.s. to display question press answer, in start it doesn't display question.
function myfunc() {
//randomizer + - * /
var symbol;
var s = Math.floor(Math.random() * 5);
if (s === 1) {
symbol = '+';
}
if (s === 2) {
symbol = '-';
}
if (s === 3) {
symbol = '*';
}
if (s === 4) {
symbol = '/';
}
//first num randomizer
var firstnum = Math.floor(Math.random() * 100);
//sec num randomizer
var secnum = Math.floor(Math.random() * 100);
document.getElementById('demo').innerHTML = firstnum + symbol + secnum;
//answer filter
var input = document.getElementById('input').value;
var testanswer;
if (s === 1) {
testanswer = firstnum + secnum;
}
if (s === 2) {
testanswer = firstnum - secnum;
}
if (s === 3) {
testanswer = firstnum * secnum;
}
if (s === 4) {
testanswer = firstnum / secnum;
}
//test answerer
if (testanswer === input) {
document.getElementById('atbilde').innerHTML = 'true';
}
else {
document.getElementById('atbilde').innerHTML = 'false';
}
}
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="application/javascript" src="test.js"></script>
</head>
<body>
<p id="demo"></p>
<input id="input" type="text">
<button id="mybt" type="button" onclick="myfunc()">submit</button><br>
<p id="atbilde"></p>
</body>
</html>
First of all, randomizing * 5 for 4 symbols is incorrect. Also, try to compare the answer to the actual numbers, not to the newly generated one.
var last = null;
myfunc();
function myfunc() {
//randomizer + - * /
var symbol;
var s = Math.floor(Math.random() * 4) + 1;
if (s === 1) {
symbol = '+';
}
if (s === 2) {
symbol = '-';
}
if (s === 3) {
symbol = '*';
}
if (s === 4) {
symbol = '/';
}
//first num randomizer
var firstnum = Math.floor(Math.random() * 10);
//sec num randomizer
var secnum = Math.floor(Math.random() * 10);
document.getElementById('demo').innerHTML = firstnum + symbol + secnum;
//answer filter
var input = document.getElementById('input').value;
var testanswer;
if (s === 1) {
testanswer = firstnum + secnum;
}
if (s === 2) {
testanswer = firstnum - secnum;
}
if (s === 3) {
testanswer = firstnum * secnum;
}
if (s === 4) {
testanswer = firstnum / secnum;
}
if (last != null) {
if (last == input && input != '') {
document.getElementById('atbilde').innerHTML = 'true';
} else {
document.getElementById('atbilde').innerHTML = 'false';
}
}
last = testanswer;
}
<form onsubmit="myfunc(); return false">
<p id="demo"></p>
<input id="input" type="text">
<button id="mybt" type="submit">submit</button><br>
<p id="atbilde"></p>
</form>
Need to separate generating questions from checking answers. I modified your code and added some comments:
HTML
<p id="demo"></p>
<input id="input" type="text">
<button id="mybt" type="button" onclick="checkAnswer()">submit</button><br>
<button type="button" onclick="showQuestion()">Show New Question</button><br>
<p id="atbilde"></p>
JavaScript:
var s, firstnum, secnum;
// first, show an initial question for a start
showQuestion();
// this method is used to show initial question and also to "Show New Question" when that button is pressed
function showQuestion(){
//randomizer + - * /
let symbol;
// changed formula to return 1, 2, 3, or 4. It was also returning 0 and 5 previously.
s = Math.floor(Math.random() * 4) + 1;
if (s === 1) {
symbol = '+';
}
if (s === 2) {
symbol = '-';
}
if (s === 3) {
symbol = '*';
}
if (s === 4) {
symbol = '/';
}
//first num randomizer
firstnum = Math.floor(Math.random() * 100);
//sec num randomizer
secnum = Math.floor(Math.random() * 100);
document.getElementById('demo').innerHTML = firstnum + symbol + secnum;
}
// when the user is ready and clicks submit, we check the answer using s, firstnum, and secnum
function checkAnswer() {
//answer filter
var input = document.getElementById('input').value;
var testanswer;
if (s === 1) {
testanswer = firstnum + secnum;
}
if (s === 2) {
testanswer = firstnum - secnum;
}
if (s === 3) {
testanswer = firstnum * secnum;
}
if (s === 4) {
testanswer = firstnum / secnum;
}
console.log('the answer is supposed to be ', testanswer, ' and the user submitted ', testanswer);
//test answer
// I changed === to == this way you can compare a string "100" to the number 100 and it will be true.
// Because "100" === 100 is false (it checks the type) and "100" == 100 is true (does not check the type.)
if (testanswer == input) {
document.getElementById('atbilde').innerHTML = 'true';
}
else {
document.getElementById('atbilde').innerHTML = 'false';
}
}

JS Calculator not working in wordpress, script worked on old site

This issue has been problematic this week. We're creating a new site as the current one is a bit outdated. The current site has a series of financial calculators that work perfectly.
Upon transferring the scripts and content to the new wordpress site, we get an error which prevents it from working.
The error we get is:
TypeError: document.formc is undefined[Learn More] accounting-calc.js:7:3
recalc_onclick
http://77.104.171.166/~paramo48/grtglobal.com/wp-content/themes/child-theme/js/accounting-calc.js:7:3
onclick
http://77.104.171.166/~paramo48/grtglobal.com/business-financial-calculators/:1:1
The script we use is:
/* <![CDATA[ */
var co = new Object;
function recalc_onclick(ctl) {
if (ctl == '') {
co.pA1B = eeparseFloatTh(document.formc.pA1B.value);
co.pA2B = eeparsePercent(document.formc.pA2B.value);
co.pA3B = eeparseFloat(document.formc.pA3B.value);
calc(co);
document.formc.pA4B.value = eedatefmt(fmtdate5, co.pA4B);
document.formc.pA5B.value = eedatefmt(fmtdate5, co.pA5B);
};
};
var eeisus = 0;
var eetrue = "TRUE";
var eefalse = "FALSE";
var eedec = ".";
var eeth = ",";
var eedecreg = new RegExp("[.]", "g");
var eethreg = new RegExp(",", "g");
var fmtdaynamesshort = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
var fmtdaynameslong = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var fmtmonthnamesshort = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var fmtmonthnameslong = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var fmtstrings = new Array(",", " ", "");
var fmtdate5 = new Array(34, 25, 2);
var fmtdate6 = new Array(34, 25, 0);
function calc(data) {
var cA1B = data.pA1B;
var cA2B = data.pA2B;
var cA3B = data.pA3B;
var cA4B = (((pmt((((cA2B) / (12))), (((cA3B) * (12))), (cA1B), (0), (0))) * (-1)));
var cA5B = (((((cA1B) * (cA2B))) / (12)));
data.pA4B = cA4B;
data.pA5B = cA5B;
};
function myIsNaN(x) {
return (isNaN(x) || (typeof x == 'number' && !isFinite(x)));
};
function mod(n, d) {
return n - d * Math.floor(n / d);
};
function round(n, nd) {
if (isFinite(n) && isFinite(nd)) {
var sign_n = (n < 0) ? -1 : 1;
var abs_n = Math.abs(n);
var factor = Math.pow(10, nd);
return sign_n * Math.round(abs_n * factor) / factor;
} else {
return NaN;
}
};
function eeparseFloat(str) {
str = String(str).replace(eedecreg, ".");
var res = parseFloat(str);
if (isNaN(res)) {
return 0;
} else {
return res;
}
};
function eeparsePercent(str) {
var parts = String(str).split('%');
var tmp = String(parts[0]).replace(eedecreg, ".");
var res = parseFloat(tmp) / 100;
if (isNaN(res)) {
return 0;
} else {
return res;
}
};
function eedisplayFloat(x) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
return String(x).replace(/\./g, eedec);
}
};
function eedisplayScientific(x, nd) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
var str = String(x.toExponential(nd));
return str.replace(/\./g, eedec);
}
};
function eedisplayFloatND(x, nd) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
var res = round(x, nd);
if (nd > 0) {
var str = String(res);
if (str.indexOf('e') != -1) return str;
if (str.indexOf('E') != -1) return str;
var parts = str.split('.');
if (parts.length < 2) {
var decimals = ('00000000000000').substring(0, nd);
return (parts[0]).toString() + eedec + decimals;
} else {
var decimals = ((parts[1]).toString() + '00000000000000').substring(0, nd);
return (parts[0]).toString() + eedec + decimals;
}
} else {
return res;
}
}
};
function eedisplayPercent(x) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
var tmp = (x * 100).toString() + '%';
return tmp.replace(/\./g, eedec);
}
};
function eedisplayPercentND(x, nd) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
return eedisplayFloatND(x * 100, nd) + '%';
}
}
function eeparseFloatTh(str) {
str = String(str).replace(eethreg, "");
str = String(str).replace(eedecreg, ".");
var res = parseFloat(str);
if (isNaN(res)) {
return 0;
} else {
return res;
}
};
function eedisplayFloatNDTh(x, nd) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
var res = round(x, nd);
if (nd > 0) {
var str = String(res);
if (str.indexOf('e') != -1) return str;
if (str.indexOf('E') != -1) return str;
var parts = str.split('.');
var res2 = eeinsertThousand(parts[0].toString());
if (parts.length < 2) {
var decimals = ('00000000000000').substring(0, nd);
return (res2 + eedec + decimals);
} else {
var decimals = ((parts[1]).toString() + '00000000000000').substring(0, nd);
return (res2 + eedec + decimals);
}
} else {
return (eeinsertThousand(res.toString()));
}
}
};
function eedisplayPercentNDTh(x, nd) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
return eedisplayFloatNDTh(x * 100, nd) + '%';
}
}
function eeinsertThousand(whole) {
if (whole == "" || whole.indexOf("e") >= 0) {
return whole;
} else {
var minus_sign = "";
if (whole.charAt(0) == "-") {
minus_sign = "-";
whole = whole.substring(1);
};
var res = "";
var str_length = whole.length - 1;
for (var ii = 0; ii <= str_length; ii++) {
if (ii > 0 && ii % 3 == 0) {
res = eeth + res;
};
res = whole.charAt(str_length - ii) + res;
};
return minus_sign + res;
}
};
function eedatefmt(fmt, x) {
if (!isFinite(x)) return Number.NaN;
var tmp = 0;
var res = "";
var len = fmt.length;
for (var ii = 0; ii < len; ii++) {
if (fmt[ii] > 31) {
res += fmtstrings[fmt[ii] - 32];
} else {
switch (fmt[ii]) {
case 2:
res += eemonth(x);
break;
case 3:
tmp = eemonth(x);
if (tmp < 10) {
res += "0";
};
res += tmp;
break;
case 4:
res += fmtmonthnamesshort[eemonth(x) - 1];
break;
case 5:
res += fmtmonthnameslong[eemonth(x) - 1];
break;
case 6:
res += eeday(x);
break;
case 7:
tmp = eeday(x);
if (tmp < 10) {
res += "0";
};
res += tmp;
break;
case 8:
res += fmtdaynamesshort[weekday(x, 1) - 1];
break;
case 9:
res += fmtdaynameslong[weekday(x, 1) - 1];
break;
case 10:
tmp = year(x) % 100;
if (tmp < 10) {
res += "0";
};
res += tmp;
break;
case 11:
res += year(x);
break;
case 12:
res += hour(x);
break;
case 13:
tmp = hour(x);
if (tmp < 10) {
res += "0";
};
res += tmp;
break;
case 14:
tmp = hour(x) % 12;
if (tmp == 0) {
res += "12";
} else {
res += tmp % 12;
};
break;
case 15:
tmp = hour(x) % 12;
if (tmp == 0) {
res += "12";
} else {
if (tmp < 10) {
res += "0";
};
res += tmp;
};
break;
case 16:
res += minute(x);
break;
case 17:
tmp = minute(x);
if (tmp < 10) {
res += "0";
};
res += tmp;
break;
case 18:
res += second(x);
break;
case 19:
tmp = second(x);
if (tmp < 10) {
res += "0";
};
res += tmp;
break;
case 21:
case 22:
if (hour(x) < 12) {
res += "AM";
} else {
res += "PM";
};
break;
case 23:
res += eedisplayFloat(x);
break;
case 24:
tmp = fmt[++ii];
res += eedisplayFloatND(x, tmp);
break;
case 25:
tmp = fmt[++ii];
res += eedisplayFloatNDTh(x, tmp);
break;
case 26:
res += eedisplayPercent(x);
break;
case 27:
tmp = fmt[++ii];
res += eedisplayPercentND(x, tmp);
break;
case 28:
tmp = fmt[++ii];
res += eedisplayPercentNDTh(x, tmp);
break;
case 29:
tmp = fmt[++ii];
res += eedisplayScientific(x, tmp);
break;
};
};
};
return res;
};
function leap_gregorian(year) {
return ((year % 4) == 0) && (!(((year % 100) == 0) && ((year % 400) != 0)));
}
var GREGORIAN_EPOCH = 1721425;
function gregorian_to_jd(year, month, day) {
return (GREGORIAN_EPOCH - 0) + (365 * (year - 1)) + Math.floor((year - 1) / 4) + (-Math.floor((year - 1) / 100)) + Math.floor((year - 1) / 400) + Math.floor((((367 * month) - 362) / 12) + ((month <= 2) ? 0 : (leap_gregorian(year) ? -1 : -2)) + day);
}
function jd_to_gregorian(jd) {
var wjd, depoch, quadricent, dqc, cent, dcent, quad, dquad, yindex, year, yearday, leapadj;
wjd = Math.floor(jd);
depoch = wjd - GREGORIAN_EPOCH - 1;
quadricent = Math.floor(depoch / 146097);
dqc = mod(depoch, 146097);
cent = Math.floor(dqc / 36524);
dcent = mod(dqc, 36524);
quad = Math.floor(dcent / 1461);
dquad = mod(dcent, 1461);
yindex = Math.floor(dquad / 365);
year = (quadricent * 400) + (cent * 100) + (quad * 4) + yindex;
if (!((cent == 4) || (yindex == 4))) {
year++;
}
yearday = wjd - gregorian_to_jd(year, 1, 1);
leapadj = ((wjd < gregorian_to_jd(year, 3, 1)) ? 0 : (leap_gregorian(year) ? 1 : 2));
var month = Math.floor((((yearday + leapadj) * 12) + 373) / 367);
var day = (wjd - gregorian_to_jd(year, month, 1)) + 1;
return new Array(year, month, day);
}
function eeday(serial_number) {
if (!isFinite(serial_number)) return Number.NaN;
if (serial_number < 1) {
return 0;
}
if (serial_number > 60) serial_number--;
var res = jd_to_gregorian(serial_number + 2415020);
return res[2];
};
function hour(serial_number) {
if (!isFinite(serial_number)) return Number.NaN;
var res = Math.floor((serial_number - Math.floor(serial_number)) * 86400 + 0.5);
return Math.floor(res / 3600);
}
function minute(serial_number) {
if (!isFinite(serial_number)) return Number.NaN;
var res = Math.floor((serial_number - Math.floor(serial_number)) * 86400 + 0.5);
return Math.floor(res / 60) % 60;
};
function eemonth(serial_number) {
if (!isFinite(serial_number)) return Number.NaN;
if (serial_number < 1) {
return 1;
}
if (serial_number > 60) serial_number--;
var res = jd_to_gregorian(serial_number + 2415020);
return res[1];
};
function second(serial_number) {
if (!isFinite(serial_number)) return Number.NaN;
var res = Math.floor((serial_number - Math.floor(serial_number)) * 86400 + 0.5);
return res % 60;
};
function weekday(serial_number, return_type) {
if (!isFinite(return_type) || !isFinite(serial_number)) return Number.NaN;
if (return_type < 1 || return_type > 3) return Number.NaN;
var res = Math.floor(serial_number + 6) % 7;
switch (Math.floor(return_type)) {
case 1:
return res + 1;
case 2:
return (res + 6) % 7 + 1;
case 3:
return (res + 6) % 7;
};
return "hej";
};
function year(serial_number) {
if (!isFinite(serial_number)) return Number.NaN;
if (serial_number < 1) {
return 1900;
}
if (serial_number > 60) serial_number--;
var res = jd_to_gregorian(serial_number + 2415020);
return res[0];
};
function pmt(rate, nper, pv, fv, type) {
if (rate == 0) {
return -pv / nper;
} else {
var pvif = Math.pow(1 + rate, nper);
var fvifa = (Math.pow(1 + rate, nper) - 1) / rate;
var type1 = (type != 0) ? 1 : 0;
return ((-pv * pvif - fv) / ((1 + rate * type1) * fvifa));
}
};
/* ]]> */
and the content is:
<form id="formc" method="post" action="" class="calc normal">
<noscript><p>Your browser does not support Javascript or has Javascript disabled.<br />Our calculators will not work without it.</p><p>If you want to enable Javascript but are unsure of how to do it, visit our website help page</p></noscript>
<p>See how much you can afford to borrow...</p>
<fieldset><legend><strong>Calculator</strong></legend>
<p><label for="pA1B">Amount of loan</label><span>£</span><input name="pA1B" id="pA1B" onblur="this.value=eedisplayFloatNDTh(eeparseFloatTh(this.value),0);recalc_onclick('pA1B')" value="" type="text"></p>
<p><label for="pA2B">Interest rate</label><span>%</span><input name="pA2B" id="pA2B" onblur="this.value=eedisplayPercentND(eeparsePercent(this.value),2);recalc_onclick('pA2B')" value="" type="text"></p>
<p><label for="pA3B">Term in years</label><span> </span><input name="pA3B" id="pA3B" onblur="this.value=eedisplayFloat(eeparseFloat(this.value));recalc_onclick('pA3B')" value="" type="text"></p>
<p class="formresult"><label for="pA4B">Monthly payment</label><span>£</span><input name="pA4B" tabindex="-1" id="pA4B" value="Result" readonly="readonly" type="text"></p>
<p class="formresult"><label for="pA5B">Interest only</label><span>£</span><input name="pA5B" tabindex="-1" id="pA5B" value="Result" readonly="readonly" type="text"></p>
<p><button type="button" name="xl_update_bottom" onclick="recalc_onclick('')">Calculate</button><button type="button" name="xl_reset_bottom" onclick="reset_onclick('')">Reset</button></p>
</fieldset>
<script>
/* <![CDATA[ */
function reset_onclick(x){document.formc.reset();postcode();recalc_onclick('');};function postcode(){};function eequerystring(){var querystring=document.location.search;if(querystring.length>0){variables=(querystring.substring(1)).split("&");var variable;var key;var value;for(var ii=0;ii<variables.length;ii++){variable=variables[ii].split("=");key=unescape(variable[0]);value=unescape(variable[1]);if(document.formc[key]!=null){document.formc[key].value=value;}}}}function initial_update(){postcode('');eequerystring();recalc_onclick('');}
/* ]]> */</script>
</form>
I'm sure it's something simple but I've yet to solve it.
At first I thought formc was a typo but it's the exact same on the original site where it works.
You are missing the name attribute on the form.
console.log(document.formc)
<form id="formc" name="formc">
</form>

Formatting the phone number for multiple asp:TextBox in Javascript

This might be very basic problem. I found the similar solution on Stack Overflow for formatting the phone number and I used it for asp:TextBox control, but I want this code to be work for multiple phone number textbox control rather than passing IDs directly. I have five different phone field and all those textbox are asp:TextBox. I want to call the same code from all those filed. (I am looking this solution in JavaScript only)
Here is my JS code:
/*Start of phone number formating */
var n;
var p;
var p1;
function format_phone() {
p = p1.value
if (p.length == 3) {
pp = p;
d4 = p.indexOf('(')
d5 = p.indexOf(')')
if (d4 == -1) {
pp = "(" + pp;
}
if (d5 == -1) {
pp = pp + ") ";
}
document.getElementById('<%=HomePhone.ClientID%>').value = "";
document.getElementById('<%=HomePhone.ClientID%>').value = pp;
}
if (p.length > 3) {
d1 = p.indexOf('(')
d2 = p.indexOf(')')
if (d2 == -1) {
l30 = p.length;
p30 = p.substring(0, 4);
p30 = p30 + ") "
p31 = p.substring(5, l30);
pp = p30 + p31;
document.getElementById('<%=HomePhone.ClientID%>').value = "";
document.getElementById('<%=HomePhone.ClientID%>').value = pp;
}
}
if (p.length > 7) {
p11 = p.substring(d1 + 1, d2);
if (p11.length > 4) {
p12 = p11;
l12 = p12.length;
l15 = p.length
p13 = p11.substring(0, 4);
p14 = p11.substring(4, l12);
p15 = p.substring(d2 + 1, l15);
document.getElementById('<%=HomePhone.ClientID%>').value = "";
pp = "(" + p13 + ") " + p14 + p15;
document.getElementById('<%=HomePhone.ClientID%>').value = pp;
}
l16 = p.length;
p16 = p.substring(d2 + 2, l16);
l17 = p16.length;
if (l17 > 3 && p16.indexOf('-') == -1) {
p17 = p.substring(d2 + 1, d2 + 5);
p18 = p.substring(d2 + 5, l16);
p19 = p.substring(0, d2 + 1);
pp = p19 + p17 + "-" + p18;
document.getElementById('<%=HomePhone.ClientID%>').value = "";
document.getElementById('<%=HomePhone.ClientID%>').value = pp;
}
}
setTimeout(format_phone, 100)
}
function getIt(m) {
n = m.name;
p1 = m;
format_phone()
}
/* End of phone number formating */
and asp:TextBox as
<asp:TextBox MaxLength="14"
runat="server" ID="HomePhone"
placeholder="(xxx) xxx-xxxx"
onFocus="if(this.value==this.defaultValue)this.value='';" onclick="javascript:getIt(this)"
onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
And I have other similar four textboxes for phone field and I want to use the same formatting logic for all those. What is the best way to use this or any alternative JavaScript code from multiple textbox. Any help would be highly appreciated.
I don't remember where I found this solution but, it might help you out to format the phone fields:
<script type="text/javascript">
//Phone validation
var zChar = new Array(' ', '(', ')', '-', '.');
var maxphonelength = 13;
var phonevalue1;
var phonevalue2;
var cursorposition;
function ParseForNumber1(object) {
phonevalue1 = ParseChar(object.value, zChar);
}
function ParseForNumber2(object) {
phonevalue2 = ParseChar(object.value, zChar);
}
function backspacerUP(object, e) {
if (e) {
e = e
} else {
e = window.event
}
if (e.which) {
var keycode = e.which
} else {
var keycode = e.keyCode
}
ParseForNumber1(object)
if (keycode >= 48) {
ValidatePhone(object)
}
}
function backspacerDOWN(object, e) {
if (e) {
e = e
} else {
e = window.event
}
if (e.which) {
var keycode = e.which
} else {
var keycode = e.keyCode
}
ParseForNumber2(object)
}
function GetCursorPosition() {
var t1 = phonevalue1;
var t2 = phonevalue2;
var bool = false
for (i = 0; i < t1.length; i++) {
if (t1.substring(i, 1) != t2.substring(i, 1)) {
if (!bool) {
cursorposition = i
bool = true
}
}
}
}
function ValidatePhone(object) {
var p = phonevalue1
p = p.replace(/[^\d]*/gi, "")
if (p.length < 3) {
object.value = p
} else if (p.length == 3) {
pp = p;
d4 = p.indexOf('(')
d5 = p.indexOf(')')
if (d4 == -1) {
pp = "(" + pp;
}
if (d5 == -1) {
pp = pp + ")";
}
object.value = pp;
} else if (p.length > 3 && p.length < 7) {
p = "(" + p;
l30 = p.length;
p30 = p.substring(0, 4);
p30 = p30 + ")"
p31 = p.substring(4, l30);
pp = p30 + p31;
object.value = pp;
} else if (p.length >= 7) {
p = "(" + p;
l30 = p.length;
p30 = p.substring(0, 4);
p30 = p30 + ")"
p31 = p.substring(4, l30);
pp = p30 + p31;
l40 = pp.length;
p40 = pp.substring(0, 8);
p40 = p40 + "-"
p41 = pp.substring(8, l40);
ppp = p40 + p41;
object.value = ppp.substring(0, maxphonelength);
}
GetCursorPosition()
if (cursorposition >= 0) {
if (cursorposition == 0) {
cursorposition = 2
} else if (cursorposition <= 2) {
cursorposition = cursorposition + 1
} else if (cursorposition <= 5) {
cursorposition = cursorposition + 2
} else if (cursorposition == 6) {
cursorposition = cursorposition + 2
} else if (cursorposition == 7) {
cursorposition = cursorposition + 4
e1 = object.value.indexOf(')')
e2 = object.value.indexOf('-')
if (e1 > -1 && e2 > -1) {
if (e2 - e1 == 4) {
cursorposition = cursorposition - 1
}
}
} else if (cursorposition < 11) {
cursorposition = cursorposition + 3
} else if (cursorposition == 11) {
cursorposition = cursorposition + 1
} else if (cursorposition >= 12) {
cursorposition = cursorposition
}
var txtRange = object.createTextRange();
txtRange.moveStart("character", cursorposition);
txtRange.moveEnd("character", cursorposition - object.value.length);
txtRange.select();
}
}
function ParseChar(sStr, sChar) {
if (sChar.length == null) {
zChar = new Array(sChar);
}
else zChar = sChar;
for (i = 0; i < zChar.length; i++) {
sNewStr = "";
var iStart = 0;
var iEnd = sStr.indexOf(sChar[i]);
while (iEnd != -1) {
sNewStr += sStr.substring(iStart, iEnd);
iStart = iEnd + 1;
iEnd = sStr.indexOf(sChar[i], iStart);
}
sNewStr += sStr.substring(sStr.lastIndexOf(sChar[i]) + 1, sStr.length);
sStr = sNewStr;
}
return sNewStr;
}
</script>
And call this on your asp:TextBox as
<asp:TextBox MaxLength="14"
runat="server" ID="HomePhone"
placeholder="(xxx) xxx-xxxx"
onkeydown="javascript:backspacerDOWN(this,event);"
onkeyup="javascript:backspacerUP(this,event);" />
And If you want to insert space after ')' you can use the following trick
function markSpace(field) {
if (field.value.includes(")")) {
field.value = field.value.split(')').join(') ');
}
if (field.value.includes(") ")) {
field.value = field.value.replace(/ +/g, ' ');
}
}
and call this as onblur="markSpace(this);" But I personally prefer using JQuery :)

Betfair like Odds increment and decrement

Please help me it is very irritating. Don't know why my logic is failed every time.
I am trying to make Betfair like odds increment in my web project. Betfair have it's own price group which can be found here
LINK: https://api.developer.betfair.com/services/webapps/docs/display/1smk3cen4v3lu3yomq5qye0ni/Betfair+Price+Increments
Here is explanation:
if odds is 1.01 and some body want to increase that odds via html5 number spinner the increment will be 0.01 and if odds is 2 the increment will be 0.02. whole increment list is available in that link.
working example can be found in betfair's betslip.
here is my Javascript:
function getIncremantal(fval) {
var val = parseFloat(fval);
var step;
if (val <= 1.99) {
step = 0.01;
} else if (val > 2 && val < 3) {
step = 0.02;
} else if (val > 3 && val < 4) {
step = 0.05;
} else if (val > 4 && val < 6) {
step = 0.1;
} else if (val > 6 && val < 10) {
step = 0.2;
} else if (val > 10 && val < 19.5) {
step = 0.5;
} else if (val >= 20 && val < 30) {
step = 1;
} else if (val >= 30 && val < 50) {
step = 2;
} else if (val >= 50 && val < 100) {
step = 5;
} else if (val >= 100 && val < 1000) {
step = 10;
} else if (val > 1000) {
step = null;
}
return step;
}
Update: jsFiddle
http://jsfiddle.net/71fs0a67/1/
I tried the following which is not using number stepping, but if you use the buttons it does work. It is an alternate solution, sorry if its not what you are looking for.
HTML:
<input type="number" min="1.01" max="1000" id="num"/>
<button class="increment">+</button>
<button class="decrement">-</button>
Javascript:
$('.increment').on('click', function() {
var elem = $('#num');
var value = parseFloat(elem.val());
var result = +(value + getIncremantal(value)).toFixed(2);
elem.val(result);
});
$('.decrement').on('click', function() {
var elem = $('#num');
var value = parseFloat(elem.val());
var result = +(value - getDecremantal(value)).toFixed(2);
elem.val(result);
});
function getIncremantal(val) {
var step;
if (val < 2) {
step = 0.01;
} else if (val >= 2 && val < 3) {
step = 0.02;
} else if (val >= 3 && val < 4) {
step = 0.05;
} else if (val >= 4 && val < 6) {
step = 0.1;
} else if (val >= 6 && val < 10) {
step = 0.2;
} else if (val >= 10 && val < 20) {
step = 0.5;
} else if (val >= 20 && val < 30) {
step = 1;
} else if (val >= 30 && val < 50) {
step = 2;
} else if (val >= 50 && val < 100) {
step = 5;
} else if (val >= 100 && val < 1000) {
step = 10;
} else if (val > 1000) {
step = null;
}
return step;
}
function getDecremantal(val) {
var step;
if (val <= 2) {
step = 0.01;
} else if (val > 2 && val <= 3) {
step = 0.02;
} else if (val > 3 && val <= 4) {
step = 0.05;
} else if (val > 4 && val <= 6) {
step = 0.1;
} else if (val > 6 && val <= 10) {
step = 0.2;
} else if (val > 10 && val <= 20) {
step = 0.5;
} else if (val > 20 && val <= 30) {
step = 1;
} else if (val > 30 && val <= 50) {
step = 2;
} else if (val > 50 && val <= 100) {
step = 5;
} else if (val > 100 && val <= 1000) {
step = 10;
} else if (val > 1000) {
step = null;
}
return step;
}
http://jsfiddle.net/71fs0a67/7/
With jquery ui spinner, you can do something like this:
$( "#spinner" ).spinner({
min: 1.01,
max: 1000,
step: 0.01,
spin: function( event, ui ) {
event.preventDefault();
event.stopPropagation();
var value = this.value || ui.value;
value = parseFloat(value);
var step;
if ($(event.currentTarget).hasClass('ui-spinner-up')) {
step = getIncremantal(value);
value = +(value + step).toFixed(2);
$( "#spinner" ).spinner('value', value);
} else {
step = getDecremantal(value);
value = +(value - step).toFixed(2);
$( "#spinner" ).spinner('value', value);
}
}
});
http://jsfiddle.net/71fs0a67/9/
Your code will return undefined for whole numbers.
Change all instances of val > number to val >= number
Try this:
function getIncremantal(fval) {
var val = parseFloat(fval);
var step;
if (val < 2) {
step = 0.01;
} else if (val >= 2 && val < 3) {
step = 0.02;
} else if (val >= 3 && val < 4) {
step = 0.05;
} else if (val >= 4 && val < 6) {
step = 0.1;
} else if (val >= 6 && val < 10) {
step = 0.2;
} else if (val >= 10 && val < 20) {
step = 0.5;
} else if (val >= 20 && val < 30) {
step = 1;
} else if (val >= 30 && val < 50) {
step = 2;
} else if (val >= 50 && val < 100) {
step = 5;
} else if (val >= 100 && val < 1000) {
step = 10;
} else if (val > 1000) {
step = null;
}
return step;
}
function getDecremantal(fval) {
var val = parseFloat(fval);
var step;
if (val <= 2) {
step = 0.01;
} else if (val > 2 && val <= 3) {
step = 0.02;
} else if (val > 3 && val <= 4) {
step = 0.05;
} else if (val > 4 && val <= 6) {
step = 0.1;
} else if (val > 6 && val <= 10) {
step = 0.2;
} else if (val > 10 && val <= 20) {
step = 0.5;
} else if (val > 20 && val <= 30) {
step = 1;
} else if (val > 30 && val <= 50) {
step = 2;
} else if (val > 50 && val <= 100) {
step = 5;
} else if (val > 100 && val <= 1000) {
step = 10;
} else if (val > 1000) {
step = null;
}
return step;
}

Categories