I am trying to do some inline editing using jquery. The problem i am having is when i create the input text, i cannot change the text. I can not even seem to get focus. It seems like its readonly or disabled. The $( “.sr-label” ).live(“click” is still being called when i try to click in the text field. Do i need to do some kind of unbind or something?
Thanks for any help
<ul>
<li><span class='sr-label'>label 1</span></li>
<li><span class='sr-label'>label 2</span></li>
</ul>
my js looks like
$( ".sr-label" ).live("click", function(event){
console.log("sr-label");
var $item = $( this ),
$target = $( event.target );
var $pitem = $item.parent();
newHTML = '<input id="label_'+$pitem.attr('id')+'" type="text" size="30" '+
' value="'+$item.text()+'"><input class="saveedit" '+
' id="save_'+$pitem.attr('id')+'" type="button" value="save">'+
' <input id="canedit" type="button" value="cancel">';
$item.html(newHTML);
return false;
});
Click events on elements inside the span propagate up to the span and cause your handler to run again. And your handler replaces the entire contents of the span each time it runs. So it’s not that the input is readonly or disabled, it is that clicking on it removes and recreates it.
You’ll notice that if you tab into the input with the keyboard then you can type in it since keypresses don’t trigger your click handler.
Well you can’t really unbind
.live()in a way that stops it applying to certain elements with that class and not others. If you’d bound individual handlers with.click(),.bind()or the non-delegated form of.on()then you could unbind them one by one.What you can do instead is change your selector so that it will only apply for elements that don’t have any child input elements:
Demo: http://jsfiddle.net/H2ncm/2/
However, you should note that
.live()is deprecated, so (unless you’re stuck with a really old version of jQuery for some reason) you should switch to the delegation version of the.on()method:When a click on
documentoccurs jQuery tests whether it was on an element that matches the selector in the second parameter and if so calls your function (otherwise does nothing). Note that ideally you won’t usedocument, you’ll use an element much closer to the elements in question, e.g., your containingulelement.Demo: http://jsfiddle.net/H2ncm/1/
This is sort of equivalent to adding a simple test within the handler to do nothing if the clicked span already contains inputs:
Demo: http://jsfiddle.net/H2ncm/