Dave
Dave

Reputation: 3458

Getting form html and its values

Consider this html:

<form onsubmit="alert( $(this).html() );return false">
    <input type='text' name='test'/>
    <input type='submit' value='Submit'/>
</form>

If I type some text in the input box, the value isn't captured by html(). How do I get the raw form html and its input values?

Upvotes: 0

Views: 145

Answers (2)

tkt986
tkt986

Reputation: 1028

using Jquery, you can do like this

<form id='form'>
    <input type='text' name='test' id='name'/>
    <input type='submit' value='Submit'/>
</form>

and jquery code

$(document).ready(function(){
    $('#form').submit(function(){
        alert($(this).find("#name").val());
        return false;
    });
});

Fiddle Code sample

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318798

The value attributes etc are not synchronized with the form elements. You could use code like this though assuming your form only contains input which have a proper value (e.g. no select, checkbox and radio elements)

$('form').submit(function(e) {
    e.preventDefault();
    $(':input', this).each(function() {
        var $this = $(this);
        $this.attr('value', $this.val());
    });
    alert($(this).html());
});

Don't forget to remove the onsubmit code from the HTML. If you have more than one form, replace $('form') with $('#someid') and add id="someid" to your form tag.

Upvotes: 3

Related Questions