1

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>'); }); 
1
  • Because you are selecting a html tag within the DOM. You should post infos on your DOM if you want some more helpl. Commented Jun 9, 2016 at 15:27

1 Answer 1

2

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>'); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script> <input type="text" id="student_firstname" value="fn" /> <input type="text" id="student_lastname" value="fn" /> <button id="x">Click me</button> <ul></ul>

Sign up to request clarification or add additional context in comments.

1 Comment

No problem, glad to help :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.