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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With