Reputation: 7240
I have the following label:
<div id="email">
<label>
[email protected]
</label>
<i class="fa fa-edit"></i>
</div>
<div id="phone">
<label>
1234567890
</label>
<i class="fa fa-edit"></i>
</div>
When I click on the edit button I want to replace the label with an input and set the label value as selected. Below is what i have tried so far:
$('.fa-edit').click(function(){
var info = $(this).closest('div');
var label = info.find('label');
var curr_value = label.text();
label.replaceWith('<input class="edit_input" type="text" value="'+curr_value+'" />')
.focus(function(){
//alert(this);
this.select();
});
// some code ..
the problem is that I can not set the input text as selected (ready to be replaced). What should I do?
Upvotes: 1
Views: 64
Reputation: 2691
Create the input element and set the focus & select on it after you replace the label.
Please check the below code:
$("#editBtn").click(function(){
var label = $(this).parent().find('label');
var curr_value = label.text().trim();
var newInput = $('<input class="edit_input" type="text" value="'+curr_value+'" />')
label.replaceWith(newInput)
newInput.focus().select()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="email">
<label>
[email protected]
</label>
<button id="editBtn">EDIT</button>
</div>
Upvotes: 3
Reputation: 4327
the value returned from .replaceWith is still the old <label />
reference, you need to re-select the input, so that you can focus it.
label.replaceWith('<input class="edit_input" type="text" value="'+curr_value+'" />')
$('.edit_input').off('focus').on('focus',function() {
this.select()
}).trigger('focus')
use off() to remove previous event listener everytime the user click the edit button again.
Upvotes: 1
Reputation: 179
i hope that help you.
var label = $('label');
var curr_value = label.text();
label.replaceWith('<input class="edit_input" type="text" value="'+curr_value+'" />').focus(function(){
$(this).select(); });
Upvotes: 0