I need to concatenate two variables in jquery - javascript

I didn't find an answer to this, I need to concatenate two variables (ans & i) in Jquery to get ans1, ans2, etc. I tried this:
if(preguntaTipo<2){
var numero = "";
}
else{
var numero = $('#numero').val();
for (var i = 1; i < numero; i++) {
var ans.i = $('#ans'+i).val();
}
}
Its a mode to do like PHP $ans.$i? I also tried ans + i and it didn't work...

var ans.i = makes no sense.
You can't have periods/dots inside of variable names.
Is this what you're looking for?
var ans = [];
for (var i = 1; i < numero; i++) {
ans[i] = $('#ans' + i).val();
}
You could also use ans.push($('#ans' + i).val()); which would make the resulting answer array 0-based instead of 1-based.

Related

Can I concat a string and a variable to select a DOM element in JavaScript?

I have tried Googling this question but no luck. Probably because I'm asking the wrong way. Any help is much appreciated.
I have variables copy1, copy2, etc. I want to iterate through them and select each one to check if it's contents has a certain number of characters. When I use any variation of the below, it will either console an error or output a string in the console.
var copy1 = document.getElementById('copy1');
var copy2 = document.getElementById('copy2');
var copy3 = document.getElementById('copy3');
for(var i=0;i<4;i++){
console.log(copy+i);
console.log("copy"+i);
};
Ideally I would be able to select an element and style that via javascript.
Much appreciated
Thanks All.
Moe
Agree with #jaromanda-x:
var copy1 = document.getElementById('copy1');
var copy2 = document.getElementById('copy2');
var copy3 = document.getElementById('copy3');
for (var i=1; i<4; i++) {
console.log(window['copy'+i]);
};
Or you can use more simple example, like:
for (var i=1; i<4; i++) {
var name = 'copy' + i;
console.log(document.getElementById(name));
};
Or even:
for (var i=1; i<4; i++) {
console.log(document.getElementById('copy' + i));
};
You can store the properties in an object where values are set to the DOM element
let copies = {
1 : document.getElementById('copy1'),
2 : document.getElementById('copy2'),
3 : document.getElementById('copy3')
}
for (let [key, prop] of Object.entries(copies)) {
console.log(key, prop)
}
console.log(copies[1], copies[2], copies[3]);
Or use attribute begins with and attribute ends with selectors with .querySelector()
let n = 1;
let copy1 = document.querySelector(`[id^=copy][id$='${n}']`); // `#copy1`
let copy2 = document.querySelector(`[id^=copy][id$='${++n}']`); // `#copy2`
for (let i = 1; i < 4; i++) {
console.log(document.querySelector("[id^=copy][id$=" + i + "]"));
}
Since nobody has addressed your "certain number of characters" requirement yet, I thought I would.
You could always use jQuery or write your own $ method, which works as a document.getElementById() wrapper function.
Here is a jsfiddle to see it in action.
HTML
<div id="copy1">01234</div>
<div id="copy2">012345678</div>
<div id="copy3">0123456789 0123456789</div>
JavaScript
// Isn't this just a brilliant short-cut?
function $(id) {
return document.getElementById(id);
}
for (let i=1; i<4; i++){
let obj = $('copy' + i);
let value = (obj) ? obj.innerText : '';
console.log('value.length:', value.length);
};

Refer to the long range of variables in the array

