Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
148
rated 0 times [  150] [ 2]  / answers: 1 / hits: 23725  / 11 Years ago, sat, may 4, 2013, 12:00:00

I am developing web app, I have such a requirement that whenever user click on text inside span i need convert it into input field and on blur i need to convert it back to span again. So i am using following script in one of my jsp page.



Java Script:



<script type=text/javascript>
function covertSpan(id){

$('#'+id).click(function() {
var input = $(<input>, { val: $(this).text(),
type: text });
$(this).replaceWith(input);
input.select();
});

$('input').live('blur', function () {
var span=$(<span>, {text:$(this).val()});
$(this).replaceWith(span);

});
}


JSP Code:



<span id=loadNumId onmouseover=javascript:covertSpan(this.id);>5566</span>


Now my problem is, everything works fine only for the first time. I mean whenever i click on the text inside span for the first time it converts into input field and again onblur it coverts back from input field to normal text. But if try once again to do so it won't work. Whats wrong with above script?


More From » jquery

 Answers
22

Would be good to change your dom structure to something like this (note that the span and the input are side by side and within a shared parent .inputSwitch



<div class=inputSwitch>
First Name: <span>John</span><input />
</div>
<div class=inputSwitch>
Last Name: <span>Doe</span><input />
</div>


Then we can do our JS like this, it will support selecting all on focus and tabbing to get to the next/previous span/input: http://jsfiddle.net/x33gz6z9/



var $inputSwitches = $(.inputSwitch),
$inputs = $inputSwitches.find(input),
$spans = $inputSwitches.find(span);
$spans.on(click, function() {
var $this = $(this);
$this.hide().siblings(input).show().focus().select();
}).each( function() {
var $this = $(this);
$this.text($this.siblings(input).val());
});
$inputs.on(blur, function() {
var $this = $(this);
$this.hide().siblings(span).text($this.val()).show();
}).on('keydown', function(e) {
if (e.which == 9) {
e.preventDefault();
if (e.shiftKey) {
$(this).blur().parent().prevAll($inputSwitches).first().find($spans).click();
} else {
$(this).blur().parent().nextAll($inputSwitches).first().find($spans).click();
}
}
}).hide();

[#78431] Friday, May 3, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tina

Total Points: 91
Total Questions: 106
Total Answers: 104

Location: Vanuatu
Member since Fri, May 13, 2022
2 Years ago
tina questions
;