ray
ray

Reputation: 8699

Can I save dynamic form with html() rather than iterating through INPUTs?

I have a dynamically created HTML page which adds inputs.

I want to be able to capture the page (and all form input values) using the html() function.

This does not seem to work though. Take the following page for example:

<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$( document ).ready(function() {
        $( "#_create" ).click(function() {
            var myHtml = '<input class="my-input" val="">';
            $('#_input').html(myHtml);
        });
        $( "#_save" ).click(function() {
            alert($('#_masterDiv').html());

        });
        $( "#_saveIterate" ).click(function() {
            $("input").each(function(){
                alert(this.value);
            });
        });
    });
</script>
</head>
<body>
    <button id="_create">Create Dynamic Input</button><br>
    <button id="_save">Save by grabbing html</button><br>
    <button id="_saveIterate">Save by iterating</button><br>
    <div id="_masterDiv">
        <div id="_input">Input button here</div><br>
    </div>
</body>
</html>

Clicking "Save by grabbing html" gets the form, but does not get the values. Clicking "Save by iterating" gets the value of the input.

Do I need to call a function like "apply changes" before I can get the most current values in INPUT?

Upvotes: 0

Views: 627

Answers (1)

WebNovice
WebNovice

Reputation: 2220

Some browsers like Firefox/Chrome does not save the current state of HTML input values. So you will have to assign the input values manually:

$( document ).ready(function() {
        $( "#_create" ).click(function() {
            var myHtml = '<input class="my-input" value="">';
            $('#_input').html(myHtml);
        });
        $( "#_save" ).click(function() { 
         //if you have many input fields, loop through them all           
            $("input").each(function(){                
                //set the value manually
                this.setAttribute('value', this.value);                
            });            
            alert($('#_masterDiv').html());

        });
        $( "#_saveIterate" ).click(function() {
            $("input").each(function(){
                alert(this.value);
            });
        });
    });

Here's the jsfiddle link: http://jsfiddle.net/urspz/1/

Upvotes: 1

Related Questions