I have been trying for hours to fix this code, I can't see what's wrong:
document.getElementById('detail'+num).innerHTML='<a class="dobpicker" href="javascript:NewCal('+s_d+','+ddmmyy+')">'
The problem is in href="javascript ..."
s_d is a javascript variable defined as
var num = 2;
var s_d = "sname"+num;
var ddmmyy = "ddmmyy";
Basically I need to call a javascript function with different parameter each time.
Use a backslash like \'.
document.getElementById('detail'+num).innerHTML=
'<a class="dobpicker" href="javascript:NewCal(\''+s_d+'\',\''+ddmmyy+'\')">'
Since this is the value of a href attribute, HTML encode them:
document.getElementById('detail'+num).innerHTML='<a class="dobpicker" href="javascript:NewCal("'+s_d+'","'+ddmmyy+'")">'
Or better yet don't use the javascript: protocol:
[0,1,2,3,4,5].forEach(function(num) {
var s_r = "sname"+num;
var ddmmyy = "ddmmyy";
var aEl = document.createElement("a");
aEl.className = "dobpicker";
aEl.onclick = function() {
NewCal(s_d, ddmmyy);
}
document.getElementById('detail'+num).appendChild(aEl);
});
Your .innerHTML setting is using s_d, but your variable declaration has s_r.
EDIT: That was the first thing that jumped out at me. Having looked a bit closer and realised the values are strings, I think fixing the variable name together with adding some escaped quotation marks as in Daniel A. White's answer will do the trick.
Related
I'm trying to create a button that links to a random page in my simple website. I'm having issues modifying the "href" and making it go to the page on the click.
Here is the JavaScript I have written:
document.addEventListener("DOMContentLoaded", function(){
let arrayofpages = ["my_cat.html","about_me","art.html","index.html"]
let randompage = arrayofpages[Math.floor(Math.random()*arrayofpages.length)];
document.addEventListener("click",function(){
document.getElementById("lucky_btn").href = "${randompage}";
document.getElementById("lucky_btn").innerHTML = "random page";
});
The string "${randompage}" is literally just a string that says "${randompage}". Instead, use backticks:
`${randompage}` // This creates a string out of the variable randompage
But in your case, since you're not doing anything with the string, the simplest way is to use the variable directly:
document.getElementById("lucky_btn").href = randompage;
In general, template literals are more useful for inserting variables into a longer string, like
let name = 'Sarah';
let quality = 'great';
let message = `Hello ${name}, have a ${quality} day`;
A little bug in your code. you used double quotes "" instead of backticks ``.
This line
document.getElementById("lucky_btn").href = "${randompage}";
should be
document.getElementById("lucky_btn").href = `${randompage}`;
I have found the bug that was causing the issue, of not redirecting to a random page:
instead of
document.getElementById("lucky_btn").href = "${randompage}";
where I should have used backticks, I changed the code to:
document.location.href = `${randompage}`;
and this has solved the problem!
Sorry if this question has already been asked. If so, could someone please direct me to the thread(s)? I have not found any existing ones so far.
But my question revolves around this type of action:
var Product_Linky = document.getElementById("Product_Link_Container");
Product_Linky.style.position.left= 12px;
A literal is being applied to the attribute with the indicated units. But...can a variable be applied and if so, how would the units be specified?
The following code is not written properly, but it shows an example of the problem I have:
var Product_Linky = document.getElementById("Product_Link_Container");
Product_Linky.style.position.left= 'MyVariable_x'px ;
If a variable can be used, what is the correct syntax to include the units?
Best regards!
There's a similar question already, but to answer your question this will work:
var variable_Length = 5;
var Product_Linky = document.getElementById("Product_Link_Container");
Product_Linky.style.position.left= variable_Length + 'px' ;
Try using template Literals!
In JavaScript, if you want to make a variable "fit in" to a string, you an use the following syntax:
var num = 12;
var myString = `My number is ${num}.`;
console.log(myString);
will log
My number is 12.
One important note on this: you cannot use regular quotation marks to enclose the string. You must use the backtick:
`
(it should be right above your tab key). Otherwise, this will not work.
For more information, check out the MDN Web Docs!
For an example, check out this Codepen I made! (Try changing the myHeight variable's value.)
I hope that helps!
Do this, my friend. It's called ES6 template literal
Product_Linky.style.position.left= `${MyVariable_x}px` ;
Or you do the String concatenation like this
Product_Linky.style.position.left= MyVariable_x + 'px' ;
How can I strip the $ and , characters from the following value, the code i am using is not working
var asset_value = second_col.find("input[type=text]").val().replace('$', '');
second_col.find("input[type=text]").val() looks like
$1,080.00
Update:
I am not sure why i am getting voted down! the duplicate solution does not solve my question, nor does any answer below, except for this, very strange!
second_col.find("input[type=text]").val(function(i, val) {
return val.replace(/\$|,/g, '');
});
var asset_value = second_col.find("input[type=text]").val();
You can use regex for this:
second_col.find("input[type=text]").val().replace(/[\$,]/g,'').
Assign this value to variable and use it.
Okay, so I have some variables in javascript...
var link = 'http://8wayrun.com/streams/multi?type=3&pos1=1.teamsp00ky.video&pos2=1.teamsp00ky.chat&pos3=1.nycfurby.chat';
var position = 2;
As you can see, I have a link and a position. Using the position var I would like to replace some text in the link field. I would like to strip &pos2=1.teamsp00ky.chat from the link. Naturally, I have to do some basic regular expressions; the problem comes into when I try to use the position var in the regex. I just can't figure it out.
In PHP I could do the following:
preg_replace('/&pos'.$position.'=[^&]*/i', '', $link);
I tried the following in JS, but its not working:
link.replace(new RegExp('&pos'+position+'=[^&]*'), '');
Could someone help me out and tell me what I'm doing wrong? Also, how would I make it case-insensitive?
You need to set the value, not just call the method:
link = link.replace(new RegExp('&pos'+position+'=[^&]*'), '');
To make it case insensitive, use this regex:
new RegExp('&pos'+position+'=[^&]*', "i")
Although it might make it easier if you split the string on the "?", then split up the key/value pairs by "&", and then split them by "=".
Could someone help me out and tell me what I'm doing wrong?
replace does not mutate the string, but returns a new one - you'd have to assign it somewhere.
Also, how would I make it case-insensitive?
Pass the i flag to the RegExp constructor.
link = link.replace(new RegExp('&pos'+position+'=[^&]*', 'i'), '');
<div id="result"></div>
var link = 'http://8wayrun.com/streams/multi?type=3&pos1=1.teamsp00ky.video&pos2=1.teamsp00ky.chat&pos3=1.nycfurby.chat';
var position = 2;
var start = link.indexOf("pos2");
var end = link.indexOf("&", start);
document.getElementById("result").textContent = link.slice(0, start) + link.slice(end + 1);
on jsfiddle
The question is simple, assume the following string:
var str = 'aaaaab\'s'
How do you extract the value of href. I would think something like
var arr = str.match(/(?:href=")(\w+)/g) ;
--> ["href="aaaa", "href="bb"]
Of course I want
["aaaa", "bb"]
Withoug the /g it get close, but it only matches "aaaa". Any suggestions how to fix this ?
Thanks!
DOM parsing with JS is so easy.
var str = 'aaaaab\'s',
help = document.createElement('div');
helper.innerHTML = str;
Array.prototype.forEach.call(help.querySelectorAll("a[href]"), function (elem) {
console.log(elem.getAttribute('href'));
});
http://jsfiddle.net/ExplosionPIlls/gtdFh/
Because Javascript doesn't have lookbehind, this may be what you want. Naturally there will be more elegant solutions:
input.match(/<[^href|/]*(href[\s]*=[\s]*")([^"]+)(?=">)/g).map(
function(x){return x.split('href')[1].replace(/[^"]+"(.*)/,'$1');
})
Additionally, you may be better off getting a HTML parsing plugin. And extracting the properties you need using that.
Cheers.