15

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.

3 Answers 3

29

You could $.clone() the element.

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

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

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

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! I completely forgot about .clone(). Just tested it, works great.
The selected option in the <select> tag doesn't get cloned.
@Ivan Are you saying the <option/> no longer exists, or is not selected?
Not selected (Sorry for the confusion).
@Ivan You'll have to set the $.val() of the clone based upon the $.val() of the original. $clone = $orig.clone().val($orig.val()).appendTo("body");
7

You may also achieve this by first changing the value of input fields uding DOM like this:

$('div input').each(function(){
    $(this).keyup(function(){
        $(this).attr('value',$(this).val());
    });
});

after which you can extract the HTML by using this:

$('div').html();

1 Comment

For using select as well: if($(this).is('select')) { $(this).find('option:selected').attr('selected', 'selected'); } else { $(this).attr('value', $(this).val()); }
0

If the document having Ajax content, the best solution would be:

$(document).on("keyup change", "input", function () {
    $(this).attr("value", $(this).val());
});

You must use both change and keyup event.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.