I was wondering how to refer to the long range of variables in the array.
I have fields called Check1, Check2, Check3 up to 60. I'd like to refer to the range of Check1-Check60.
//Do I have to mention ALL the 60 fields here?
var fieldsToValidate = ["Check1", "Check2", "Check3", "Check4", "Check5", "Check6", "Check7"];
Is there a cleaner/shorter way to write this?
edit:
Forgot to mention I am using JavaScript for Acrobat, here's the snippet:
//Do I have to mention ALL the 60 fields here?
var fieldsToValidate = ["Check1", "Check2", "Check3", "Check4", "Check5", "Check6", "Check7"]; //etc.
var emptyFields = [];
for (var i in fieldsToValidate) {
var f = this.getField(fieldsToValidate[i]);
if (f.valueAsString==f.defaultValue) {
emptyFields.push(f.name);
}
}
if (emptyFields.length>0) {
app.alert("Error! You must fill in all required Fields:\n" + emptyFields.join("\n"));
} else {
this.getField("Signature1").display = display.visible;
}
If all your field are simply like Check[n] where n is incremented by 1. You can do the following
var fieldsToValidate = []
for (let i = 1; i <= 60; i++) {
fieldsToValidate.push("Check" + i);
}
console.log(fieldsToValidate);
Using a generator:
console.log([...function*(n) {
for (let i = 0; i < n; i++) yield `Check${i + 1}`;
}(60)]);
This method works for me, Thank you!
var fieldsToValidate = []
for (let i = 1; i <= 60; i++) {
fieldsToValidate.push("Check" + i);
}
console.log(fieldsToValidate);

get value from variable dynamically

I'm trying, but unsuccessfully, to get the value of a variable, where the variable name is dynamic
var v_1playerName = document.getElementById("id_1playerName").value;
var v_2playerName = document.getElementById("id_2playerName").value;
for (i = 1; i <=5 i++) {
alert(window["v_"+i+"playerName"]);
}
Is this possible?
A simple thing would be to put the variables in an array and then use the for loop to show them.
var v_1playerName = document.getElementById("id_1playerName").value;
var v_2playerName = document.getElementById("id_2playerName").value;
var nameArray = [v_1playerName,v_2playerName];
for (var i = 0; i < 5; i++) {
alert(nameArray[i]);
}
Accessing variables through window isn't a great idea.
Just store the values in an object and access them using square notation:
var obj = {
v_1playerName: 0,
v_2playerName: 3
}
obj['v_' + 2 + 'playerName']; // 3
If you want to keep named references to things you could use an object.
var playerNames = {};
playerNames['p1'] = document.getElementById("id_1playerName").value;
playerNames['p2'] = document.getElementById("id_2playerName").value;
for (i = 1; i <= 2; i++) {
// dynamically get access to each value
alert.log(playerNames['p' + i])
}

populate select element based on json

How could I populate a second select element? I've figured out how to do the first one. But how could I do the same for the second depending on which "Make" is selected? I've tried to talk myself through it while taking small steps but I'm thinking this may be too advanced for me.
var cars = '{"USED":[{"name":"Acura","value":"20001","models":[{"name":"CL","value":"20773"},{"name":"ILX","value":"47843"},{"name":"ILX Hybrid","value":"48964"},{"name":"Integra","value":"21266"},{"name":"Legend","value":"21380"},{"name":"MDX","value":"21422"},{"name":"NSX","value":"21685"},{"name":"RDX","value":"21831"},{"name":"RL","value":"21782"},{"name":"RSX","value":"21784"},{"name":"SLX","value":"21879"},{"name":"TL","value":"22237"},{"name":"TSX","value":"22248"},{"name":"Vigor","value":"22362"},{"name":"ZDX","value":"32888"}]},{"name":"Alfa Romeo","value":"20047","models":[{"name":"164","value":"20325"},{"name":"8c Competizione","value":"34963"},{"name":"Spider","value":"22172"}]}';
var carobj = eval ("(" + cars + ")");
var select = document.getElementsByTagName('select')[0];
//print array elements out
for (var i = 0; i < carobj.USED.length; i++) {
var d = carobj.USED[i];
select.options.add(new Option(d.name, i))
};
If I read your question right, you want to populate a second select with the models for the make in the first select. See below for a purely JS approach (with jsfiddle). If possible, I would recommend looking into jQuery, since I would prefer a jQuery solution.
http://jsfiddle.net/m5U8r/1/
var carobj;
window.onload = function () {
var cars = '{"USED":[{"name":"Acura","value":"20001","models":[{"name":"CL","value":"20773"},{"name":"ILX","value":"47843"},{"name":"ILX Hybrid","value":"48964"},{"name":"Integra","value":"21266"},{"name":"Legend","value":"21380"},{"name":"MDX","value":"21422"},{"name":"NSX","value":"21685"},{"name":"RDX","value":"21831"},{"name":"RL","value":"21782"},{"name":"RSX","value":"21784"},{"name":"SLX","value":"21879"},{"name":"TL","value":"22237"},{"name":"TSX","value":"22248"},{"name":"Vigor","value":"22362"},{"name":"ZDX","value":"32888"}]},{"name":"Alfa Romeo","value":"20047","models":[{"name":"164","value":"20325"},{"name":"8c Competizione","value":"34963"}, {"name":"Spider","value":"22172"}]}]}';
carobj = eval ("(" + cars + ")");
var makes = document.getElementById('make');
for (var i = 0; i < carobj.USED.length; i++) {
var d = carobj.USED[i];
makes.options.add(new Option(d.name, i));
}
makes.onchange = getModels;
getModels();
}
// add models based on make
function getModels () {
var makes = document.getElementById('make');
var make = makes.options[makes.selectedIndex].text;
for (var i = 0; i < carobj.USED.length; i++) {
if (carobj.USED[i].name == make) {
var models = document.getElementById('model');
models.options.length = 0;
for (var j= 0; j < carobj.USED[i].models.length; j++) {
var model = carobj.USED[i].models[j];
models.options.add(new Option(model.name, j));
}
break;
}
}
}
I would also recommend looking into safer JSON parsing. There is a security risk in using eval if it runs on any user input. You could look into JSON.org and their json2.js. Or if you want to use jQuery: parseJSON. Below is the jQuery version:
jQuery.parseJSON(jsonString);
JSON parsing tips from: Safely turning a JSON string into an object.

