Javascript key value array storing - javascript

I am here today with a question to do with key value pair arrays.
my html is as follows
<input type="checkbox" class="data" id="task_checked" value="1" email="a#a.com">
<input type="checkbox" class="data" id="task_checked" value="2" email="b#b.com">
I would like to store the following data as an array like below:
"1" => "a#a.com"
"2" => "b#b.com"
My Javascript currently is as follows:
var newTasksArr = new Array();
$("#task_checked:checked").each(function() {
var email = $(this).attr("email");
var id = $(this).val();
newTasksArr['id'] = email;
});
Perhaps I am using the Jquery .each() wrong, could someone shed some light in to my question please?
Thank you for you reading.
Regards.

Two issues :
In Javascript, an Array may only have sequential, numeric keys. If you want to use strings as keys, you want an Object.
If you want to insert an element with a key equal to the value of id, then you want newTasksArr[id] = email; without the quotes.

You're almost right, you just need to remove the quotes around 'id' so that it uses the value the id variable contains, instead of the literal string 'id'.
You should also use an object ({}) instead of an array ([]).
var newTasks = {};
$("#task_checked:checked").each(function() {
var email = $(this).attr("email");
var id = $(this).val();
newTasks[id] = email;
});

Avoid duplicating Ids in your markup. The following should help, however you might want to tweek the jquery selector to include a context.
var arr = {};
$('input:checked').each(function() {
var $t = $(this);
var email = $t.attr("email");
if (!email) {
// you may wish to do something if email is missing
}
var id = $t.val();
if (!id) {
// deal with the error
}
arr[id] = email;
});

Related

Is it possible to break an "each" iteration, append or add something to one of the values and then continue?

