Dynamically set global JS variables - javascript

I am wondering on how to dynamically set JS values. To better understand what I am trying to accomplish, here's a php example:
$first;
$second;
$third;
$my_array = ('first' => 'val_1','second' => 'val_2','third' => 'val_3');
foreach ($my_array as $key => $value){
$$key = $value;
}
let's say you have a ton of input boxes with a unique ID in html form and you want to use the id as a global variable using jquery or js, that's when I am a bit confused how I can dynamically assign already defined global variables from an Each statement.
The type of html I want to identify through js.
<input id='first' value='val_1'>
<input id='second' value='val_2'>
<input id='third' value='val_3'>
The JS/jquery code
var first;
var second;
var third;
$('input').each(function(){
var item_id = $(this).attr('id');
var item_value = $(this).attr('value');
/* now what... */
});
in the php example the extra dollar sign make the dollar to say I want to populate a variable named like the variable stored in $key. I am wondering if the same can be accomplished with JS or jquery.
The purpose is to manage the amount of values only by adding inputs to the HTML form without the need for altering the JS code considerably.

This isn't good programming style in PHP or JavaScript. Just use an array instead:
var values = [];
$('input').each(function() {
var item_id = $(this).attr('id');
var item_value = $(this).attr('value');
values[item_id] = item_value;
});
console.log('first = ' + values['first'] + ', second = ' + values['second']);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="first">First: </label>
<input id="first" type="text" value="hello" />
<label for="second">Second: </label>
<input id="second" type="text" value="world!" />
<label for="third">Third: </label>
<input id="third" type="text" />

You can use eval function
var first;
var second;
var third;
$('input').each(function(){
var item_id = $(this).attr('id');
var item_value = $(this).attr('value');
eval(item_id+'='+item_value);
});
For example
var v1 = 'first';
var v2 = 'second';
var val1 = 10;
var val2 = 20;
var first;
var second;
eval(v1+'='+val1);
eval(v2+'='+val2);
console.log('first='+first,'second='+second);

Related

I want to increase a value when some checkboxes are checked

I want to increase the price if one or more check boxes are checked. Here is the code i have but it does not work
HTML
<input type="checkbox" value="15" />Checkbox
<br/>
<br/>
<span id="result"></span>
JAVASCRIPT
var a=0;
window.onload = function () {
var input = document.querySelector('input[type=checkbox]');
function check() {
var a = a+value;
document.getElementById('result').innerHTML = 'result ' + a;
}
input.onchange = check;
check();
}
You've scoped your a variable away in the check function, and you're calling the function check without the proper "this".
This should work
var a = 0;
window.onload = function() {
var input = document.querySelector('input[type=checkbox]');
function check() {
a = a + parseInt(this.value, 10);
document.getElementById('result').innerHTML = 'result ' + a;
}
input.onchange = check;
input.onchange();
}
your variable "a" is in global scope when you have initialized it on the top var a = 0; If you want to use it, you can directly do a = a + 1.
When you declare it again as a var inside check function, it is now a new variable "a" bound to the check function scope as a new variable and its not referring to the variable declared at the top.
So the solution is remove declaration var and directly use it as a = a + 1 inside check function.
Also you need to check if checkbox is checked :
here is a working fiddle : https://jsfiddle.net/1m09z0cg/
There are a couple of things wrong.
First, querySelector will only return the first element that matches the selector, if you want to get all checkboxes you'll have to use querySelectorAll.
Second, you're using var a = a+value; if you want to add value to the previous value of the global variable a you should use a = a+value;, by using var a = ... you're declaring a new variable a in the current context.
Third, there is no variable value, if you're trying to get the value of the clicked element use event.currentTarget.value.
var checkboxes = Array.from(document.querySelectorAll("input[type='checkbox']"));
var result = document.querySelector("#result");
checkboxes.forEach(function(checkbox){
checkbox.onchange = function(){
var total = checkboxes.reduce(function(a, c){
return a + (c.checked ? parseInt(c.value):0);
}, 0);
result.textContent = "Result " + total;
}
});
<input type="checkbox" value="15" />Checkbox
<br/>
<input type="checkbox" value="15" />Checkbox 2
<br/>
<input type="checkbox" value="15" />Checkbox 3
<br/>
<br/>
<span id="result">Result 0</span>

