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
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.
var newDiv = $(document.createElement("div"));
var newTextBox = $('<input />')
.attr("type", "text")
.attr("id", "textbox")
.attr("name", "textbox")
.val("my text"); // <-- You can use here...
newTextBox.val("my text"); // <-- or here
newDiv.append(newTextBox);
alert(newDiv.html());
With a little hack you can do it ..
var newDiv = $('<div/>');
var newTextBox;
newTextBox = $('<input/>')
.attr("type", "hidden")
.attr("id", "textbox")
.attr("name", "textbox");
newTextBox.val("text");
newDiv.append(newTextBox);
newTextBox.each(function(){this.type='text';});
alert(newDiv.html());
1st define its type as hidden, because this will allow the value attribute, and then using code change it to text ..
$("#element")[0].setAttribute("value","newvalue");
One can also do this
var chip = document.createElement("div");
chip.innerHTML="some value here"
card.appendChild(chip)
精彩评论