document.getElementById("id").value , change id by adding a variable to it - javascript

function totalCost(obj,a){
var price = document.getElementById("price").value;
}
I want to create a new id adding variable a. If a =1, then the next id will be price1. How can I do it?

You can use Template Literals which allows embedded expressions:
function totalCost(obj,a){
var price = document.getElementById(`price${a}`).value;
}
OR: Using String Concatenation (if browser is yet to support Template Literals)
function totalCost(obj,a){
var price = document.getElementById('price' + a).value;
}

function totalCost(obj,a)
{
var price = document.getElementById("price"+a).value;
}
this solution is working fine .

Related

Why does javascript reads var as a string if i add '+' to it?

I have field names in my firestore document as
videolink1-"some video link"
videolink2-"some video link"
videolink3-"some video link"
I am using a for loop to get all videolinks present in the document.
if (doc.exists) {
for (var i = 1; i == videocount; i++) { //videocount is 3
var data = doc.data();
var videolink = data.videolink+i;
//creating new paragraph
var p = '<p class ="trackvideostyle">'+"Your Video Link : "+String(videolink)+'</p>\';
document.getElementById("btn").insertAdjacentHTML('beforebegin', p);
}
But this for loop is creating var values which are being read as string and firestore is returning me NaN as I dont have these fields :
data.videolink+1
data.videolink+2 //Firestore is returning null as i dont have these document fields
data.videolink+3
How can I write for loop so that var values are created like this and firestore reads it as:
videolink1
videolink2
videolink3
I think you could try something like this,
var videolink = data[`videolink${i}`];
Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
you are using "data.videolink+i" and javascript does not evaluate the value after the "." instead it is treated as the object's property. you need to use [] for evaluation. try this I hope this will work
if (doc.exists) {
for (var i = 1; i == videocount; i++) {
var data = doc.data();
var videolink = data[videolink+i];
//creating new paragraph
var p = '<p class ="trackvideostyle">'+"Your Video Link :
"+String(videolink)+'</p>\';
document.getElementById("btn").insertAdjacentHTML('beforebegin',
p);
}
Why it doesn't work
The dot operator (property accessor) has higher precendense, so it is evaluated first, so you get the value of the property and then you concatenate the value of your i variable.
What should you do
You can use another property accessor - square brackets, just like in arrays:
data['videolink']
You can build your property name inside of the square brackets:
data['videolink' + i]
or using template literals:
data[`videolink${i}`]
You can do this by using
1. template strings
..
var videolink = `${data.videolink}${i}`
..
2. concat()
..
var videolink = data.videolink.concat(i.toString());
..

Replace different Values in String?

I have a string which looks like this: (id:561644cdb40fbe0100247dd7:q) (id:56165d8a79c8c40100adbdb6:q) and I need to replace the different id's with different values. I already have the id's in a variable and trying to loop through with something like this var mailId = "(id:" + rplcId + ":q)"; But If I use the replace() function it doesnt work...Any other suggestions?
You can select the id with:
"(id:56165d8a79c8c40100adbdb6:q)".split(":")[1]
var id = "(id:561644cdb40fbe0100247dd7:q)";
var idArr = id.split(":");
idArr[1] = newId; //56165d8a79c8c40100adbdb6
var mailId = idArr[0]+idArr[1]+idArr[2];
and please provide your full code

Capturing variable names from a select

In the back end I have written some code that reads through a file and outputs to a list of JavaScript arrays for example, the page will see:
<script>
var peanuts = ["1","s","g","3","n"];
var cashewNuts = ["d","a","f","d","n"];
var PecanNuts = ["6","m","3","x","m"];
var BrazilNuts = ["j","n","7","v","s"];
var goingNuts = ["a","e","7","m","y"];
</script>
I then want to use an array based on the value of a somewhere else in that page.
So for example:
if($('select').val()===0){
alert(firstArray[1]);
}
My issue is that the variable names are decided on what is contained in the read file, I can't know this information. Is there a way to say for example
//collect the value from the select and assign it to a var
var varN = $('select').val();
//then collect another variable that has the variable name that
//equals the value of the 'varN'
I know this seems horrendous but unfortunately based on what I need to do, it is what I need to do :(
Yes. If for example your vars are in the global scope, you can do
var val = window[varN][0]; to get peanuts:1
If you do
var nuts = {
peanuts : ["1","s","g","3","n"],
cashewNuts : ["d","a","f","d","n"],
PecanNuts : ["6","m","3","x","m"],
BrazilNuts : ["j","n","7","v","s"],
goingNuts : ["a","e","7","m","y"]
}
then you can use
var val = nuts[varN][0];
If the variables are declared directly in <script>, you can use window[varN].

Javascript string concatenation issue

I am trying to create a new jQuery variable from some text and another jQuery variable.
This is what I have tried but it just displays "+emc+" instead of the value that the variable is set to.
var emc = $(".emc").attr("value");
var new_page = "index.php?emc=+emc+";
The new_page variable should display index.php?emc=XXXXXX but instead it displays as index.php?emc=+emc+
If I've understood correctly:
var new_page = "index.php?emc="+emc;
Or, indeed:
var new_page = "index.php?emc="+$(".emc").val();
You made a mistake in your string concatenation. You wanted to do this:
var new_page = "index.php?emc="+emc;
You have included the variable in the constant your code must look like:
var emc = $(".emc").attr("value");
var new_page = "index.php?emc="+emc;

use variable part of ID with js

I have a list of 8 divs: #video1, #video2, ... with each the same javascript actions to run when clicked, but with other id's (for #video1: show #image1, #preview1, ...).
Instead of writing 8 times the same code but with other id's, can I do this more efficient? Is it possible to take the sixth caracter (the number) from each #videoX as a variable when clicked, and use
this in the code?
Inside your event handler, you can extract the number, e.g. with a regular expression [MDN]:
var id = element.id.match(/\d+$/)[0];
and then use it to create the IDs of the other elements:
var image_id = "image" + id,
preview_id = "preview" + id;
Another option would be to assign data- attributes to the elements and use them to store the numerical part of the ID.
Use a class name instead. This way it's independent of the IDs completely.
<div class="videoClick" id="...">...</div>
JS:
$('.videoClick').click(function() {
...
})
yes you can:
$("div[id*='video']").click(function() {
var numid = $(this).attr("id").replace("video", "");
alert(numid);
//...use your numid value
});
Check attribute contains selector.
Try this
var ids = [#video1, #video2, #video3, #video4, #video5, #video6, #video7, #video8];
$(ids.join(",")).click(function(){
var imageId = this.id.replace("video", "image");
var previewId = this.id.replace("video", "preview");
$("#"+imageId).show();
$("#"+previewId).show();
});

Categories

Resources