Is it possible to break an "each" iteration, append or add something to one of the values and then continue?
var aKeys = new Array(),
aValues = new Array(),
sArray = {};
$(input).each(function (index, element) {
var sKey = $(this).attr('name'),
sValue = $(this).val();
aKeys.push(sKey);
aValues.push(sValue);
});
As you can see, I'm first creating a few arrays and an empty object named "sArray". Then I'm pushing the values inside those arrays via input attributes. Finally, I'm creating my object:
aKeys.forEach(function (v, j) {
sArray[v] = aValues[j];
});
return sArray;
But here's the thing. I want to add a nested object inside one of those values. I already have that object stored in another variable. Is there a way to append it or add it?
EDIT:
I've been looking at the examples and maybe I didn't express myself quite well. I've already created an object. What I wanna do is to append or store another object inside one of the keys of this object I've created.
sArray is an object, not an array. You don't need the arrays ata ll to build the object. Try this...
var sObj = {};
$("input").each(function (index, element) {
sObj[$(this).attr('name')] = $(this).val();
});
// Let's nest another object in there i guess...
var myObj = {"wut-wut": "in the butt"};
sObj.pickles = myObj;
console.log(sObj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name=one value=1>
<input name=two value=2>
<input name=three value=3>
<input name=four value=4>

Combine Strings coming from different inputs

I have some inputs with data-attributes
<form>
<input style="width: 300px" data-schrift="SchriftEins" name="input1" id="input1" /></br></br>
<input style="width: 300px" data-schrift="SchriftEins" name="input2" id="input2" /></br></br>
<input style="width: 300px" data-schrift="SchriftZwei" name="input3" id="input3" /></br></br>
</form>
and i need to combine the values of the inputs with the same data-attributes
i create an array inputs that should store the results at the end like this:
[SchriftEins: "from first input & from second input", SchriftZwei: "from third input "]
At the moment I have something like this:
var inputs = new Array();
$("form").on("keydown",function(e){
$("form :input").each(function(){
var schrift = $(this).data("schrift");
var value = $(this).val();
inputs[schrift] = value;
});
console.log(inputs);
});
this code will overwrite the value how can i fix this?
thanks alot!
Like others have mentioned, you'll probably want to use an object instead of an array. You'll also want to use keyup, and make sure you aren't appending new data to old data. Something like this should work:
JavaScript
var inputs = {};
//this should use keyup instead of key down
$("form").on("keyup",function(e){
//inputs needs to be reset, otherwise the next keyup will continue to append the values to old data
inputs = {};
$("input").each(function(i){
var schrift = $(this).data("schrift");
var value = $(this).val();
//if the property has already been set, append the next matching schrift, otherwise just set the property to the schrift
inputs[schrift] = inputs[schrift] == null ? value : inputs[schrift] + ' ' + value;
});
console.log(inputs);
});
Some notes:
Changed the array to an object, as others have also mentioned.
Changed keydown to keyup, because on keydown the character entered will not yet be available, so the inputs variable will always be one character behind what the user has entered
Reset the inputs object each time the user enters information. This prevents the loop from appending new data to the existing old data.
Added the ternary operation to append the value to an existing property, if one exists.
You can see it working here: https://jsfiddle.net/axp1nxom/2/
Hope that helps!
I think you wanted to use an object not an array there.
Try defining the variable input like this:
var inputs = {};
And you will see a result like you wanted. More on objects: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object
If you really want an array will will have to use .push to add. You can see more about arrays here https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array
Edit: Also I see that 2 inputs have the same data-schrift value "SchriftEins". This will overwrite one over the other.
You are overwriting what the value is. What you are wanting it sounds like is a dictionary type of object. Try the following if you want an array:
var inputs = new Array();
$("form").on("keydown",function(e){
$("form :input").each(function(){
var schrift = $(this).data("schrift");
var value = $(this).val();
inputs.push(value);
});
console.log(inputs);
});
Or if you want a dictionary with named keys and values:
var obj = {
key1: value1,
key2: value2
};
$("form").on("keydown",function(e){
$("form :input").each(function(){
var schrift = $(this).data("schrift");
var value = $(this).val();
obj[schrift] = value;
});
console.log(inputs);
});
Then use it like the following:
var myValue = obj[schrift];
Hopefully this helps in what you were needing.

How to get all elements with class name in list form in javascript

I have multiple email inputs:
<input type="text" class="email" value="{{email}}">
And I want to retrieve each email input and put them all in one list:
var names = $(".email").val();
But right now I only get the first value instead of the full list. What's wrong?
You can use $.map to create an array of the values.
var names = $.map($(".email"), function(e) {return e.value});
jQuery.each function will help you,
var email array = [];
jQuery(".email").each(function{
email_array[email_array.length] = jQuery(this).val();
#you can any operation in this block
});
now, you have all email in email_array
I'm guessing you're looking for a string list?
Try the "each" function!
var names = "";
$(".email").each(function(){
if(names != ""){
names += ", ";
}
names += $(this).val();
});
console.log(names);

How to convert input name to JavaScript array

I have an issue related to converting html inputs names to a javascript object.
For example I have an input:
<input type="checkbox" name="product[1]">
<input type="checkbox" name="product[2]">
and I have javascript code:
var data = {};
$('input').each(function(){
// need to do something like
data[$(this).attr('name')] = $(this).attr('checked');
})
I expect to get data object like this;
data = {
product: {
1: 'checked',
2: 'checked'
}
}
Is this possible without using regular expressions?
Replacing your variables with literal values, you get this:
data["product[1]"] = true;
The square brackets have no meaning as they are inside a string, so you won't get any result.
There are ways around this. You could use eval: eval("data."+this.name+" = "+(this.checked?"true":"false"));
However since eval is best avoided, try this:
var m = this.name.match(/(.*)\[(\d+)\]/);
data[m[0]][m[1]] = this.checked;
Yes in general it is possible. You can do the following:
var noregexp = $(this).attr('name').split("[");
if (noregexp.length==2) {
//should be
var the_name = noregexp[0];
var the_index = noregexp[1].substr(0,noregexp[1].length-1); //this will get the index with removed ]
}
I made this up from my mind. It's not a beautiful solution but one without regexp as you wished.
You can get a data structure the way you need using:
var data = {product: []};
$('input').each(function(){
data.product[$(this).attr('name').match(/product\[([\d]*)\]/)[1]] = $(this).prop('checked');
})
console.log(data);
Check thid demo

Show javascript array value in input type hidden

I have a question regarding Javascript array.
I have the following javascript array:
var startTimeList= new Array();
I've put some values in it. Now I have the following input (hidden type):
<input type="hidden" value"startTimeList[0]" name="startTime1" />
Hoewever, this is obviously not correct because the javascript array is not recognized in the input hidden type. So I cant even get one value.
Does anyone know how I can get a value in the input type from a javascript array?
You need to set the value in Javascript:
document.getElementById(...).value = startTimeList[0];
Use this :
<script>
window.onload = function() {
document.getElementsByName("startTime1")[0].value = startTimeList[0];
}
</script>
You have to set value from javascript.
Something like document.getElementById (ID).value = startTimeList[0];
You execute javascript from body oload event.
You need to set the value through JavaScript itself so.
document.getElementById("startTime1").value = startTimeList[0];
Or JQuery
$("#startTime1").val(startTimeList[0]);
Assign "startTime1" as the id above.
You can find your element by name with:
document.getElementsByName(name)[index].value = 'new value';
OR
You should identify your element and then change the value;
Give your element an ID for example id="ex"
Get the element with JavaScript(of course once the DOM is ready) with var element = document.getElementById('ex')
Change the value with element.value = 'your value';
You'd need to split the array into a delimited string and then assign that string to the value of the hidden input.
Then, on postback or similar events you'd want to parse the value back into an array for use in JavaScript:
var startTimeList = [1,2,3,4,5];
var splitList = '';
for(var i = 0; i < startTimeList.length; i++)
{
splitList += startTimeList[i] + '|';
}
and back again:
var splitList = '2|4|6|8|';
var startTimeList = splitList.split('|');

Categories