Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 140190

jQuery.html() function does not preserve values in selects and inputs in dynamic DOM

$
0
0

I have content generated by PHP, but changed dynamically by jQuery. DOM is generated based on user's choises and I need all inputs, selects etc. be saved when user choose any option which re-generate DOM. For that I use .html() function. The problem is that only values, which were inserted by PHP are copied. Values which were set by .val() function or typed by user himself are lost when used .html(). I tried even .clone() function, but result is the same.

I have DOM similar to:

<div id="number_of_persons">
    <select>
        <option value="1">1</option>
        <option value="2" selected>2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select>
</div>
<div id="placeholder">
    <div id="person1">
        Name: <select><option value="">Name A</option><option value="">Name B</option></select>
        <div id="person1_placeholder">... another dynamically generated inputs ...</div>
    </div>
    <div id="person2">
        Name: <select><option value="">Name A</option><option value="">Name B</option></select>
        <div id="person2_placeholder">... another dynamically generated inputs ...</div>
    </div>
</div>

When user change number of persons, for example from 2 to 3, I need first and second be saved (yes, the solution in this case would be use .append(), but the real DOM is quite complicated and whole #placeholder need to be regenarated). So I am using function simliar to:

$('#number_of_persons').on('change', function() {
    var html = '';
    for(var i = 1; i <= $(this).val(); i += 1) {
        html += '<div id="person' + i + '">';
        html += 'Name: <select><option value="">Name A</option><option value="">Name B</option></select>';
        // the line below is the problem, because all selects and inputs lost their values set by user or via jQuery .val() function
        html += '<div id="person' + i + '_placeholder">' + ($('#person_' + i + '_placeholder').html() || '') + '</div>';
        html += '</div>';
    }
    $('#placeholder').html(html);
});

How to ensure copying values from selects and inputs in #personX_placeholder?


Viewing all articles
Browse latest Browse all 140190


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>