I am trying to dynamically have my javascript look for an element ID in the DOM.
I am currently using this
var string = "retail";
document.getElementById('markup_'+string+'_percentage').value=z.toFixed(2)+"%";
Where the variable "string" has a value like "retail"
This I thought would give a concatenated string of "markup_retail_percentage".
However it actually gives this as an error message:
document.getElementById("markup_"+string+"_percentage") is null
I have tried also using the "." and " * " operators.
One of my html elements
<input type="text" id="markup_retail_percentage" size="5" name="markup_retail_percentage" value="" readonly />
SOLUTION!!!!
//using a new variable name to be passed to function
function percentage(elementid)
{
elementid = "markup_" + elementid;
elementid = elementid + "_percentage";
document.getElementById(elementid).value = "a value";
}
I see two^w three^w four possibilities:
string doesn't contain what you think it does
you should have an underscore before percentage.
the specified element really doesn't exist! (thanks #jAndy)
it does, but the DOM isn't ready yet (thanks #Yoshi)
It looks like you are missing an underscore ahead of percentage
document.getElementById('markup_'+ string +'percentage')
I think you want
document.getElementById('markup_'+ string +'_percentage')
If you run this code before the Document has finished loading, your markup will not have been fully parsed and the Element with that id will not be accessible using DOM methods.
Solution:
function percentage(elementid)
{
elementid = "markup_" + elementid;
elementid = elementid + "_percentage";
document.getElementById(elementid).value = "a value";
}
I dont know why its working:
-Could be concatenation problem , not allowed to use multiple " + " operators?
-Change variable name ?
But it is working now, so thanks to all!
Related
I've been away from jQuery development and all js in general for about three years. I can not for the life of me remember how this is supposed to work. This has been going on for four days, and I could really use some help.
Can you tell me what I am doing wrong here:
var $imgAll = $(function(f, a) {
'<img src="' + f + ' alt="' + a + '">';
});
var $imgAC = $imgAll('filename1.jpg', 'Some Alt Text');
var $imgBC = $imgAll('filename2.jpg', 'Some Alt Text');
$page.append($imgAC);
I want an output of code for images whose filenames (f) and alt texts (a) are passed using a single function. It looks like Greek at this point because I'm staring at it constantly.
Thanks for any help!
You'll want $imgAll to be a function, not the return value of a call of $. Here is how it could work:
var $imgAll = function(src, alt) {
return $('<img>').attr({src, alt});
}
var $imgAC = $imgAll('https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.svg', 'Some Alt Text');
$("body").append($imgAC);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Note how the call to attr avoids building the attribute strings yourself, and thereby the potential problems with characters that need escaping. Also, by naming the function parameters as the attribute names (src and alt) you can use the short object literal notation. You could even use an arrow function expression:
const $imgAll = (src, alt) => $('<img>').attr({src, alt});
If I have:
<div class="test" data-name="Paul" >
and
var name = "Paul";
Can I use document.querySelector to do something like this?
document.querySelector("[data-name=name]");
This doesn't work. What do I have to do?
You can do that, but you need to use the CSS.escape() function to ensure the value is properly encoded for use in a CSS expression.
var name = "hello, world!";
document.querySelector("[data-name=" + CSS.escape(name) + "]");
<div data-name="hello, world!">…</div>
ES2015:
const name = "hello, world!";
document.querySelector(`[data-name=${CSS.escape(name)}]`);
If you don't use CSS.escape(...) then certain values of name could cause your code to throw an error instead.
var name = "hello, world!";
document.querySelector("[data-name=" + name + "]");
Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '[data-name=hello, world!]' is not a valid selector
If you're targeting a browser which doesn't natively support CSS.escape() you can use this polyfill by Mathias Bynens.
You need to concatenate the strings, like:
document.querySelector("[data-name=" + name + "]");
For example:
(See #Jeremy Bank's answer for a much better answer, tho)
var name = "Paul";
var element = document.querySelector("[data-name=" + name + "]");
alert(element.nodeName);
<div class="test" data-name="Paul">
test.
</div>
you could also do this
let name = 'Paul'
document.querySelector('.'+ name)
then you do not need a data-name
This works in Typescript:
document.querySelector(\`[data-name=${name}]`)
<div class="test" data-name="Paul"></div>
Try in this way it may be work :-
var username = "Paul";
document.querySelector(`[data-name="${username}"]`);
I'm super late to this party but check out the code snippet - it shows you how to get the current value of data-name and also how to change the value
let test = document.querySelector('.test');
// get the current value of data-name
let name = test.dataset.name;
console.log('current value of data-name: ' + name)
// change the value of data-name
let newName = 'Jimmy'
console.log(test.dataset.name = newName);
<div class="test" data-name="Paul"></div>
When trying to pass String value to the javascript function , Uncaught ReferenceError is thrown on the browser console.
Below is the sample code:
function mySampleTest(myId, comments){
alert("myId " + myId);
alert("comments : " + comments);
}
var myTest = function(value, rowIndex) {
var myId = this.grid.getItem(rowIndex).MY_ID;
var comments = this.grid.getItem(rowIndex).COMMENTS;
return "<img src=<%=request.getContextPath()%>/images/image1.gif width=\"25\" height=\"25\" onClick=\"mySampleTest("+ myId +" , "+comments+")\">";
};
The JavaScript function mySampleTest is being called when the user clicks the image but it throws a JavaScript error when I pass the string comments to mySampleTest function. If I remove the comment parameters and just pass the myId to mySampleTest(..), it works fine.
Please suggest how to pass string values to the JavaScript function.
I tried the below also, but didn't work.
return "<img src=<%=request.getContextPath()%>/images/image1.gif width=\"25\" height=\"25\" onClick=\"mySampleTest("+ myId +" , \'' + comments + '\')\">";
As a professor once told me, much of writing code involves "being the computer".
Consider your function's output for a moment and you should see the issue pretty quickly:
<img src=whatever/your/context/path/is/images/image1.gif
width="25" height="25"
onClick="mySampleTest(12345, this is a comment)">
Your javascript is invalid:
mySampleTest(12345, this is a comment)
It should be:
mySampleTest(12345, 'this is a comment') // <--- notice the quotes
Which would translate all the way back to:
return "<img src=\"<%=request.getContextPath()%>/images/image1.gif\" width=\"25\" height=\"25\" onClick=\"mySampleTest('"+ myId +"' , '"+comments+"')\">";
Not to mention your src attribute really needs quotes.
I am making an image for my webpage through javascript like so:
photoHTMLString = '<li class = "SliderPhoto"><img src = "' + ImageArray[x].src_small + '" size = "thumb" onclick = "ShowImagePopUP(' + ImageArray[x].src_big + ')" class = "FacebookSliderPhoto"/></li>';
Whenever I try and click a photo go into ShowImagePopUP I get this error:
missing ) after argument list
[Break On This Error] ShowImagePopUp(http://a8.sph...389_84095143389_5917147_2636303_n.jpg)
It doesn't look like I am missing any ')'s so I am lost on the error.
Any suggestions?
You need to wrap the contents of ShowImagePopUP in quotes:
"ShowImagePopUp(\'' + ImageArray[x].src_big + '\')"
Which should render as:
ShowImagePopUp('http://a8.sph...389_84095143389_5917147_2636303_n.jpg')
^ note the quote here
Example: http://jsfiddle.net/V23J6/1/
try
photoHTMLString = '<li class = "SliderPhoto"><img src = "'
+ ImageArray[x].src_small
+ '" size = "thumb" onclick = "ShowImagePopUP(\"'
+ ImageArray[x].src_big + '\")" class = "FacebookSliderPhoto"/></li>';
should do the trick and solve your problem leaving intact the uglyness of you code
A function like this one should be a bit readable and ready to use...
function slideElement(image){
var li=document.createElement('li');
var img=document.createElement('img');
li.appendChild(img);
li.setAttribute('class','SliderPhoto');
img.setAttribute('class','FacebookSliderPhoto');
img.setAttribute('size', 'thumb');
img.setAttribute('src', image.src_small);
img.setAttribute('onclick', function(){showImagePopUP(image.src_big);});
return li;
}
The value in ImageArray[x].src_big needs to be quoted.
Try to avoid building HTML by mashing strings together. Using a DOM builder gives code that is much easier to debug.
You'd probably be better off writing this so the function computes the large URI based on the small URI rather than having it hard coded.
Here's some general advice, build up the strings into intermediate variables and then assemble it at the end. You can then use the debugger to find out where you're getting your ' or "s unbalanced. When you have it all built you can coalesce it into a single line if you want or leave it with the intermediate variables.
I am working in JavaScript coding. I have created a text area with name OQ_0 and value "0". When i use eval() method for that field in JavaScript it is giving the value undefined. The below are the part of JavaScript code
var tempOpenQtyStr = "document.InitiateReturnsForm.OQ" + "_" + 0;
var tempOpenxQtyStr = eval(tempOpenQtyStr).value;
alert('Manuals =' + document.InitiateReturnsForm.OQ_0.value);
alert('eval(tempOpenxQtyStr ) =' + eval(tempOpenxQtyStr));
alert('eval(tempOpenxQtyStr).value =' + eval(tempOpenxQtyStr).value);
Output:
Manuals = 0
eval(tempOpenxQtyStr ) = 0 --- Here it is suppose to show "[object]"
eval(tempOpenxQtyStr).value = undefined.
Kindly help me out what is change to do. Thanks in advance.
Why not just use document.InitiateReturnsForm["OQ_" + 0].value?
Try
alert('eval(tempOpenxQtyStr ) = ' + eval(tempOpenQtyStr));
alert('eval(tempOpenxQtyStr).value = ' + eval(tempOpenQtyStr).value);
In the second and third alert you are evaluating the second variable which stores the value of the first evaluated object. That's why the error occurs.
alert('eval(tempOpenxQtyStr ) =' + eval(tempOpenxQtyStr));
Since you put a string, not an object, inside tempOpenxQtyStr, it evaluates that string and returns 0.
alert('eval(tempOpenxQtyStr).value =' + eval(tempOpenxQtyStr).value);
Here you're using a method on a variable that contains a string. That doesn't work. It doesn't have that method, that's why it returns undefinied.
You might want to try doing eval(tempOpenxQtyStr.value) instead of eval(tempOpenxQtyStr).value since the last one does basically nothing, just evaluating an object and then fetching the objects value (it doesn't eval the value itself).