Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single array[0] item is returning undefined

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.

like image 765
Jim41Mavs Avatar asked Mar 07 '23 08:03

Jim41Mavs


2 Answers

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.

like image 98
Rory McCrossan Avatar answered Mar 16 '23 09:03

Rory McCrossan


you have some syntax issues as:

var array = [];

var fullname = $("#firstName").val();
array=fullname.split(" ");
$("#lastName").val(array[1]);
alert(array[1]);
like image 26
kritikaTalwar Avatar answered Mar 16 '23 10:03

kritikaTalwar