ReynierPM ReynierPM - 26 days ago 16
Javascript Question

Switch element types but keeping the same IDs

I need to change the element type dynamically and below is how I am doing it:



$(function() {
$('.click_me').click(function(ev) {
var condition_value_1 = $('#condition_value_1');
var select_html = '<select name="condition_value_1" id="condition_value_1"></select>';
condition_value_1.after().html(select_html);
condition_value_1.remove();
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<input type="text" id="condition_value_1">
<span class="click_me">Click Me</span>





After change the types as you see on the snippet above I should remove the previous element but because they share (and this is mandatory) the same ID then the new SELECT gets deleted. Is there any way to avoid this?

Answer

If you want to replace, you can use replaceWith..

$(function() {
  $('.click_me').click(function(ev) {
    var condition_value_1 = $('#condition_value_1');
    var select_html = '<select name="condition_value_1" id="condition_value_1"></select>';
    condition_value_1.replaceWith(select_html);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<input type="text" id="condition_value_1">
<span class="click_me">Click Me</span>

Comments