I am trying to toggle between span and input text field using on function but I need some help in finding out what I am doing wrong.
I have created a fiddle for it here
UI
<div>
<span >My value here!</span>
</div>
JS
var focusInName = '';
var focusOutName = '';
$(function () {
$("document").on("click",".span", function () {
var input = $('<input />', {'type': 'text', 'name': 'aname', 'value': $(this).html()});
$(this).parent().append(input);
$(this).remove();
input.focus();
focusInName = $(this).html();
alert(focusInName);
});
$('document').on('blur',".input", function () {
$(this).parent().append($('<span />').html($(this).val()));
$(this).remove();
focusOutName = $(this).val();
alert(focusOutName);
});
});
You should change the version of the jquery to 1.9 And change the class to html element like this:
$(document).on("click","span", function () {
//codes
}
And same for the input field:
$(document).on('blur',"input", function () {
//codes
}
Edit
If you want to set the classes to the html elements you can do as follows:
var focusInName = '';
var focusOutName = '';
$(function () {
$(document).on("click",".sp", function () {
var input = $('<input class="box" />', {'type': 'text', 'name': 'aname','value': $(this).html()});
$(this).parent().append(input);
$(this).remove();
input.focus();
focusInName = $(this).html();
alert(focusInName);
});
$(document).on('blur',".box", function () {
$(this).parent().append($('<span class="sp" />').html($(this).val()));
$(this).remove();
focusOutName = $(this).val();
alert(focusOutName);
});
});
I would recommend you to use simple contenteditable
<span contentEditable="true">My value here!</span>
You need to use jQuery 1.7+ as $.fn.on()
as it was added in 1.7
HTML , Initially add the required class ie span
to your element
<span class='span'>My value here!</span>
Code :
var focusInName = '';
var focusOutName = '';
$(function () {
$(document).on("click", ".span", function () {
focusInName = $(this).html();
var input = $('<input />', {
'type': 'text',
'name': 'aname',
'value': $(this).html(),
'class': 'input' //Add the CSS class while creating element
});
input.focus();
$(this).parent().append(input);
$(this).remove(); //Always remove at the end
alert(focusInName);
});
$(document).on('blur', ".input", function () {
focusOutName = $(this).val();
var span = $(
'<span />', {
'class': 'span', //Add the CSS class while creating element
'html': $(this).val()
});
$(this).parent().append(span);
$(this).remove(); //Always remove at the end
alert(focusOutName);
});
});
The modified Fiddle
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.