Count values from <input type="text"

Hello i want to count the ids inside a input type="text"
the values return as this 1,4,6 etc
<input type="hidden" class="selected_ids" value="selected_ids" name="selected_ids[]" multiple="yes" id="selected_ids" />
here the only javascript version :
var testme = function() {
var myInput = document.getElementById('selected_ids');
var myValue = myInput.value;
var myCount = myValue.split(',').length;
document.body.innerHTML += '<br>myValue = ' + myValue + ' | myCount = ' + myCount;
}
<input type="text" class="selected_ids" value="1,4,6" name="selected_ids[]" multiple="yes" id="selected_ids" />
<button onclick='testme()'>test me</button>
You can use split function. for example :
var curval = document.getElementById('selected_ids').value;
var curval_arr = curval.split(',');
var cnt = curval_arr.length;
First, your input type needs to be text and not hidden. It's not possible to enter values in a hidden text box.
So your text box should be :-
<input type="text" class="selected_ids" value="selected_ids" name="selected_ids[]" multiple="yes" id="selected_ids" />
Now suppose the user enters 1,4,6 into the text box(make sure the numbers are separated by a comma). Then on the PHP side you can access as follows.
<?php
$array = explode(',', $_POST['selected_ids']); //this array consists all the elements.
//To get length, do :-
count($array);
?>

How to create an array from inputs?

