views:

51

answers:

1

I have a webpage with different controls. I have to get html source on button click for a particular div element's controls with values.

jQuery .html() method gives me html source of controls without values, but I require html source with user selected values.

+3  A: 

Try iterating over each <input> and setting it's value attribute to it's DOM value before accessing the html.

jsFiddle: http://jsfiddle.net/AWK9S/3/

$('form input').each(function()
{
    this.setAttribute('value',this.value);
    if (this.checked)
        this.setAttribute('checked', 'checked');
    else
        this.removeAttribute('checked');
});

$('form select').each(function()
{
    var index = this.selectedIndex;
    var i = 0;
    $(this).children('option').each(function()
    {
        if (i++ != index)
            this.removeAttribute('selected');
        else
            this.setAttribute('selected','selected');
    });
});

$('form textarea').each(function()
{
    $(this).html($(this).val());
});

jsFiddle: http://jsfiddle.net/AWK9S/3/

Andrew Dunn
I'd use `$(':input')` instead as `input` doesn't match `<select>` elements and such. Assuming this sol'n works. **Edit:** Actually... `select` doesn't have a `value` attribute does it? Hrm... this would take some work to code it for all input types.
Mark
what about select and other elements...
Brij
Now works for `<select>` and `<textarea>` form elements...
Andrew Dunn
Not working in Firefox
Brij
Sorry about that, jQuery must handle attributes incorrectly, I replaced it with DOM functions. It's not as pretty, but at least it works. http://jsfiddle.net/AWK9S/1/
Andrew Dunn
Awesome !!! Great Job Man..
Brij
Now works with checkboxes and radio buttons too. http://jsfiddle.net/AWK9S/3/
Andrew Dunn
I have already developed for checkbox and radio button
Brij