0

I have a text box in a div:

<div id="divTest">
    <input type="text" id="txtText">
</div>

Suppose the user types a word into the text box, I want a jquery method of getting the textbox HTML with the value that the user typed in. I have tried the below code:

$('#btnTest').click(function(){
    alert($('#divTest').html());
    e.preventDefault();
});​

But this only gives me the HTML of the textbox, not the HTML + the value of the text within the textbox.

Here is a jsFiddle of the problem.

3
  • Do you want the html of the input too? Commented Apr 26, 2012 at 19:37
  • Yes, I want the HTML of the input with the embedded value Commented Apr 26, 2012 at 19:38
  • you mean something like (only IE) .outerHTML Commented Apr 26, 2012 at 19:55

2 Answers 2

1
var html_input = $("#divTest").html();
var val = $("#txtText").val();
var input = html_input.slice(0,-1) + " value='" + val + "'>";
alert(input);
Sign up to request clarification or add additional context in comments.

3 Comments

Ok, that does work for this one example. But it doesn't scale to other input elements or if there are multiple input elements in the div.
@Coltech: Ok, you didn't say multiple inputs. Just use .each() and get the val and html and input for each case.
@Coltech: You can use split() to split the html_input for the '>' separator in the string returned by $("#divTest").html() into an array, and retrieve html_input for each case using the index of $("#divTest :input").each(function(index) {etc.})
0
var html = $('#divTest').html();
var value = $('#divTest').val();
var message = html + value;

3 Comments

That won't work, you would be appending the value to the HTML, which would look something like <input type="text" name="name" />value He is looking for <input type="text" name="name" value="value" />
Sorry that wont work, that just concatenates the input value onto the end of the HTML. I want the HTML with the embedded value so it will render properly.
I don't think there is a function to extract both values and html at the same time. I would get the html, declare and array, loop through each character of the html until you get the '>' , then you add "Value =" value and concatenates what's left of the characters.

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.