Question

I'm trying to change the text inside a <span> when any data is entered to its related <input> field. So I'm using the following script.

jQuery(".selector").live({
    'paste keyup input' : function () {
        var val = $(this).val();
        var dest_class = $(this).attr('class') + '_' + $(this).attr('dest');
        $('.' + dest_class).html(val);
    },
    change: function () {
        var id = $(this).attr('id') + " option:selected";
        var val = $("#" + id).text();
        var dest_class = $(this).attr('class') + '_' + $(this).attr('dest');
        $('.' + dest_class).html(val);
    }
});

The code is working almost properly. The problem I'm facing is with the first event. When any listed even is occurring in the <input class="cell_value" ...> the html of the destination is changing like it should, but the moment I click outside or press TAB all the changes made to the destination <span> disappears.

If I press Enter then the value stays in the destination but only untill I edit the input again.

The second event i.e. "change" is working fine.

Any suggestion about what I'm doing wrong.

here is the fiddle link for this http://jsfiddle.net/k6ru4/1/

Was it helpful?

Solution

It is because of your selector, it fires the change event in both the input and select elements, but the change event handler is designed to handle the input element that is the problem

$(".selector").live({
    'paste keyup input change' : function () {
        var val, $this = $(this); 

        if($this.is('select')){
            val = $this.find('option:selected').text();
        } else {
            val = $this.val();
        }

        var dest_class = $(this).attr('class') + '_' + $(this).attr('dest');
        $('.' + dest_class).html(val);
    }
});

Demo: Fiddle

OTHER TIPS

In your change handler, you are using .text() where you should have used .val(). Tabbing out after changing the content causes the textbox to fire a change event.

Correct code should be:

....
'change' : function () {
    ...
    var val = $("#" + id).val(); // val() instead of text()
    ...
}
....

Demo: http://jsfiddle.net/k6ru4/4/

Use append() on change function instead of html()

$('.' + dest_class).append(val);

http://jsfiddle.net/k6ru4/5/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top