Welcome to WebmasterWorld Guest from 54.196.74.142

Forum Moderators: open

Message Too Old, No Replies

How to insert html elements using html() jQuery method

     
1:19 pm on Sep 24, 2013 (gmt 0)

Full Member

5+ Year Member

joined:Dec 12, 2007
posts:233
votes: 0


Hi,
I'm trying to insert a select html element in a div section of a web page by clicking a link whose href property containts a hash (#). To my big surprise, after the click on the link, the select element appears on the page but the source code of the generated page does not contain any <select>...</select> tags in the appointed div.

I do this by selecting the div element like this:
var $select = $('<select><option value="1">Option1</option></select>');
$('#cent').html($select);
div#cent is written manually and I want to add the select element inside of it. What is the problem for the html() method? It shows the expected result on the page but fails to insert real select tags on the page. Subsequent action on the select element by for exemple a server language (ex PHP) yields no result as the select element do not exist physically on the page. What can I do to see the inserted tags on the page?

Thanks for your precious help
1:45 pm on Sept 24, 2013 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Nov 3, 2005
posts:1585
votes: 0


Try

var select = '<select><option value="1">Option1</option></select>';
$('#cent').html(select);

I think you need pass in the html as text, rather than a jQuery object.
1:47 pm on Sept 24, 2013 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
posts: 5003
votes: 20


You will never see client side (JavaScript) generated elements appear in the source (I assume you mean by doing View > Source in the browser), because the "source" hasn't actually changed. However, if you use something like a DOM inspector, you will see the element in the DOM (DOM stands for Document Object Model). Form elements added to the DOM can be submitted to the server side (PHP, etc.) as long as the element is within the <form></form> tags and is named.

In your example, though, you've forgotten to give the select element a name, and therefore it will not get submitted to the server.
1:53 pm on Sept 24, 2013 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
posts: 5003
votes: 20



I think you need pass in the html as text, rather than a jQuery object.

Either seems to work, but you're right, the documentation [api.jquery.com] does say that the html method takes an HTMLString.
2:54 pm on Sept 24, 2013 (gmt 0)

New User

joined:Sept 24, 2013
posts:2
votes: 0


You could use the .append() method if you do want to pass it as an object.