Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the value of a dynamically created text box with jQuery

Using the following code

var newDiv = $(document.createElement("div"));
var newTextBox;

newTextBox = $(document.createElement("input"))
    .attr("type", "text")
    .attr("id", "textbox")
    .attr("name", "textbox");

newTextBox.val("text");
newDiv.append(newTextBox);
alert(newDiv.html());

I get the following

<input name="textbox" id="textbox" type="text">

I get the same thing with

$("#textbox").val("test");

Using

newTextBox = $("<input/>");

Doesn't help either

Where is my value?

EDIT: SOLTUION

So, further up in the stack I was converting the DOM I built to a string and since - like munch mentioned - the dynamic value doesn't get added to the tag, it wasn't showing up.

Thanks for the help

like image 658
Mason Avatar asked Jan 29 '10 00:01

Mason


1 Answers

jQuery will not put the value into the created element's generated html. Both .attr('value', 'blah') and .val() get the current value of what's been entered or changed in the text input, and allow you to see that value when you look at the input on the page or submit it to the server. However, you will not see it when looking at the html.

You can still manipulate the value all you want, you just won't see any changes in firebug, like you do with class changes, styling, etc.

AFAIK, this is the same without using jQuery. The same thing happens with:

document.getElementById('textbox').value = 'my text'; 

The value attribute is only to set something's value from the server. It's not needed with javascript.

Also, it depends on the type of input that you're using. For example, you will see the value attribute changes with a hidden input, but not with the textbox.

EDIT:

By appending newDiv to the body, the text box and the value show up using your code. Here's a test page. You can see both the code and the preview of what happens. The alert though, does not show any 'value' attribute for reasons explained above.

like image 125
munch Avatar answered Sep 22 '22 20:09

munch