I created multiplied input fields:
<div class="form-text-field first-name field-group">
<input data-index="1" type="text" id="firstName1" class="signup-input firstName" name="first[1]" placeholder="">
</div>
<div class="form-text-field email field-group">
<input type="text" data-index="1" id="inputMail1" class="signup-input text-value ignore" name="email[1]" placeholder="${message(code:"signup.redesign.placeholder.eg.email")}"/>
<span class="common-sprite disNone sign-up-cross first clone"></span>
</div>
I have a code in the JS file which clone every input.
I have to create arrays from the values of the inputs (one for the email, and one for the first name).
Here is the function:
var arrEmail = []
var arrName = []
function add() {
var obj = {};
var partner = {}
$('.email input[type="text"]').each(function() {
obj[this.data-index] = this.value;
});
arrEmail.push(obj)
$('.first-name input[type="text"]').each(function() {
partner[this.data-index] = this.value;
});
arrName.push(partner)
console.log(arrEmail[0])
}
I didn't succeed to get the arrays in this code. How do I fix it?
You have some mistakes.
Wrong syntax in line $('.email input[type="text"]').each(function({. You forgot to close bracket.
I don't understand why you tried get value this strange manner. You included jQuery. Use it!
I fix your code.
var arrEmail = [];
var arrName = [];
function add() {
var obj = {};
var partner = {};
$('.email input[type="text"]').each(function(item) {
obj[$(this).data('index')] = $(this).val();
});
arrEmail.push(obj);
$('.first-name input[type="text"]').each(function() {
obj[$(this).data('index')] = $(this).val();
});
arrName.push(obj);
console.log(arrEmail);
console.log(arrName);
}
$('#test').on('click', add);
jsFiddle demo
Upd #1
Haven't shown all conditions. Fixed it.
Use $(this).data('index') instead of this.data-index
You can handle this with a single array:
var myUsers= [];//this might be object that you store the user information
$('.first-name input[type="text"]').each(function(item) {
//first create the user information
var myUser = new Object();
myUser.Username = $(this).val();
myUser.Email= $(this).next().val();
//then add the user information to the myUsers array
myUsers.push(myUser );
});

Dropdown auto populate into text on a page (non-input field)

I am trying to make a dropdown choice populate multiple selections, but not as an input field.
Here is an example as input fields, but I am not sure how to alter this to make just text on a page via [strong] / [div] or something.
http://jsfiddle.net/zunrk/
var ids = new Array();
var use = new Array();
var ful = new Array();
ids[0] = "";
use[0] = "";
ful[0] = "";
ids[1] = 6;
use[1] = "bsmith";
ful[1] = "Buddy Smith";
ids[2] = 2;
use[2] = "lsmith";
ful[2] = "Libbie Smith";
ids[3] = 4;
use[3] = "asmith";
ful[3] = "Andy Smith";
function Choice() {
//x = document.getElementById("users");
y = document.getElementById("selectUsers");
//x.value = y.options[y.selectedIndex].text;
document.getElementById("ids").value = ids[y.selectedIndex];
document.getElementById("use").value = use[y.selectedIndex];
document.getElementById("ful").value = ful[y.selectedIndex];
}
<form name="form1" method="post" action="">
<select id="selectUsers" name="users" onChange='Choice();'><option> </option>
<option value="1">bsmith</option>
<option value="2">lsmith</option>
<option value="3">asmith</option>
</select>
<p>ids <input type="text" id="ids" name="id" ></p>
<p>use <input type="text" id="use" name="username" ></p>
<p>ful <input type="text" id="ful" name="full_name" ></p>
</form>
You can use any element instead of <input />, for example a <span />. The difference is you set its .innerHTML[1], not .value, so use
<p>ids <span id="ids"></span></p>
and
document.getElementById("ids").innerHTML = ids[y.selectedIndex];
to set the HTML of an element instead of value of an input.
http://jsfiddle.net/zunrk/171/
[1] innerText/textContent would be a better choice, but it could introduce unnecessary complexity
use innerHtml property of the dom element
document.getElementById("ids").innerHTML = ids[y.selectedIndex];
Details:
http://www.w3schools.com/jsref/prop_html_innerhtml.asp
If you want to initialize the array the way you have done then instead of setting each array item individually you can set it as below.
var ids = new Array();
var use = new Array();
var ful = new Array();
ids=["",6,2,4];
use=["","bsmith","lsmith", "asmith"];
ful=["","Buddy Smith","Libbie Smith", "Andy Smith"]
Other than this my answer is not much different than what pawel suggested, but its a bit of a cleaner solution... its not great code by any mean but it's a good piece considering that you are beginner and i wouldn't like to make it too complex. Enjoy coding :) => http://jsfiddle.net/zunrk/172/

from a html form to javascript

I have a form that requires three inputs as follows:
<form>
<input name="mn"
type="number"
min="1"
value="1">
<input name="mx"
type="number"
min="2"
value="10">
<input name="step"
type="number"
min="1"
value="1">
<input onclick="myfunc()"
type="submit"
value="calculate">
</form>
all i require is to be able to access the three fields directly in javascript. I do not need to pass the information anywhere else.
Could anyone point me in the right direction? I have read examples where there has been one input, but not multiple.
<script type="text/javascript">
function myfunc() {
var mn = document.getElementsByName("mn")
var mx = document.getElementsByName("mx")
var step = document.getElementsByName("step")
alert((mn + mx) / step)
}
</script>
Give your form an id like so
<form id="myForm">
The other thing to watch out for is that the is that the value attribute is a string so adding the two values concatenates them rather than summing them.
Try instead
var frm = document.forms["myForm"];
var _mn = parseInt( frm["mn"].value );
var _mx = parseInt( frm["mx"].value );
var _step = parseInt( frm["step"].value );
var result = ( _mn + _mx ) / _step;
I'd start with giving each input an id then i could use:
var min = document.getElementById('mn')
and so on. To access the value you simply would call
min.value
Also there is no point in removing the i from min and the a from max. That is not optimized just hard to read and understand.
Try this:
<script type="text/javascript">
function myfunc() {
var mn = document.getElementsByName("mn")[0].value;
var mx = document.getElementsByName("mx")[0].value;
var step = document.getElementsByName("step")[0].value;
var top = mn / mx;
alert(top / step);
}
</script>
if u need to access to the values of the inputs change your code to:
function myfunc() {
var mn = document.getElementsByName("mn")[0];
var mx = document.getElementsByName("mx")[0];
var step = document.getElementsByName("step")[0];
// you may need to validate your values here, like step.value != 0
alert((mn.value + mx.value) / step.value)
}

Categories

Resources