Trying to pass concatenated JavaScript string to getElementById? - javascript

I'm getting an error saying:
"Uncaught TypeError: Cannot read property 'style' of null"
My JavaScript is:
function AddAFacultyMember(){
for(x=2;x<=10;x++){
var str0 = "'";
var str1 = 'Faculty';
var str2 = x;
var str3 = 'input';
var str4 = "'";
var concat = str0.concat(str1,str2,str3,str4);
if( document.getElementById(concat).style.display =='none' ){
var eligible = concat;
return;
}
document.getElementById(eligible).style.display == 'block';
}
}
An example of one of the Faculty div IDs is "Faculty1input". What's the issue?

This will work:
function AddAFacultyMember(){
for(x=2;x<=10;x++){
var concat = 'Faculty' + x + 'input';
var ele = document.getElementById(concat);
if( ele.style.display =='none' ){
ele.style.display = 'block';
}
}
}

found the issue!
the double == wasn't restyling the display of getElementById(eligible) to 'block' though it was correctly constructing the string. Solution/fix:
document.getElementById(eligible).style.display = 'block';
also removed str0 and str4:
function AddAFacultyMember(){
for(x=2;x<=10;x++){
var str1 = 'Faculty';
var str2 = x;
var str3 = 'input';
var concat =str1.concat(str2,str3);
if( document.getElementById(concat).style.display =='none' ){
var eligible = concat;
document.getElementById(eligible).style.display = 'block';
eligible = '';
return;
}
}
}
Thanks everyone for helping!

