Single array[0] item is returning undefined - javascript

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 [ ]

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>

javascript array multidimension search index

I have an array in javascript. I've been trying to search the index but it is very frustrating. There is an object inside an array, and inside the object have an array as a value.
This is what the source code looks like:
rows = [{"id":"id0","cell":["array1","array2"]},{"id":"id1","cell":["array3","array4"]}];
I've tried this:
var v = {cell:["array1","array2"]};
rows.indexOf(v)
And also have a radio button:
<input type="radio" name='array' value="array1, array2">
jQuery here:
var i = $("input:checked").val().split(',');
rows.indexOf(i)
which has an index result of -1
Try this. It's a functional approach that loops through each index in rows, and returns true if there's a match.
var rows = [{"id":"id0","cell":["array1","array2"]},{"id":"id1","cell":["array3","array4"]}];
var index = rows.findIndex(function(i) {
return JSON.stringify(i.cell) == JSON.stringify(["array1","array2"])
});
console.log(index);
The output should return 0. The reason we need to convert both objects into JSON.strings is because of how javascripts handles the equality of two objects. You can read more about it here.

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.

Using indexof value to return a value in a second array using Javascript

I'm trying to take a user's prompt to find the index position of an item in an array
and retrieve the value of that same index position in a second array.
var arrayStars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var arrayConstellations = ["Ursa Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Minor", "Leo"];
function starSearch(param) {
var matchingConstellation = arrayConstellations[arrayStars.indexOf("param")];
return matchingConstellation;
}
var userInput = prompt("Enter a star name");
starSearch(userInput);
When I enter text in the prompt there is no response.
I've tried logging to the console after every line to see what output there is if any and it all seems to work but for some reason it doesn't give the intended result.
I've even replaced one of the array values into the line
var matchingConstellation = arrayConstellations[arrayStars.indexOf("Vega")];
And that returns the proper index item from the second array. It just doesn't seem to display a result when everything is together.
remove the quotes
arrayStars.indexOf("param")
to
arrayStars.indexOf(param)
you're searching for the string literal param, not whatever the variable param contains
FIDDLE

Javascript key value array storing

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;
});

Categories