Jessica Mather Jessica Mather - 5 months ago 157
jQuery Question

Why is the value of my input this [object HTMLInputElement]?

I can't figure out why it is not printing out the value of my

<input type="text">
?

$('#x').click(function() {
var firstname = $("#student_firstname").val();
var lastname = $("#student_lastname").val();

$("ul").after('<li style="display:list-item; padding:5px; border:2px solid black" name="c[]"><strong>First Name</strong> ' + student_firstname + ', <strong>Last Name</strong> ' + student_lastname + '</li>');
});

Answer

The cause of your issue is because your variables are named firstname and lastname, not student_firstname and student_lastname. When you use those names, Javascript retrieves the elements with those id attributes and returns them. In this case they are HTMLInputElements, and when coerced to strings give the output you see.

Also note that you should use append() not after() to add the li to the ul.

Here's a working version of your code:

$('#x').click(function() {
    var firstname = $("#student_firstname").val();
    var lastname = $("#student_lastname").val();

    $("ul").append('<li style="display:list-item; padding:5px; border:2px solid black" name="c[]"><strong>First Name</strong> ' + firstname + ', <strong>Last Name</strong > ' + lastname + ' </li>');
});

Working example

Comments