Dynamic variable creation using eval JavaScript - javascript

I need something like an associative array that contains pairings of variable name / element ID.
Looping through this array/object, assign the element ID to the variable name that is its counterpart. Something like this:
jsFiddle
HTML:
<input id="fld_1" class="input" type="text" value="bob" /><br>
<input id="fld_2" class="input" type="text" value="fred" /><br>
<input id="fld_3" class="input" type="text" value="pat" /><br>
<input id="mybutt" class="btn" type="button" value="Test" />
JS:
objFields = {'f1':'fld_1', 'f2':'fld_2', 'f3':'fld_3'};
arrErrors = [];
$('#mybutt').click(function(){
alert('iii');
for (var key in objFields){
// eval(key = objFields[key]);
eval(key) = objFields[key];
alert('f1: ' +f1);
}
});
There is no requirement to using eval, I just need to turn the key into the variable name.
Where have I gone wrong?
Solution
JCOC611 got it right, but I wasn't clear in how I asked the question. As demo'd in this revised fiddle which implements JCOC611's solution, the variable/field names had to be used to get the value of the field contents, like this:
$('#mybutt').click(function(){
for (var key in objFields){
var tmp = objFields[key];
eval('var ' + key+ ' = $("#' +tmp+ '").val()');
}
});

If you know what you are doing and are absolutely sure about it, then use this:
eval(key + " = " + JSON.stringify(objFields[key]));
Or, if you want local variables:
eval("var " + key + " = " + JSON.stringify(objFields[key]));
Otherwise, I advice you implement one of the other answers.

You don't need that eval() at all, and you want to avoid it. All you really need to do is:
for (var key in objFields){
alert(key+': '+objFields[key]);
window[key] = objFields[key];
}
Will give you:
'f1':'fld_1'
'f2':'fld_2'
'f3':'fld_3'
Where:
f1 = 'fld_1';
f2 = 'fld_2';
f3 = 'fld_3';

If it is a global variable, it is as simple as:
window[key] = objFields[key];
or
window.key = objFields[key];
The second one is a bit less weird name immune.

The eval function runs a string add code and returns the result.
What your code did was evaluate the vague of key which is undefined and then tried to set it to a new value.
Is like writing 5=4;
Correct syntax:
eval('var ' + key + ' = ' + objFields[key]);

Related

How can I get a time value from HTML using JavaScript?

