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.
Related
all devs smarter than me,
So basically I've got a name(first) input field, I want to let the user enter their first name and last name into that input. After that, I want to take the 2nd value(last name) and push the value into another input which is hidden(display:none). So the code below, in theory, should do it
var array = [];
var fullname = $("#firstName").value.split(" ");
array.push(fullname);
$("#lastName").value = array[1];
alert(array[1])
For example iI i put in "First Last" as the name values in the firstName input and split and push to array, if I alert it alert(array) or $("#lastName").value = array, it does push the correct values, however when I try to alert or set only the 2nd part of the array[1] it keeps coming back as undefined!? Please enlighten me my friends.
Firstly, jQuery uses the val() method to retrieve the value of a form element. Attempting to access the value property will return nothing.
That aside, your issue is because you're creating a nested array by pushing the result of split() (ie. an array) in to array:
var fullname = $("#firstName").val().split(" ");
var array = [];
array.push(fullname);
console.log(array)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="firstName" value="Foo Bar" />
Instead, just work with the result of split() directly, without calling push():
var fullname = $("#firstName").val();
var array = fullname.split(' ');
console.log(array[1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="firstName" value="Foo Bar" />
This is obviously a basic example. You would also need to ensure that the resulting array has at least 2 elements in it.
you have some syntax issues as:
var array = [];
var fullname = $("#firstName").val();
array=fullname.split(" ");
$("#lastName").val(array[1]);
alert(array[1]);
You want to push an array values to an array, instead of array.push(fullname);, use
array.push.apply( array , fullname);
or
array = array.concat(fullName);
In your code, use $("#lastName").val() instead of $("#lastName").value. You are using array[] instead of array constructor(). E.g: var a = array[1] returns 1 which means value of a
= 1.
Kindly check the link: Difference between new Array() and [ ]
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>
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;
});
These are my many checkboxes and I need to grab the selected ones on a save and create an array/string of numbers that will be saved.
<asp:CheckBox ID="4" runat="server" ClientIDMode="Static"/>
Do I need to add a value with a number so that i can get the number that the checkbox is so i can get something like "1,4,8,9"(checkboxes selected) or can I get it from ID?
I was looking at something like this as an example:
$(function(){
$('#btnClick').click(function(){
var val = [];
$(':checkbox:checked').each(function(i){
val[i] = $(this).val();
});
});
});
EDIT:
Is there a way to get the checkboxes specifically by starting ID as to not get every single one from the page?
You can use .push on Array's like so:
val.push(this.id);
Here is an example: http://jsfiddle.net/dpMp2/3/
or
you can just do this:
var val = $.makeArray($(':checkbox:checked'));
information on makeArray can be found here: http://api.jquery.com/jQuery.makeArray/
note as am not i am stated below, the array will be objects and you will have to get the id or value from each obj. Read the docs for more info.
I would use map
$(':checkbox:checked').map(function(){ return $(this).val(); })
Since val is an object, so you'll have to use push function to assign the data.
$(function(){
$('#btnClick').click(function(){
var val = [];
$(':checkbox:checked').each(function(i){
val.push($(this).val());
});
});
});
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('|');