Friday, February 1, 2013

How to dynamically insert html code/content into a web page using jQuery?

To dynamically insert html code/content into a web page, we can use ".html(htmlstring)" method of jQuery. Where "htmlstring" is a HTML string which is to be set as content of each and every matched elements.

When we use the method ".html(htmlstring)" to set any element's content, it will not only replace complete content in that element with the new content but also removes other constructs like data and event handlers from child elements before replacing new content.

Internally jQuery uses the browsers "innerHTML" property for this functionality.

Note: We cannot use this method for XML documents.

Inject html code/content using ".html(htmlstring)" method:

$(document).ready(function(){
$("div.button").click(function () {
$(this).html("<input type='button'; value='Button'>");
});
$("div.checkbox").click(function () {
$(this).html("<input type='checkbox' name='check' value='check'>Check Box</input>");
});
$("div.radiobutton").click(function () {
$(this).html("<input type='radio' name='radio' value='radio'>Radio Button</input>");
});
$("div.textbox").click(function () {
$(this).html("<input type='text' name='text' value='text'>Text box</input>");
});
});

Example:

<!DOCTYPE html>
<html>
<head>
<style>     
  div {padding:0px;margin:0px;cursor:pointer;}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("div.button").click(function () {
$(this).html("<input type='button'; value='Button'>");
});
$("div.checkbox").click(function () {
$(this).html("<input type='checkbox' name='check' value='check'>Check Box</input>");
});
$("div.radiobutton").click(function () {
$(this).html("<input type='radio' name='radio' value='radio'>Radio Button</input>");
});
$("div.textbox").click(function () {
$(this).html("<input type='text' name='text' value='text'>Text box</input>");
});
});
</script>
</head>
<body>
<b>Click on the below items to insert html elements:</b><br/>
<div class="button">Click here to insert a Button.</div>
<div class="checkbox">Click here to insert a Checkbox.</div>
<div class="radiobutton">Click here to insert a Radio button.</div>
<div class="textbox">Click here to insert a Textbox.</div>
</body>
</html>

Sample Output:


How to dynamically insert html code/content into a web page using jQuery

Demo:



1 comments:

  1. How is the user supposed to be able to edit these generated fields?

    ReplyDelete

Subscribe via Email