I'm trying to get the value of a time input element via JavaScript. When I try using getElementById the value that is displayed is:
[object HTMLInputElement]
If use querySelectorAll, the value is:
[NodeList]
I also tried to use the index, but nothing new happens.
Here is my HTML:
<div class="principal-grid">
<title>Hour Control</title>
<label class="description-values">In</label>
<input id="data-in" type="time" class="values">
<label class="description-values">Interval - SaĆ­da</label>
<input id="data-interval-s" type="time" class="values">
<label class="description-values">Interval - Volta</label>
<input id="data-interval-v" type="time" class="values">
<label class="description-values">Out</label>
<input id="data-out" type="time" class="values">
<input id="submit" type="submit" class="send" value="Send">
</div>
And this is the script:
var dataIn = document.getElementById(['data-in']);
var dataInterval_out = document.getElementById(['data-interval-s']);
var dataInterval_in = document.getElementById(['data-interval-v']);
var dataOut = document.getElementById(['data-out']);
document.getElementById("submit").onclick = function (e) {
//test
document.getElementById("test").innerHTML = dataIn + ' ' + dataInterval_out +
' ' + dataInterval_in + ' ' + dataOut;
}
A couple of things to note here:
First up, when you use: var dataIn = document.getElementById(...)
It's returning a reference to the html element identified by the Id string and storing it in the dataIn variable you created. If you want the value of that element, you need to use: dataIn.value.
Here's an updated version of your script that does what I think you want:
var dataIn = document.getElementById('data-in');
var dataInterval_out = document.getElementById('data-interval-s');
var dataInterval_in = document.getElementById('data-interval-v');
var dataOut = document.getElementById('data-out');
document.getElementById("submit").onclick = function (e) {
//test
document.getElementById("test").innerHTML = dataIn.value + ' ' + dataInterval_out.value +
' ' + dataInterval_in.value + ' ' + dataOut.value;
}
The second thing is that getElementById takes a string value. You're wrapping it in []'s, which is unnecessary.
One last note: type="time" is not supported on all browsers. (Safari doesn't support it for example). So you may want to look for an alternative method for collecting dates, if supporting macOS and iOS devices is important to you.
To get value of input using vanilla js, use .value property.
var dataIn = document.getElementById('data-in').value;
var dataInterval_out = document.getElementById('data-interval-s').value;
var dataInterval_in = document.getElementById('data-interval-v').value;
var dataOut = document.getElementById('data-out').value;
Also, getting element by id, use document.getElementById('elementId')

Dynamically assigning variable names JavaScript

I am trying to dynamically assign variable names using the user's input. For example:
var input = document.querySelector('input');
for(var i = 0; i < 10; i++){
var newVariableName = //input.value;
}
Any help would be very much appreciated.
Thank you,
Scratch Cat
Everything in JavaScript is an object. The way JavaScript works, you can add properties to objects in two ways:
Specify them the fixed way (e.g. obj.propertyName = 'Value')
Specify them using array notation (e.g. obj[propertyName] = 'Value'). In this case, note that propertyName is a string value.
In both cases, the result will be exactly the same. You could retrieve those properties likewise, e.g. obj.propertyName and obj[propertyName]. Both will return 'Value'.
In your case, #LuudJacobs's suggestion about using the window object will most probably do the trick...
You can use array in which the keys will be the input values and the value would be anything you want.
html
<form>
<input type="text" value="demo1" class="example"><br />
<input type="text" value="demo2" class="example"><br />
<input type="text" value="demo3" class="example">
</form>
js
First you declare array
var a = new Array();
Then you use for loop to assign key names to array which will be the input values
for(var i = 0; i < 3; i++){
a[x[i].value] = x[i].value;
}
Finally you can use those key names to access the values
alert(a['demo1'] + ' ' +a['demo2'] + ' ' + a['demo3']);
Here is a link to an example
https://jsfiddle.net/309fpsjn/1/
<html>
<form>
<input type="text" value="demo1" class="example"><br />
<input type="text" value="demo2" class="example"><br />
<input type="text" value="demo3" class="example">
</form>
<script>
var x = document.querySelectorAll(".example");
var a = new Array();
for(var i = 0; i < 3; i++){
a[x[i].value] = x[i].value;
}
alert(a['demo1'] + ' ' +a['demo2'] + ' ' + a['demo3']);
</script>
</html>

Is it possible to create a jQuery function that plays around with the name of the selector?

I am trying to make a counter for "Number of characters left" in a form:
<input type="text" id='username_input'>
<input type="text" id='password_input'>
Is it possible to make a function whose parameter will be part of the selector?
So you can understand my question better, I'll show you an example that I did, and that doesn't work.
What I'm trying to do will seem obvious. This implies I have to standardize all id's.
I'm aware I could make a maxChar parameter in the function, but I left my mistake field+'_maxChar' so that you can tell me why it's not possible.
THanks a lot in advance
var username_maxChar=20,password_maxChar=30;
function countLeft(field,minCharacters){
$('#'+field+'_input').keyup(function(){
var input_length = $('#'+field+'_input').val().length;
var input_count = field+'_maxChar' - input_length;
$('#'+field+'_counter').text(input_count);
});
}
countLeft(username,6);
Since you have defined these with the var keyword outside the function scope, they become properties of the window object and can be accessed with the [] notation:
var input_count = window[field + '_maxChar'] - input_length;
However, you might consider just using the maxlength attribute:
<input type="text" id='username_input' maxlength='20'>
<input type="text" id='password_input' maxlength='30'>
These are available to jQuery via .attr()
var input_count = $('#' + field + '_input').attr('maxlength') - input.length;

simpler way of grouping numerous variables by value of select?

thanks for looking.
im still learning the more complex javascript and jquery coding so could do with some help as i have no idea about the following or even if its possible!
i need a better/simpler/shorter way of doing the following (please note i have removed the irrelevant validation etc coding):
'
function Findbox5( myform, box1, box2, box3, box4, box5, Storeall, s1, s2, s3, s4, s5)
{
//store values
Myform = document.forms.myform;
box1 = Myform.box1.value;
box2 = Myform.box2.value;
box3 = Myform.box3.value;
box4 = Myform.box4.value;
box5 = Myform.box5.value;
s1 = Myform.s1.value;
s2 = Myform.s2.value;
s3 = Myform.s3.value;
s4 = Myform.s4.value;
s5 = Myform.s5.value;
//set as one string
Storeall = s1 + ":" + box1 + ";" + s2 + ":" + box2 + ";" + s3 + ":" + box3 + ";" + s4 + ":" + box4 + ";" + s4 + ":" + box5 + ";" ;
// next function...
} '
as you can see i have 5 input boxes and relevant selects for each box(each select has 4 options:1,2,3,4.). when a user enters data into a box they choose a relevant option. all boxes and options must be entered then they submit the form.
this data will be emailed to me as the variable stored under storeall. which would be something like 1:1234;2:1324;1:3232;4:5434;2:3211;
so what i hope to do is simplify this data into the following with either a seperate function or the same one: 1:1234-3232;2:1324-3211;4:5434;
is this possible? or have i done it the easiest way?
any comments or help welcomed, thanks again
First, you'll want to group these things into a single element that can be iterated against. So if your HTML looks like:
<form>
<input name="s1" />
<input name="box1" />
<input name="s2" />
<input name="box2" />
...
</form>
Then it's probably better to do something like:
<form>
<div class="set">
<input class="s" name="s1" />
<input class="box" name="box1" />
</div>
<div class="set">
<input class="s" name="s2" />
<input class="box" name="box2" />
</div>
...
</form>
Now you've established some commonality among these elements, instead of just different names/IDs. Each set of inputs is grouped by the .set class, and within each set, you know there's going to be two inputs: one with the .s class, and one with the .box class. Now iterating against them with JQuery is easy:
var str = "";
$("form div.set").each(
function(index, element)
{
currentValueS = $(element).find("input.s").val();
currentValueBox = $(element).find("input.box").val();
str += currentValueS + ":" + currentValueBox + ";";
}
);
This uses JQuery's .each() function. .each() allows you to provide a function to perform on each of the elements that JQuery finds from the indicated selector. Here, your selector is form div.set, which means "all div elements that have the class of .set, and are found anywhere under any form element". For each of these elements, you'll need to find the value of the <input> element with the .s class, and also the value of the <input> element with the .box class. Then you just add those to your growing str variable.
If you want everything in the form, you should use serializeArray :
$('#my_form').submit(function() {
var str = '';
$.each($(this).serializeArray(), function () {
str += this.name + ":" + this.value + ";";
});
sendByMail(str);
return false;
});

Need help with regular expression and javascript

I've following problem: I use a clone script to clone input fields which are used for cms options. Depending on the field name the option arrays are created in the db.
I have following field at the moment:
options[categories][1][3]
and want to increase the first number by using a counter variable like:
options[categories][2][3]
options[categories][3][3]
...
However I'm not familiar with regular expressions so I hoped someone could provide a str.replace code which helps me to replace the first number with my counter variable.
Thanks in advance!
.......
Code:
.......
At the moment it looks like:
if ( $(clone).attr('name') ){
newid = $(clone).attr('name');
var position = newid.lastIndexOf("[");
newid = newid.substring(0, position)+ '[' + (counter +1) + ']';
$(clone).attr('name', newid);
};
Html field:
<input type="checkbox" value="1" name="options[categories][1][3]">
3 is the category id, 1 is the option I need the category for. The clone script would produce:
<input type="checkbox" value="1" name="options[categories][1][4]">
at the moment - but I need:
<input type="checkbox" value="1" name="options[categories][2][3]">
I think it's a regex problem because the easiest solution would be to search for [categories][anyvalue] and replace it with [categories][counter]
You could use a regular expression to replace the first number in brackets. Like this:
if ( $(clone).attr('name') ) {
var newid = $(clone).attr('name');
newid = newid.replace(/\[[0-9]*\]/, '[' + (counter + 1) + ']');
$(clone).attr('name', newid);
};

Categories