I am trying to write a function that will validate that all entries within the commas are numberic and display "?" if they are not. for example: user enters 2,3,5b,c7 the output that I am getting is BCE? instead of BC?? This is the decode function that I am trying to validate in:
function fnDecode() {
var msg = $("textin").value;
if(msg === "") {
$("textin_span").innerHTML = "* Please enter a value to decode
*";
$("textin").focus();
return;
} else {
$("textin_span").innerHTML = "";
}
var nums = msg.split(","); //split method separates by delimiter
var outstr = ""; //out string
for (var i=0; i<nums.length; i++) {
var n2 = parseInt(nums[i]);
if (isNaN(n2)) { //if isNaN true, print ?
outstr += "?";
} else if (isNallN(nums[i])) { //THIS IS WHERE THE FN GOES
outstr += "?";
} else if (n2 === 0) {
outstr += " ";
} else if (n2 < 1 || n2 >26) {
outstr += "?";
}else {
outstr += String.fromCharCode(n2+64);
}
}
$("textout").value = outstr;
}
function isNallN(s) {
}
I corrected your fnDecode function.
You don't need multiple if to check for isNaN, !isNaN('5') will work as well as !isNaN(5). Check this Javascript Equality Table for more information.
Here, I adapted the function for it to work with a String given in
parameter and to return the wanted String.
function fnDecode(msg) {
var nums = msg.split(",");
var outstr = "";
for (num of nums) {
if (isNaN(num)) outstr += "?"; //isNaN works on "5" and 5
else if (+num === 0) outstr += " "; //We use +num to parse the String to an int
else if (+num < 1 || +num > 26) outstr += "?";
else outstr += String.fromCharCode(+num + 64);
}
return outstr;
}
var test = '1,2,3,4,5f,6r';
console.log(fnDecode(test));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is a shorter ES6 version :
function fnDecode(msg) {
return msg.split(',').map( num => isNaN(num) || (+num < 1 || +num > 26) ? '?' : +num == 0 ? ' ' : String.fromCharCode(+num + 64)).join('');
}
var test = '1,2,3,4,5f,6r';
console.log(fnDecode(test));
Related
My code is not reporting any errors no matter what I do. This is for a indexed array and I was to get an error when I prompt user to enter the list number they want to delete. It should give me an error if its not in the index or not a integer.
function deleteTask(){
'use strict';
//Prompt user
var input = prompt("what task do you want to delete?");
var delMessage = ' ';
try {
//Convert to integer
var delTask = parseInt(input);
//Validates that user input was number and is range of to do list
if ((typeof delTask == 'number') && (delTask <= tasks.length)){
if (delTask > 1){
//removes element from array
var oneDown = parseInt(delTask - 1);
tasks.splice(oneDown, 1);
}else{
tasks.splice(0,1);
}
delMessage = '<h2>To-Do</h2><ol>';
for (var i = 0, count = tasks.length; i < count; i++) {
delMessage += '<li>' + tasks[i] + '</li>';
}
delMessage += '</ol>';
output.innerHTML = delMessage;
}
//Return false to prevent submission:
return false;
}catch(ex){
console.log(ex.message);
}
}
simple, add the below code to beginning of try block
if((input -parseInt(input ))!=0) throw new Error('not integer');
it should do the trick.
I changed your function, please see if it is what you want:
var tasks = [1,2,3,4,5,6,7,8,9,10];
function deleteTask(){
'use strict';
//Prompt user
var input = prompt("what task do you want to delete?");
var delMessage = ' ';
//Convert to integer
var delTask = parseInt(input);
//Validates that user input was number and is range of to do list
if ((typeof delTask == 'number') && (delTask <= tasks.length)){
if (delTask > 1){
//removes element from array
var oneDown = parseInt(delTask - 1);
tasks.splice(oneDown, 1);
}else if (delTask == 0){
tasks.splice(0,1);
}
delMessage = '<h2>To-Do</h2><ol>';
for (var i = 0, count = tasks.length; i < count; i++) {
delMessage += '<li>' + tasks[i] + '</li>';
}
delMessage += '</ol>';
document.getElementById('output').innerHTML = delMessage;
} else {
throw "The value is not number or not index of array! Try again!";
}
//Return false to prevent submission:
return false;
}
try {
deleteTask();
} catch (e) {
console.log(e);
}
I'm trying to find the keycodes (if that's even what I need) and to change the character to the incremented keycode (this is just for a coding challenge) and it's not working
function LetterChanges(str) {
var newString = "";
var keyCode;
for(var i = 0; i < str.length; ++i)
{
keyCode = str.charCodeAt(i);
console.log(keyCode);
if( keyCode > 57 && keyCode < 122)
{
//add 1 to the keycode
newString += String.fromCharCode(i+1);
//console.log(String.fromCharCode(i+1));
}
else if(keyCode === 90)
{
//if it's a z being examined, add an a
newString += "a";
}
else
//it is a symbol, so just add it to the new string without change
newString += str[i];
}
return newString.toUpperCase();
}
console.log(LetterChanges("Charlie"));
change
newString += String.fromCharCode(i+1);
to
newString += String.fromCharCode(keyCode+1);
Jsfiddle: http://jsfiddle.net/techsin/pnbuae83/1/
function codeIncreaser(input) {
var str='', code=null;
Array.prototype.forEach.call(input, function (e) {
code = e.charCodeAt();
if ((code>64 && code<90) || (code>96 && code<122)) {
code++;
} else if (code == 90) {
code = 65;
} else if (code == 122) {
code = 97;
}
str += String.fromCharCode(code);
});
return str;
}
var text = codeIncreaser('abczABC');
console.log(text);
This accommodates lowercase letters as well.
and if you wanna make code somewhat compact you could do something like this...
function $(i) {
var s='', c;
Array.prototype.forEach.call(i, function (e) {
c = e.charCodeAt();
((c>64&&c<90)||(c>96&&c<122))?c++:((c == 90)?c=65:(c==122&&(c=97)));
s += String.fromCharCode(c);
});
return s;
}
console.log($('abczABC #-#'));
I have never used cookies before, so I am using a peice of code I am very unfamiliar with.
It was working all fine, until I noticed just now that for select boxes, it is not working for any values after the tenth index. (for index 10 and above).
I have looked at the cookie stored on my system, and it appears t be saving them correctly. (I saw select10) ETC stored properly.
When it runs onload of body however, it is not loading in the values properly.
Here is the cookie code I am using:
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
var expDays = 100;
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1) { endstr = document.cookie.length; }
return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) return getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function SetCookie (name, value) {
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
}
// use the following code to call it:
// <body onLoad="cookieForms('open', 'form_1', 'form_2', 'form_n')" onUnLoad="cookieForms('save', 'form_1', 'form_2', 'form_n')">
function cookieForms() {
var mode = cookieForms.arguments[0];
for(f=1; f<cookieForms.arguments.length; f++) {
formName = cookieForms.arguments[f];
if(mode == 'open') {
cookieValue = GetCookie('saved_'+formName);
if(cookieValue != null) {
var cookieArray = cookieValue.split('#cf#');
if(cookieArray.length == document[formName].elements.length) {
for(i=0; i<document[formName].elements.length; i++) {
if(cookieArray[i].substring(0,6) == 'select') { document[formName].elements[i].options.selectedIndex = cookieArray[i].substring(7, cookieArray[i].length-1); }
else if((cookieArray[i] == 'cbtrue') || (cookieArray[i] == 'rbtrue')) { document[formName].elements[i].checked = true; }
else if((cookieArray[i] == 'cbfalse') || (cookieArray[i] == 'rbfalse')) { document[formName].elements[i].checked = false; }
else { document[formName].elements[i].value = (cookieArray[i]) ? cookieArray[i] : ''; }
}
}
}
}
if(mode == 'save') {
cookieValue = '';
for(i=0; i<document[formName].elements.length; i++) {
fieldType = document[formName].elements[i].type;
if(fieldType == 'password') { passValue = ''; }
else if(fieldType == 'checkbox') { passValue = 'cb'+document[formName].elements[i].checked; }
else if(fieldType == 'radio') { passValue = 'rb'+document[formName].elements[i].checked; }
else if(fieldType == 'select-one') { passValue = 'select'+document[formName].elements[i].options.selectedIndex; }
else { passValue = document[formName].elements[i].value; }
cookieValue = cookieValue + passValue + '#cf#';
}
cookieValue = cookieValue.substring(0, cookieValue.length-4); // Remove last delimiter
SetCookie('saved_'+formName, cookieValue, exp);
}
}
}
// End -->
</script>
I beleive the problem lies with the following line, found about 3/4 of the way down the code block above (line 68):
if(cookieArray[i].substring(0,6) == 'select') { document[formName].elements[i].options.selectedIndex = cookieArray[i].substring(7, cookieArray[i].length-1); }
Just for reference, here is the opening body tag I am using:
<body style="text-align:center;" onload="cookieForms('open', 'ramsform', 'decksform', 'hullsform', 'crewform', 'shipwrightform'); Swap(crew0z,'crew0i'); Swap(crew1z,'crew1i'); Swap(crew2z,'crew2i'); Swap(crew3z,'crew3i'); Swap(crew4z,'crew4i'); Swap(crew5z,'crew5i'); Swap(crew6z,'crew6i'); Swap(crew7z,'crew7i'); Swap(crew8z,'crew8i'); Swap(crew9z,'crew9i');" onunload="cookieForms('save', 'ramsform', 'decksform', 'hullsform', 'crewform', 'shipwrightform');">
(Please ignore the swap()'s as they are unrelated)
Page I am working on can be found: http://webhostlet.com/POP.htm
In both the open and save codes, change:
document[formName].elements[i].options.selectedIndex
to:
document[formName].elements[i].selectedIndex
options is an array of all the options, the selectedIndex property belongs to the select element that contains them.
Change:
cookieArray[i].substring(7, cookieArray[i].length-1)
to:
cookieArray[i].substring(6)
You were off by 1 because you forgot that it's 0-based counting. The second argument isn't needed, it defaults to the rest of the string.
The reason it worked for the first 10 menu items is a quirk of substring: if the second argument is lower than the first, it swaps them! So "select5".substring(7, 6) is treated as "select5".substring(6, 7), which gets the last character of the string. But for the longer strings, it was `"select35".substring(7, 7), which is an empty string.
I want to make user control to get number like this:
125.00
125
125.27
125.20
1231545.25
2566.66
I have tried with mask textbox but its length can be anything.
I have used textbox with Javascript that accepts a number
like this:
click here
If a Javascript plugin is available for this let me know,
or any code to accept value in price format.
Restrict user to insert only number and two decimal spaces while entering.
If number is not well formatted then cut and format number after text change.
Like if 125.2 then 125.20 or if 125 then 125.00 or 135156. then 135156
I have search on internet but no plugin or script was found for this.
I have a plugin like numeric.js but it doesn't restrict decimal spaces.
Post if any Javascript available.
I don't want to do validation to check for entered values; I want to accept values with restriction.
Please help me.
You can use Ajax Control Toolkit MaskedEdit control:
MaskedEdit is an ASP.NET AJAX extender that attaches to a TextBox control to restrict the kind of text that can be entered. MaskedEdit applies a "mask" to the input that permits only certain types of characters/text to be entered. The supported data formats are: Number, Date, Time, and DateTime. MaskedEdit uses the culture settings specified in the CultureName property. If none is specified the culture setting will be the same as the page: English (United States).
Sample Code:
<ajaxToolkit:MaskedEditExtender
TargetControlID="TextBox2"
Mask="9,999,999.99"
MessageValidatorTip="true"
OnFocusCssClass="MaskedEditFocus"
OnInvalidCssClass="MaskedEditError"
MaskType="Number"
InputDirection="RightToLeft"
AcceptNegative="Left"
DisplayMoney="Left"
ErrorTooltipEnabled="True"/>
See Working Demo
I also having same problem.This code has solved my problem.This solution is exactly what u want.It's not only foramt yous decimal number but also will eliminate blank spaces. Try this.As in my condition i was allowing user to enter '+' or '-' so i check for this validation also.
<script type="text/javascript">
function checkforvalidation() {
var txtvalue = document.getElementById('<%=txtspherical.ClientID %>').value;
var leftstr = "";
var rightstr = "";
var tempstr = "";
var operator = "";
txtvalue = txtvalue.replace(/\s/g, '');
document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
if (txtvalue.indexOf(".") != -1) {
leftstr = txtvalue.split(".")[0];
rightstr = txtvalue.split(".")[1];
if (leftstr.indexOf("-") == 0 || leftstr.indexOf("+") == 0) {
operator = leftstr.substr(0, 1);
tempstr = leftstr.substr(1, leftstr.length - 1);
leftstr = ltrim(tempstr, '0');
if (leftstr.length == 0) {
leftstr = '0';
}
if (rightstr.indexOf("-") == -1 || rightstr.indexOf("+") == -1) {
rightstr = ltrim(rightstr, '0');
rightstr = chkdecimalpoints(rightstr);
if (operator != null || operator != "") {
txtvalue = operator + leftstr + "." + rightstr;
}
else {
txtvalue = leftstr + "." + rightstr;
}
document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
}
else {
document.getElementById('<%=txtspherical.ClientID %>').value = "";
}
}
else {
tempstr = leftstr.substr(0, leftstr.length);
leftstr = ltrim(tempstr, '0');
if (leftstr.length == 0) {
leftstr = '0';
}
if (rightstr.indexOf("-") == -1 || rightstr.indexOf("+") == -1) {
rightstr = rtrim(rightstr, '0');
rightstr = chkdecimalpoints(rightstr);
txtvalue = leftstr + "." + rightstr;
document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
}
}
}
else if (txtvalue.indexOf("-") == -1 || txtvalue.indexOf("+") == -1) {
txtvalue = ltrim(txtvalue, '0');
if (txtvalue.length == 0) {
txtvalue = '0';
}
if (operator != null || operator != "") {
txtvalue = operator + txtvalue + ".00";
}
// txtvalue = leftstr + "." + rightstr;
document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
}
else if (txtvalue.indexOf("-") == 0 || txtvalue.indexOf("+") == 0) {
operator = txtvalue.substr(0, 1);
tempstr = txtvalue.substr(1, leftstr.length - 1);
txtvalue = alltrim(tempstr, '0');
if (operator != null || operator != "") {
txtvalue = operator + txtvalue + ".00";
document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
}
}
}
function chkdecimalpoints(rightstr) {
if (rightstr.length == 0) {
rightstr = '00';
return rightstr;
}
else if (rightstr.length == 1) {
rightstr = rightstr + '0';
return rightstr;
}
else if (rightstr.length > 2) {
var tempvar = rightstr.substr(2, 1);
if (tempvar >= 5) {
tempvar = parseInt(rightstr.substr(1, 1)) + 1;
tempvar = rightstr.substr(0, 1) + tempvar.toString();
if (tempvar.length > 2) {
tempvar = tempvar.substr(0, 2);
}
return tempvar;
}
else {
tempvar = rightstr.substr(0, 2);
return tempvar;
}
}
else {
return rightstr;
}
}
function ltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
function alltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+$", "g"), "");
}
</script>
HTML Source:
<asp:TextBox ID="txtspherical" runat="server" OnBlur="javascript:checkforvalidation();">
</asp:TextBox>
function validNumber(input){
input=input.replace(/\s+/g," ").replace(/^\s+|\s+$/g,"");
if( input.match(/\d+\.*\d*/i) ){
input=input.match(/(\d+\.*\d*)/i)[1].replace(/\.$/i, "");
if(!input.match(/\./i)) input+=".00";
if(input.match(/\.(\d+)/i)[1].length<2) input+="0";
return input;
}else{
return "0.00";
}
}
OK so this works on all and every browser ive tried it on, but when i try it with internet explorer, its like i dont even have the CheckForm Action there. Any help at all would be awesome. Here is the Script.
function MM_preloadImages() { //v3.0
var d = document;
if (d.images) {
if (!d.MM_p) d.MM_p = new Array();
var i, j = d.MM_p.length,
a = MM_preloadImages.arguments;
for (i = 0; i < a.length; i++)
if (a[i].indexOf("#") != 0) {
d.MM_p[j] = new Image;
d.MM_p[j++].src = a[i];
}
}
}
function checkForm() {
var errors = "";
if (isEmpty("Name")) {
errors += "- Name missing\n";
}
if (isEmpty("Email")) {
errors += "- Email missing\n";
}
if (isEmpty("Phone")) {
errors += "- Phone missing\n";
}
if (isEmpty("Dateneed")) {
errors += "- Date Needed Missing\n";
}
if (isEmpty("ZipCode")) {
errors += "- Zip code mising\n";
}
if (errors.length != 0) {
errors += "\n";
}
var rad_val = document.form1.LanyardStyle.value;
var quantity = parseInt(document.form1.Quantity2.value);
if (isNaN(quantity)) {
quantity = 0;
}
if (rad_val == 'Polyester' && quantity < 100) {
errors += "- Minimum order for Polyester is 100";
}
else if (rad_val == 'AntiMicro' && quantity < 100) {
errors += "- Minimum order for AntiMicro is 100";
}
else if (rad_val == 'Bamboo' && quantity < 100) {
errors += "- Minimum order for Bamboo is 100";
}
else if (rad_val == 'PET' && quantity < 100) {
errors += "- Minimum order for PET is 100";
}
else if (rad_val == 'Reflective' && quantity < 100) {
errors += "- Minimum order for Reflective is 100";
}
else if (rad_val == 'Dyesub' && quantity < 200) {
errors += "- Minimum order for Dyesub is 200";
}
else if (rad_val == 'Woven' && quantity < 500) {
errors += "- Minimum order for Woven is 500";
}
if (errors.length > 0) {
alert("Information missing or invalid:\n\n" + errors);
return false;
}
return true;
}
function getText(id) {
return document.getElementById(id).value.trim();
}
function isEmpty(id) {
if (getText(id).length == 0) {
return true;
}
return false;
}
Try this:
function checkForm() {
var rad = document.form1.LanyardStyle.value,
quantity = parseInt(document.form1.Quantity2.value, 10) || 0,
errors = '',
fields = ['Name', 'Email', 'Phone', 'Dateend', 'ZipCode'],
min = {'Polyester':100, 'AntiMicro':100, 'Bamboo':100, 'PET':100,
'Reflective':100, 'Dyesub':200, 'Woven':500};
for (var i = 0, l = fields.length; i < l; i++) {
if ( isEmpty(fields[i]) ) {
errors += '- ' + fields[i] + ' missing\n';
}
}
if ( quantity < min[rad] ) {
errors += '- Minimum order for ' + rad + ' is ' + min[rad];
}
if ( errors ) {
alert('Information missing or invalid:\n\n' + errors);
return false;
}
return true;
}