Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Get HTML as well as input values

I'm trying to have a variable store the HTML in a div tag, but simply using var a = $('div').html() doesn't store the values of the input tags that lie within the div.

So, my question is, how should I go about saving the HTML and the selected options and values of input tags to a variable using jQuery?

Here is some example code:

HTML:

<div>
  <p>Some Text</p>
  <select name="word">
    <option value="1">Placeholder 1</option>
    <option value="2">Placeholder 2</option>
  </select>
  <input type="text" />
</div>

Javascript:

/* "a" should also have the user values, such that when I use $('body').append(a), 
it has the same user input as the div. */

var a = $('div').html(); 

Thanks in advance.

like image 245
Ivan Avatar asked Jun 28 '11 18:06

Ivan


People also ask

How do I get html using jQuery?

To get HTML content of an element using jQuery, use the html() method. The html() method gets the html contents of the first matched element.

How can get input tag value in jQuery?

jQuery val() method is used to get the value of an element. This function is used to set or return the value. Return value gives the value attribute of the first element.

What does jQuery html () do?

jQuery html() Method The html() method sets or returns the content (innerHTML) of the selected elements. When this method is used to return content, it returns the content of the FIRST matched element. When this method is used to set content, it overwrites the content of ALL matched elements.

Can we get element by value in JavaScript?

Use getElementsByTagName (defined in DOM) to get a list of all input tags, and then filter them in Javascript code (looking at their value attribute).


1 Answers

You could $.clone() the element.

var $a = $("div:first").clone();

$a.appendTo("body"); // Clone invades your body

Online Demo: http://jsbin.com/obebov/edit

like image 106
Sampson Avatar answered Sep 23 '22 09:09

Sampson