Reputation: 18660
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?
Upvotes: 0
Views: 43
Reputation: 1086
use the name attribute instead of the id to delete
$(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);
$('[name="ElementNameHere"]')[0].remove();
});
});
note that this will only delete the first entry it gets into when searching the DOM.
Upvotes: 1
Reputation: 24191
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>
Upvotes: 5