user3225440 user3225440 - 2 months ago 7
HTML Question

Losing text after a space setting the value in a new field

I am having an odd issue when using Javascript to create a new field. To sum it up, I have button that when clicked will create two text fields. I give those text fields a string as a value. However, it is only working correctly if I give it a string with no spaces. If my string contains a space, then it makes the value equal to the text before the space occurs.

function nameField() {
$('#nameArea').html("<br/>First Name:<input type='text' id='fnField' value=" + $('#firstName').text() + ">Last Name:<input type='text' id='lnField' value=" + $('#lastName').text() + "></input><button id='bName' onclick='updateName(fnField.value, lnField.value)'>Save Changes</button>");

So for example, if the firstName value is "David E", it is currently only putting "David" in the field as the value. However, I have used alert and can confirm that $('#firstName').text(); does contain the full "David E". How can I make sure that the text after the space doesn't get slashed out?


The issue is because you don't have any string delimiters around the value. Try this:

$('#nameArea').html('<br/>First Name:<input type="text" id="fnField" value="' + $('#firstName').text() + '">Last Name:<input type="text" id="lnField" value="' + $('#lastName').text() + '"></input><button id="bName" onclick="updateName(fnField.value, lnField.value)">Save Changes</button>');

Note the " around the values of the value attribute.