Reputation: 9152
I am using Jquery for my web application and I am creating a numeric updown box. For this I am replacing an input <input type="text">
field with a pre defined div.
Thing is I want to get the html of the original input box as it may have styles etc added that I would like my .replaceWith
version to have also.
e.g.
Current code <input type="text">
New Code
<div>
<input type="text">
<div>
<!-- Other Stuff -->
</div>
</div>
So as you can see I need to regenerate the input control along side making a parent element. The way I do this at present is just regenerate everything and use the .replaceWith()
method to paste it all.
Any Ideas?
Upvotes: 1
Views: 177
Reputation: 150020
jQuery's .html()
returns empty if you use it on an <input>
element because it has no content, only attributes.
Thing is I want to get the html of the original input box as it may have styles etc added
You can get the style
and class
attributes of the original input box and then apply them to your generated <div>
element, e.g., something like this:
$("someselectorforyournewdiv").addClass( $("input").attr("class") );
// and/or
$("someselectorforyournewdiv").attr( "style", $("input").attr("style") );
(Obviously adjusting the selectors to suit.)
But won't your generated element have its own styles to make a nice "updown box"? If you apply the original styles from the input as well it might not work too well, unless you pick out certain styles that won't affect the shape, like the colour or that sort of thing.
Upvotes: 1
Reputation: 21191
An <input />
element is not a container, therefore it will not have an HTML value. If you're after the text that was entered in the box, use the .val()
method instead.
Upvotes: 0
Reputation: 2070
Probably you are using a wrong selector
give your input or whateever an id and then do like
$('input#yourid').replaceWith('Insert your desired html');
Reference JQuery API
Upvotes: 0
Reputation: 45083
Elements of type input
don't really contain HTML, but rather, the input
tag would be the HTML contained within its parent container (div
in this case). So what you might consider is placing it in a dedicated inner container and remove and replace it in that.
Upvotes: 1
Reputation: 165951
I'm not entirely sure what you're trying to do, but it looks like you want to wrap a parent div
around the input
, and add another div
after it. If that's the case, you can do something like this:
$("input").wrap("<div></div>").after("<div></div>");
This way, you don't need to replace the input
, as it will stay in the DOM. wrap
will wrap the argument around the selected element, and after
will insert content after the selected element.
Here's a working example.
Upvotes: 3