Dynamically assigning variable names JavaScript - 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>

Related

Generate automatically variable and get values usign "document.getElementsByClassName"

I'm java script beginner, so do not be angry against me ;)
In order to simplify my code, I would like to generate automatically variables and affect them their current value in order to use them further.
What I have done and works (but I have a lot of changing variable on various documents) :
Html : input a,b,c,... with id a,b,c,...
a = Number($('#a').val());
b = Number($('#a').val());
c = Number($('#c').val());
...
What I'm trying to do :
Html : add a class 'test' to all inputs I want to generate
var elements = document.getElementsByClassName('test');
elementsLength = elements.length;
for (var i = 0 ; i < elementsLength ; i++) {
elements[i].value = Number($("#"+elements[i].id).val());
}
Something must be wrong in the part elements[i].value = Number($("#"+elements[i].id).val());
because when I call the variable a, b or c, it has not been generated.
after the loop,
alert (a);
returns [object HTMLInputElement] instead of the value I would like to get ;(
I'm searching since yesterday, I'm loose.
Thank you for your support guys.
++
Seems you want to persist the value of INPUTS in variable. I would suggest you to create an object i.e. obj and create properties based on input.
var obj = {};
$('button').on('click', function() {
$('.test').each(function() {
obj[$(this).prop('id')] = Number($(this).val());
});
//For debugging
console.clear();
console.log(obj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="a" class="test">
<input type="text" id="b" class="test">
<input type="text" id="c" class="test">
<button type="button">Click me</button>

Get value from hidden field - JavaScript

I have a <input type="hidden" class="Key" value="1m2.123.mds.34g" />
How can I get the value without using jQuery?
With jQuery i just only write:
var parse = $('.Key').attr("value")
alert(parse);
I need this in pure JavaScript, maybe use RegEx? I will execute this script on txt file which will contain such line.
check this
window.onload=function(){
var hidden=document.getElementsByClassName("Key");
alert(hidden[0].value);
}
<input type="hidden" class="Key" value="1m2.123.mds.34g" />
var inputs = getElementsByClassName('Key');
for(var i=0; i<inputs.length;i++) {
console.log(inputs[i].value);
}
Easy! Just use getElementsByClassName. E.g:
document.getElementsByClassName('Key')[0].value
Or if you had to get the value by id you can use getElementById
document.getElementById('idHere').value
Here's 4 ways to get the value of .Key. Also I added a better way to do it in jQuery as well using the method val().
SNIPPET
var k = document.querySelector('.Key').value;
console.log(k);
// This works if .Key is inside a <form>
var e = document.forms[0].elements[0].value;
console.log(e);
var y = document.getElementsByTagName('input')[0].value;
console.log(y);
var s = document.getElementsByClassName('Key')[0].value;
console.log(s);
//BTW there's a better way of finding value with jQuery
var $Key = $('.Key').val();
console.log($Key);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='f1'>
<input type="hidden" class="Key" value="1m2.123.mds.34g" />
</form>
Thank you all. I resolve this problem as follow:
var regEx = /class="Name"+ value="(.*?)"/;
newName = result.match(regEx)[1];
var regEx2 = /class="Key"+ value="(.*?)"/;
var key = result.match(regEx2)[1];
Alert(key + ' ' + newName );

Javascript: How use a loop function to show all the user input in one single alert box?

I'm trying to write a function that will show an Alert Box for all the data entered by the user in the form. I must do it only in simple javascript (sorry no jQuery). My HTML is as follows:
<form method="POST">
<label class="form">Name: </label><input type="text" name="name" id="name"><br>
<label class="form">Address: </label><input type="text" name="address" id="address"><br>
<label class="form">Email: </label><input type="text" name="email" id="email"><br>
<button id="submit" type="submit" value="submit" onclick="showAlert()">
Submit
</button>
</form>
My javascript:
function showAlert() {
var userInputs = document.getElementsByTagName("input");
for (var i=0; i < userInputs.length; i++) {
alert(userInputs.value + " ");
//Basically my idea would be to implement a loop for as many input fields,
//run through all of them, then display ONE SINGLE alert box containing all the
//data entered by the user. But I'm having trouble with how to implement the loop.
}
}
How do I implement the loop?
I have written another function that achieves the same effect but it involved writing a long, tedious list of variables for each input field and I don't want to do that since it's messy:
function alternateShowAlert() {
var name = document.getElementById('name').value;
var address = document.getElementById('address').value;
var email = document.getElementById('email'.value;
alert(name + " " + address + " " + email)
//This function, although it works fine, will be too long and tedious if I have
//more input fields such as age, city, state, country, gender, etc. I want to put
//it in a loop format but how do I do this?
}
function showAlert() {
var userInputs = document.getElementsByTagName("input");
var alertBody = "";
for (var i=0; i < userInputs.length; i++) {
alertBody += userInputs[i].value + " ";
}
alert(alertBody);
}
document.getElementsByTagName() returns an array, so you need to access the elements of the array using their index: userInputs[i].
Or you can use Array.prototype.forEach. See the example below.
function showAlert() {
var userInputs = document.getElementsByTagName("input");
var alertBody = "";
Array.prototype.forEach.call(userInputs, function(element) {
alertBody += element.value + " ";
});
alert(alertBody);
}
You have the logic: you need the loop to collect all info, but should show only one alert, so instead of alert'ing inside the loop, you need to do it after:
function showAlert() {
var userInputs = document.getElementsByTagName("input");
var infos = ""; // Create a string for the content
for (var i=0; i < userInputs.length; i++) {
infos += userInputs[i].value + " "; // Add the info from user input
}
alert(infos); // Show one alert at the end
}
Martin is getting you part of the way there, but I think you'll trip up at getting the values. Document.getElementsByTagName
returns an HTML collection best treated as an array.
So user inputs.value would probably need to be something like userinputs[i].value for Martin's code to work
You can do it in one single line, without any loop:
function Show() {
alert([].slice.call(document.querySelectorAll("input[type='text']")).map(function(x) { return x.id + ": " + x.value; }).join("\n"));
}
Name: <input type="text" id="name" /><br />
Address: <input type="text" id="address" /><br />
Email: <input type="text" id="email" /><br />
<button type="button" onclick="Show();">Show</button>
The method querySelectorAllis supported by all modern browsers (IE 9+) and is the plain JS equivalent to jQuery selectors. However, it returns a node list which should be converted to plain array in order for us to use the desired .map() method to get all the values easily.

Dynamic variable creation using eval 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]);

Get values of all textboxes with same name attributes in jquery

I need to get values of all textboxes with same name attributes using jquery.
<input type="text" id="text1" name="text[]">
<input type="text" id="text2" name="text[]">
<input type="text" id="text3" name="text[]">
How can I get all values of textbox text[] and compare it using jquery.
I tried using
var values = $("input[name='text[]']")
.map(function(){return $(this).val();}).get();
but am no successful.
You can use map method and store the values into an array.
$(function(){
var values = $('input[name="text[]"]').map(function(){
return this.value
}).get()
})
http://jsfiddle.net/UugWW/
This one should work :
$('input[name="text[]"]');
You can loop on it to get all values.
$('input[name="text[]"]').each(function() {
alert($(this).val());
});
Let's split the requirement into smaller problems.
First you want to select all those inputs.
var $inputs = $("input[name='text[]']")
It returns a jQuery object, containing all the input named text[].
You also might not need to use square brackets into the name.
var inputs = $inputs.get();
Extract the matching elements into a plain Array, so that we can now access Array's prototype methods, such as Array.prototype.map.
var values = inputs.map(function takeValue(input) {
return input.value;
});
Use a selector like this:
$('input[type="text"][name="text[]"')
var textboxcount = document.getElementsByName("text").length;
var textvalue="";
for (var i = 0; i < textboxcount ; i++) {
textvalue= textvalue + document.getElementsByName("text").item(i).value;
}
alert(textvalue);

Categories