Try this:
funciĆ³n AddAFacultyMember({
for(x=2;x<=10;x++){
var str1 = 'Faculty';
var str2 = x;
var str3 = 'input';
var concat =str1.concat(str2,str3);
...

Related

JavaScript regex.exec() should intended to use an assembled regEx

if I use ( https://jsfiddle.net/fgsvzn4a/ ) :
var text = "ui1pu";
var regExParameter = '\d+';
var regEx = '/(.*)' + regExParameter + '(.*)/gi';
var matches = regEx.exec(text);
if(matches && matches[1]) {
var str1 = matches[1];
var str2 = matches[2];
var newStr = str1 + str2
console.log(newStr);
}
i get this error:
Paused on exception
TypeError: regEx.exec is not a function
this prototype is working (inspired by https://stackoverflow.com/a/15845184/2891692 ):
var text = "my1bla";
var matches = /(my)\d+(.*)/gi.exec(text);
if(matches && matches[1]) {
var str1 = matches[1];
var str2 = matches[2];
var newStr = str1 + str2
alert(newStr);
}
but i want to use input parameters to build the regex (first example).
i get ReferenceError: Regex is not defined if i try this:
var text = "ui1pu";
var regExParameter = '\d+';
var regExString = '/(.*)' + regExParameter + '(.*)/gi';
var regEx = new Regex(regExString);
var matches = regEx.exec(text);
if(matches && matches[1]) {
var str1 = matches[1];
var str2 = matches[2];
var newStr = str1 + str2
console.log(newStr);
}
any idea?
Use the RegExp constructor. Note that the slashes should be omitted from the string and the flags should be passed as the second argument.
var text = "ui1pu";
var regExParameter = '\\d+';
var regExString = '(.*)' + regExParameter + '(.*)';
var regEx = new RegExp(regExString, 'gi');
var matches = regEx.exec(text);
if(matches && matches[1]) {
var str1 = matches[1];
var str2 = matches[2];
var newStr = str1 + str2
console.log(newStr);
}
Based on the previous correct answers, I was able to come up with this more comprehensive solution. Its a little modification of this correct answer by Unmitigated and all answers :
// window.replaceDOM = function (regExParameter, replaceParameter) {
function replaceDOM(regExParameter, replaceParameter) {
// let reg = '/' + search + '/';
// regExParameter = '\\d+';
console.log('regExParameter=' + regExParameter);
const regExString = '(\\w+)' + regExParameter + '(\\w+)'; // ugly but needet. that escape, that double backslash
console.log('regExString=' + regExString);
const regEx = new RegExp(regExString, 'gi');
let elems = document.body.getElementsByTagName("*");
for (i in elems) {
let ele = elems[i];
if(ele.classList){
const val = ele.classList.value;
if(!val)
continue;
const matches = regEx.exec(val);
if(matches && matches[1]) {
console.log('val=' + val);
const str1 = matches[1];
const str2 = matches[2];
const valNew = str1 + replaceParameter + str2
// alert(valNew);
console.log('valNew=' + valNew);
ele.classList.value = ele.classList.value.replace(val, valNew);
}
}
};
}
.my1bla {
background-color: black;
}
.mybla {
background-color: blue;
}
<button onclick="replaceDOM('y\\d+','y')">
change the style class from DIV using regEx</button>
<div class="my1bla">
I am a DIV element
</div>

How do I make the right conditions for the url based on the value of a variable? (javascript)

My script javascript like this :
<script>
var url = 'http://my-app.test/item';
var sessionBrand = 'honda';
var sessionModel = 'jazz';
var sessionCategory = 'velg';
var sessionKeyword = 'RS 175/60 R 15';
if(sessionBrand)
var brand = '?brand='+sessionBrand;
else
var brand = '';
if(sessionModel)
var model = '&model='+sessionModel;
else
var model = '';
if(sessionCategory)
var category = '&category='+sessionCategory;
else
var category = '';
if(sessionKeyword)
var keyword = '&keyword='+this.sessionKeyword;
else
var keyword = '';
var newUrl = url+brand+model+category+keyword;
console.log(newUrl);
</script>
The result of console.log like this :
http://my-app.test/item?brand=honda&model=jazz&category=velg&keyword=RS 175/60 R 15
var sessionBrand, sessionModel, sessionCategory and sessionKeyword is dynamic. It can change. It can be null or it can have value
I have a problem
For example the case like this :
var sessionBrand = '';
var sessionModel = '';
var sessionCategory = '';
var sessionKeyword = 'RS 175/60 R 15';
The url to be like this :
http://my-app.test/item&keyword=RS 175/60 R 15
Should the url like this :
http://my-app.test/item?keyword=RS 175/60 R 15
I'm still confused to make the condition
How can I solve this problem?
Just use the array for params and then join them with & separator. For example:
var url = 'http://my-app.test/item';
var sessionBrand = 'honda';
var sessionModel = 'jazz';
var sessionCategory = 'velg';
var sessionKeyword = 'RS 175/60 R 15';
var params = [];
if (sessionBrand) {
params.push('brand=' + sessionBrand);
}
if (sessionModel) {
params.push('model=' + sessionModel);
}
if(sessionCategory) {
params.push('category=' + sessionCategory);
}
if(sessionKeyword) {
params.push('category=' + sessionCategory);
}
var newUrl = url + '?' + params.join('&');
console.log(newUrl);
The problem with your code is that it is prefacing all query parameters with a & - except for the sessionBrand. What you need in a URL is for the first parameter to start with a ?, and all others with a &. As you saw, your code doesn't do this when there is no sessionBrand.
There are number of ways to fix this. Probably the neatest I can think of is to assemble the various parts as you are, but without any prefixes - then join them all together at the end. Like this (I just saw Viktor's solution, it's exactly the same idea, but neater because he rewrote more of your earlier code):
if(sessionBrand)
var brand = 'brand='+sessionBrand;
else
var brand = '';
if(sessionModel)
var model = 'model='+sessionModel;
else
var model = '';
if(sessionCategory)
var category = 'category='+sessionCategory;
else
var category = '';
if(sessionKeyword)
var keyword = 'keyword='+this.sessionKeyword;
else
var keyword = '';
var queryString = '?' + [sessionBrand, sessionModel, sessionCategory, sessionKeyword].filter(function(str) {
return str.length > 0;
}).join("&");
var newUrl = url+queryString;

sum field values based on condition in another field in javascript

I am attempting to sum a number of field values but only if a condition associated with those filed values is met. For example:
I have a form with several number value fields. Each of those number fields is accompanied by a choice in status. I simply want to add all of the number fields of the same status, or possibly some with a couple different status. Here is the code I tried, that does not work:
// field names
var cTotal1 = "Day1Pd1Total";
var cTotal2 = "Day1Pd2Total";
var cTotal3 = "Day1Pd3Total";
var cTotal4 = "Day1Pd4Total";
var cTotal5 = "Day1Pd5Total";
var cTotal6 = "Day1Pd6Total";
var cStatus1 = "Day1Pd1Status";
var cStatus2 = "Day1Pd2Status";
var cStatus3 = "Day1Pd3Status";
var cStatus4 = "Day1Pd4Status";
var cStatus5 = "Day1Pd5Status";
var cStatus6 = "Day1Pd6Status";
// get conditonal field values
var vStatus1 = this.getField(cStatus1).value;
var vStatus2 = this.getField(cStatus2).value;
var vStatus3 = this.getField(cStatus3).value;
var vStatus4 = this.getField(cStatus4).value;
var vStatus5 = this.getField(cStatus5).value;
var vStatus6 = this.getField(cStatus6).value;
// get field values base on condition
if(vStatus1 = "1"){
var vTotal1 = this.getField(cTotal1).value;
}else{
var vTotal1 = "0";
}
if(vStatus2 = "1"){
var vTotal2 = this.getField(cTotal2).value;
}else{
var vTotal2 = "0";
}
if(vStatus3 = "1"){
var vTotal3 = this.getField(cTotal3).value;
}else{
var vTotal3 = "0";
}
if(vStatus4 = "1"){
var vTotal4 = this.getField(cTotal4).value;
}else{
vTotal4 = "0";
}
if(vStatus5 = "1"){
var vTotal5 = this.getField(cTotal5).value;
}else{
vTotal5 = "0";
}
if(vStatus6 = "1"){
var vTotal6 = this.getField(cTotal6).value;
}else{
vTotal6 = "0";
}
// clear result value
event.value = "";
// add values
var FLPTotal = vTotal1+ vTotal2 + vTotal3 + vTotal4 + vTotal5 + vTotal6;
event.value = FLPTotal;
I have also tried something like this:
var FLPTotal = vTotal1(vStatus1 == "1") + vTotal2(vStatus2 == "1") +vTotal3(vStatus3 == "1") +vTotal4(vStatus4 == "1") +vTotal5(vStatus5 == "1") +vTotal6(vStatus6 == "1")
My knowledge of JavaScript is fairly poor, I admit. Any help would be genuinely appreciated. Thank you!
After working on this some more, I noticed it was riddled with syntax errors. After fixing them, I got this to work:
// field names
var cTotal1 = "Day1Pd1Total";
var cTotal2 = "Day1Pd2Total";
var cTotal3 = "Day1Pd3Total";
var cTotal4 = "Day1Pd4Total";
var cTotal5 = "Day1Pd5Total";
var cTotal6 = "Day1Pd6Total";
var cStatus1 = "Day1Pd1Status";
var cStatus2 = "Day1Pd2Status";
var cStatus3 = "Day1Pd3Status";
var cStatus4 = "Day1Pd4Status";
var cStatus5 = "Day1Pd5Status";
var cStatus6 = "Day1Pd6Status";
// get conditonal field values
var vStatus1 = this.getField(cStatus1).value;
var vStatus2 = this.getField(cStatus2).value;
var vStatus3 = this.getField(cStatus3).value;
var vStatus4 = this.getField(cStatus4).value;
var vStatus5 = this.getField(cStatus5).value;
var vStatus6 = this.getField(cStatus6).value;
// get field values base on condition
if(vStatus1 == "1"){
var vTotal1 = this.getField(cTotal1).value;
}else{
var vTotal1 = "";
}
if(vStatus2 == "1"){
var vTotal2 = this.getField(cTotal2).value;
}else{
var vTotal2 = "";
}
if(vStatus3 == "1"){
var vTotal3 = this.getField(cTotal3).value;
}else{
var vTotal3 = "";
}
if(vStatus4 == "1"){
var vTotal4 = this.getField(cTotal4).value;
}else{
var vTotal4 = "";
}
if(vStatus5 == "1"){
var vTotal5 = this.getField(cTotal5).value;
}else{
var vTotal5 = "";
}
if(vStatus6 == "1"){
var vTotal6 = this.getField(cTotal6).value;
}else{
var vTotal6 = "";
}
// clear result value
event.value = "";
// add values
var FLPTotal = vTotal1 + vTotal2 + vTotal3 + vTotal4 + vTotal5 + vTotal6;
event.value = FLPTotal;
I am not sure it is as streamlined as it could be, but it is doing what I need.

node.js replace() - Invalid string length error

I've just coded a little script to replace all variables from a .txt file to their values in a JS file
Example:
Txt file example (values):
Hi = "HELLO WORLD",
Hey = /someregex/g,
Hh = 'haha';
Script example:
window[Hi] = true;
"someregex hi".replace(Hey, "")
window[Hh] = 1;
Here's my script:
var fs = require("fs")
var script = fs.readFileSync("./script.js", "utf8");
var vars = fs.readFileSync("./vars.txt", "utf8");
var replace = {}
var spl = vars.replace(/\r\n/g, "").replace(/ /g, "").split(",");
console.log("caching variables")
for(var dt of spl) {
var splt = dt.split(" = ");
var name = splt[0];
var val = splt[1];
if(!name || !val) {
continue;
}
if(val.endsWith(";")) {
val = val.slice(0, -1);
}
replace[name] = val;
}
console.log("Variables are in cache!")
console.log("Replacing variables in script")
var i = 1;
var t = Object.keys(replace).length;
for(var var_name in replace) {
var var_val = replace[var_name];
var regex = new RegExp(var_name, "g");
console.log(i, "/", t, "Replacing", var_name, "with", var_val, "regex", regex)
script = script.replace(regex, var_val);
i++;
}
console.log("DONE!")
fs.writeFileSync("./dec.js", script, "utf8")
However, when i ~= 100, I have this error:
RangeError: Invalid string length
at RegExp.[Symbol.replace] (native)
at String.replace (native)
EDIT: also, I can see that node.js process is using ~400MB of RAM and I have the error when it reaches 900MB
What's wrong?

javascript: how to modify the query string?

Like
?a=1&b=2&c=3
I only want to change b=6 while keep the other things the same, how to do it?
Following function if you have to replace any b=XXX with b=newBValue
function ReplaceB(strQuery,newBValue)
{
var idxStart= strQuery.indexOf("b=")
if(idxStart<0)
return; // b= not found, nothing to change
var idxFin=strQuery.substr(0,idxStart).indexOf("&");
var newQuery;
if(idxFin<0)
newQuery = strQuery.substr(0,idxStart) + "b="+newBValue
else
newQuery = strQuery.substr(0,idxStart) + "b="+newBValue+strQuery.substr(idxStart+idxFin)
return newQuery;
}
here a small function to do this:
jQuery.replaceURLParam = function (oldURL, replaceParam, newVal) {
var iStart = oldURL .indexOf(replaceParam + '=');
var iEnd = oldURL .substring(iStart + 1).indexOf('&');
var sEnd = oldURL .substring(iStart + iEnd + 1);
var sStart = oldURL .substring(0, iStart);
var newURl = sStart + replaceParam + '=' + newVal;
if (iEnd > 0) {
newURl += sEnd;
}
return newURl;
}
document.body.innerHTML = jQuery.replaceURLParam('www.foo.com?a=1&b=2&c=3', 'b', 6) ;
demo: http://jsfiddle.net/3rkrn/
var queryStr = "?a=1&b=2&c=3";
var startTag = "b=";
var endTag = "&";
var index1 = queryStr.indexOf(startTag) + startTag.length;
var index2 = queryStr.indexOf(endTag,index1);
var newValue = 23;
queryStr = queryStr.substr(0, index1) + newValue + queryStr.substr(index2);
alert(queryStr);
See it here : http://jsfiddle.net/aQL8p/
var test = "?a=1&b=2&c=3".replace(/b=2/gi,"b=6");
alert(test);
Example
var test = "?a=1&b=2&c=3".replace("b=2","b=6");
alert(test);
Example
var test = "?a=1&b=2&c=3".split("b=2").join("b=6");
alert(test);
Example
Regardless of Number
Want to change to value of b regardless of number it is already? Use:
var test = "?a=1&b=2&c=3".replace(/b=\d/gi, "b=6");
alert(test);
Example
var queryString = '?a=1&b=2&c=3'.replace(/([?&;])b=2([$&;])/g, '$1b=6$2');
jsFiddle.
(JavaScript regex does not support lookbehinds).
See if this works for you - a more or less universal urlFor:
https://gist.github.com/4108452
You would simply do
newUrl = urlFor(oldUrl, {b:6});

Categories

Resources