Welcome to WebmasterWorld Guest from 23.22.17.192

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)

5+ Year Member



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 Sep 24, 2013 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member



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 Sep 24, 2013 (gmt 0)

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



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 Sep 24, 2013 (gmt 0)

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




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 Sep 24, 2013 (gmt 0)



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