I would like to use JavaScript to take data entered into a text field and replace the first two digits with a character and at the same time preserve the remaining digits in the string. The input data will always be 6 digits in length and there are 4 different possible character options depending on the first 2 digits of the input data. Here are the four possible options.
00 = A, 01 = M, 31 = B, 71 = F
So for example, if the input data is 001234, the output would need to be A1234. If the input is 719999, the output needs to be F9999.
I appreciate any help you can provide and thank you in advance for your support.
You declare tc_event; I assume this is a value returned by another function or application. But in your function you call TC_event. Please bare in mind that variables in JS are case sensitive. So tc_event is an entirely different variable than TC_event.
In your function you don't assing the returned value of strNewFld to tc_event so even while returned, tc_event will remain the initial value.
var persNr = "711212";
var strSrc = persNr ;
var strLtr = strSrc.substring(0,2);
var strNum = strSrc.substr(2,4);
console.log("This is strLtr: " + strLtr);
console.log("This is strNum: " + strNum);
var strNewFld = "";
var strLtrOut= "";
// In your if statement you use a single =. This means assign.
// To compare allways use ==. This compares.
if (strLtr == "00"){
strLtrOut = "A";
}
if (strLtr == "01"){
strLtrOut = "M";
}
if (strLtr == "31"){
strLtrOut = "B";
}
if (strLtr == "71"){
strLtrOut = "F";
}
strNewFld = strLtrOut + strNum;
// here you could assign value of strNewFld
// to tc_event or directly assiging
// strLtrOut + strNum to tc_event.
tc_event = strLtrOut + strNum
console.log("This is strNewFld: " + strNewFld);
I put it in a Snippet for you to understand what your variables do and how to manipulate it with if statements. A Switch statement should be more suitable. You can ask if needed.
var persNr = "021212"
var strLtr = persNr.substring(0,2);
var strNum = persNr.substr(2,4);
if (strLtr == "01"){
strLtrOut = "A" + strNum ;
}
if (strLtr == "02"){
strLtrOut = "B" + strNum ;
}
console.log("This is strLtr: " + strLtr);
console.log("This is strNum: " + strNum);
console.log("This is strLtrOut: " + strLtrOut);
Related
im just started to learn JavaScript and i´m trying to simplify some code, but couldn´t get a working solution. The working part is this:
switch (v) {
case 0:
if (localStorage.FGAz0) {
localStorage.FGAz0 = Number(localStorage.FGAz0)+1;
} else {
localStorage.FGAz0 = 1;
}
document.getElementById("Ergebnis").innerHTML = "You have " + localStorage.FGAz0+ " Visitor(s).";
break;
case 1:
if (localStorage.FGAz1) {
localStorage.FGAz1 = Number(localStorage.FGAz1)+1;
} else {
localStorage.FGAz1 = 1;
}
document.getElementById("Ergebnis").innerHTML = "You have " + localStorage.FGAz1+ " Visitor(s).";
break;
case 2:
if (localStorage.FGAz2) {
localStorage.FGAz2 = Number(localStorage.FGAz2)+1;
} else {
localStorage.FGAz2 = 1;
}
document.getElementById("Ergebnis").innerHTML = "You have " + localStorage.FGAz2+ " Visitor(s).";
break;
case 3:
if (localStorage.FGAz3) {
localStorage.FGAz3 = Number(localStorage.FGAz3)+1;
} else {
localStorage.FGAz3 = 1;
}
document.getElementById("Ergebnis").innerHTML = "You have " + localStorage.FGAz3+ " Visitor(s).";
break;
case 4:
if (localStorage.FGAz4) {
localStorage.FGAz4 = Number(localStorage.FGAz4)+1;
} else {
localStorage.FGAz4 = 1;
}
document.getElementById("Ergebnis").innerHTML = "You have " + localStorage.FGAz4+ " Visitor(s).";
break;
case 5:
if (localStorage.FGAz5) {
localStorage.FGAz5 = Number(localStorage.FGAz5)+1;
} else {
localStorage.FGAz5 = 1;
}
document.getElementById("Ergebnis").innerHTML = "You have " + localStorage.FGAz5+ " Visitor(s).";
break;
default:
if (localStorage.FahrGastAnzahl) {
localStorage.FahrGastAnzahl = Number(localStorage.FahrGastAnzahl)+1;
} else {
localStorage.FahrGastAnzahl= 1;
}
document.getElementById("Ergebnis").innerHTML = "You have " + localStorage.FahrGastAnzahl+ " Visitor(s).";}
} else {
document.getElementById("Ergebnis").innerHTML = "Sorry, dein Browser unterstützt die Speicherung von lokalen Daten nicht...";
}
and i am trying to short it to the var depending on "v" which only had numbers. At the moment i have this:
if (localStorage.FGAz + "v") {
(localStorage.FGAz + "v") = Number(localStorage.FGAz + "v")+1;
} else {
(localStorage.FGAz + "v") = 1;
document.getElementById("Ergebnis").innerHTML = "You have " + (localStorage.FGAz + "v") + " Visitor(s).";}
Something isn´t right with the adding of the variable "v", but i don´t know what and didn´t found a solution on searching. Hope someone can help me. Please no jquery, i haven´t learned that yet.
Firs of all, make sure you understand the difference between v and "v":
v is a variable name, which can hold any value (string, number, etc), eg:v = 1; v = "1"; v = "xxx";
"v" (mind the brackets) is a string value itself (v = "v", where v is the variable name and "v" is the variable value). Everything inside the brackets (" or ') is a string.
If you wish to cast numerical (integer in this example) value to string, you can use v.toString() or simply append an empty string to the value v + "".
Secondly, please get some knowledge on Property Accessors.
In short: you can access properties of an object in two different ways: using dot notation (localStorage.FGAz1) or brackets notation (localStorage["FGAz1"]).
Appending string value to dot notated property accessor (document.getElementBy + "Id") will firstly evaluate the value of property (document.getElementBy - which evaluates to undefined) and THEN will concatenate it with the string (undefined + "Id" - which results in "undefinedId"). On the other hand, appending string to accessor value inside bracket notation (document["getElementBy" + "Id"]) will firstly evaluate the value of accessor ("getElementBy" + "Id" - which evaluates to "getElementById"), and then access the object's property (document["getElementById"] - which returns the function).
Based on your example:
localStorage.FGAz is not defined, so the localStorage.FGAz + "v" evaluates to undefined + "v" which results in "undefinedv" (Notice the 'v' added to the end of 'undefined'). Sentence if ("undefinedv") always evaluates to true (HERE you can find out why).
In conclusion:
Use brackets notation:
if (localStorage['FGAz' + v.toString()]) {. This will evaluate to if (localStorage['FGAz1']) { for v = 1, if (localStorage['FGAzXXX']) { for v = XXX and so on.
I'm hoping it makes sens to you, if not leave me a question in comments.
I'm looking at the code above and it looks like you're doing some sort of visitor counter. However the localstorage would only work for the one person.
If you're going to be doing vistor counter, you could use ajax to send the information to a database and then check how many people are online.
Simple visit counter:
JSFIDDLE LINK
Code from JSFIDDLE
<div id="visitCount"></div>
if (localStorage.visitCount){
localStorage.visitCount = Number(localStorage.visitCount)+1;
} else {
localStorage.visitCount = 1;
}
document.getElementById("visitCount").innerHTML = "You've been to this page "+ localStorage.visitCount + " time(s)."
Instead of using
localStorage.FGAz + "v"
Use
localStorage["FGAz" + v]
v in "" quotations makes it a string value not variable.
This question already has answers here:
How to convert a string to an integer in JavaScript
(32 answers)
Closed 6 years ago.
here's the code I'm struggling with. I'd like to concat the two inputs together and keep the result as an integer (number in JS's case).
var secsVal = -1;
function valueAssign(i) {
if (secsVal == -1){
document.getElementById("countdown").value = i;
document.getElementById("countdown").innerHTML = (i);
secsVal = i;
}
else {
secsVal = "" + secsVal + i;//concatenating first value of i to the second.
secsVal = secsVal.map(Number);//trying to convert back to num, but I think map() needs to see an array, which I don't think I got here.
document.getElementById("countdown").value = secsVal;
document.getElementById("countdown").innerHTML = (secsVal);//I want to replace the first displayed digit here, with the new (concatenated) number.
}
}
It makes no sense to use a number for a value in an input tag. The type is always a string.
To convert to number use either Number or an unary +
secsVal = Number(secsVal);
or
secsVal = +secsVal;
Try this
secsVal = +("" + secsVal + i);
secsVal = Number('' + secsVal + i) // explicit cast to number
secsVal = +('' + secsVal + i) // implicit cast to number
secsVal = parseInt('' + secsVal + i) // explicit cast to integer
secsVal = ~~('' + secsVal + i) // implicit cast to integer
Simply use +secsVal
var secsVal = -1;
function valueAssign(i) {
if (secsVal == -1){
document.getElementById("countdown").value = i;
document.getElementById("countdown").innerHTML = (i);
secsVal = i;
}
else {
secsVal = "" + secsVal + i;
console.log(typeof secsVal);//secsVal is a string
secsVal = +secsVal;
console.log(typeof secsVal); //secsVal is now a number
document.getElementById("countdown").value = secsVal;
}
}
<input type="number" id="countdown"/>
<button onclick="valueAssign(5)">Click</button>
How about parsing the String?
"The parseInt() function parses a string and returns an integer."
http://www.w3schools.com/jsref/jsref_parseint.asp
This question already has answers here:
'IsNullOrWhitespace' in JavaScript?
(8 answers)
Closed 7 years ago.
I need to return true if string is containing either nothing or just space(s), else false.
var str = ""; // true
var str = " "; // true
var str = " 1 "; // false
var str = " s "; // false
How can I do that?
I have tried using /^\s*?$/.
/^ *$/
^ - from the start
$ - til the end
* - the string consists of zero or more spaces
See it in action
I would replace the spaces with nothing and see what the length is.
var strTest = str.replace(" ","");
if(strTest.length == 0) {dowork();}
if the string is all spaces then the length will be 0.
You could also do:
if (!str || !str.replace(/ /g, "")) {
// str is either empty, null, undefined or has nothing in it other than spaces
}
This also protects you if str is null or undefined too.
Here's a demo using the OP's test cases:
var testStrings = ["", " ", " 1 ", " s "];
testStrings.forEach(function(str) {
var result = false;
if (!str || !str.replace(/ /g, "")) {
// str is either empty, null, undefined or has nothing in it other than spaces
result = true;
}
log('"' + str + '"' + " tests as " + result + "<br>");
});
function log(x) {
var r = document.getElementById("results");
var div = document.createElement("div");
div.innerHTML = x;
r.appendChild(div);
}
<pre id="results"></pre>
<script type="text/javascript">
//var EProductId = prompt('Please enter your product Id');
var EProductId = [];
EProductId[0] = prompt("New member name?");
//Product price, code, name, declare here
var ProductId = [];
ProductId[0] = 001;
var product = [];
product[0] = "tshirt";
var ProdPrice = [];
ProdPrice[0] = 299;
//Condition start here
if (ProductId[0] === EProductId[0]) {
// var EProductId2 = parseInt(prompt("Please enter a product", "")ProductId[0] + ' ' + product[0] + ' ' + ProdPrice[0]);
prompt(ProductId[0] + ' ' + product[0] + ' ' + ProdPrice[0]);
} else{
alert("You pressed Cancel or no value was entered!");
}
</script>
Why it is not entering in if condition. i am entering the value 001 after run a program but it alert the message is You pressed Cancel or no value was entered!
if (ProductId[0] == EProductId[0]) {}
Only use === when comparing types.
=== is only used for strict comparisons in javascript. For example: if('0' == 0) would return true as only values are compared here. However, === would check if they are of the same type (2 strings, 2 numbers, but not 1 of each). So, 0===0 returns true while 0==='0' returns false.
You should use == instead. Using == you can compare if values of different types are 'truthy' or 'falsy'. Example: 0 == 0 returns true as well as '0' == 0.
typeof(prompt()) returns string. You will have to convert it to an integer first using parseInt(string, radix). The 10 specifies base 10, the common numbering system used by people.
if (ProductId[0] === parseInt(EProductId[0],10))
I guess it returns "001" as a string, try this
if (ProductId[0] === +EProductId[0])
The answer may be obvious but I don't see
I have a JavaScript object virtualTable. I write :
parseInt(virtualTable["resource_" + resourceId])
it returns NaN
I check virtualTable["resource_" + resourceId] with an alert and the answer is "690"
If I alert parseInt("690") it works fine and returns 690
What is wrong then?
the whole code :
if(!virtualTable.hasOwnProperty("resource_" + resourceId)) {
virtualTable["resource_" + resourceId] = "\"" + minutesToFill + "\"";
}
var timeForTarget = (target.end.getTime() - target.start.getTime()) / 60000;
var timeInVirtualTable;
var tooltipInTarget
if(virtualTable["resource_" + resourceId].indexOf("_") == -1) {
timeInVirtualTable = parseInt(virtualTable["resource_" + resourceId]);
tooltipInTarget = "";
} else {
timeInVirtualTable = parseInt(virtualTable["resource_" + resourceId].substring(0, virtualTable["resource_" + resourceId].indexOf("_")));
tooltipInTarget = virtualTable["resource_" + resourceId].substring(virtualTable["resource_" + resourceId].indexOf("_"));
}
Per your statement,
I check virtualTable["resource_" + resourceId] with an alert and the
answer is "690"
I'm assuming that the value inside virtualTable["resource_" + resourceId] is literally "690", including the quotes. Because of this, it's NaN, or, not-a-number (due to the leading double-quote).
If this will be common input, you can strip the double-quotes from your value before (or during) the call to parseInt using replace():
var value = virtualTable["resource_" + resourceId].replace(/"/g, '');
var number = parseInt(value);
or:
var number = parseInt(virtualTable["resource_" + resourceId].replace(/"/g, ''));
EDIT (parseInt()'s base):
Building on a comment, you should also remember to always specify the numeric-base to parse the input to. In your case, you want base-10 (or "decimal"). This is specified as the second parameter to parseInt():
var number = parseInt(value, 10);
or
var number = parseInt(virtualTable["resource_" + resourceId].replace(/"/g, ''), 10);