How to simplify this javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Any way to simplify this code?
What is the best way to simplify this for going from 1-19?
var backer1 = document.getElementById("backer-prediction-1").value;
var incentive1 = document.getElementById("incentive-cost-1").value;
var totalIncentive1 = parseInt(backer1,10) * parseInt(incentive1,10);
document.getElementById("incentive-total-1").value = totalIncentive1;
var backer2 = document.getElementById("backer-prediction-2").value;
var incentive2 = document.getElementById("incentive-cost-2").value;
var totalIncentive2 = parseInt(backer2,10) * parseInt(incentive2,10);
document.getElementById("incentive-total-2").value = totalIncentive2;
Last one I posted they gave me a "for" loop.
Still learning this stuff.. Very New, THANKS!!!
Just like the last question, use a for loop:
for(var i = 1; i < 20; i++){
var backer = document.getElementById("backer-prediction-"+i).value;
var incentive = document.getElementById("incentive-cost-"+i).value;
var totalIncentive = parseInt(backer,10) * parseInt(incentive,10);
document.getElementById("incentive-total-"+i).value = totalIncentive;
}
for (var i=1; i<=19; i++) {
var backer = document.getElementById("backer-prediction-" + i).value;
var incentive = document.getElementById("incentive-cost-" + i).value;
var totalIncentive = parseInt(backer,10) * parseInt(incentive,10);
document.getElementById("incentive-total-" + i).value = totalIncentive;
}
This untested code should be enough, unless you need access to the backer and incentive values for each one of the cases after the loop is completed.
Use Array in javascript
var backer=[],
incentive=[],
totalincentive=[];
for(var i=1;i<20;i++){
backer[i] = document.getElementById("backer-prediction-"+i).value;
incentive[i] = document.getElementById("incentive-cost-"+i).value;
totalIncentive[i] = parseInt(backer[i],10) * parseInt(incentive[1],10);
document.getElementById("incentive-total-"+i).value = totalIncentive[i];
}
So you can use them after ending for loop , like
backer[1]....,backer[19]
incentive[1]....,incentive[19]
totalincentive[1]....,totalincentive[19]
If the value of backer and incentive is a number, I'd be tempted to do:
var get = document.getElementById;
var backer, incentive, totalIncentive = 0;
for(var i = 1; i < 20; i++) {
totalIncentive += get("backer-prediction-" + i).value * get("incentive-cost-" + i).value;
}
as the multiplication will implicitly convert numeric strings to numbers. But you really should validate that the content of those elements is a valid number before doing anything, even if using parseInt.

Categories