Link to home
Start Free TrialLog in
Avatar of tonelm54
tonelm54

asked on

.on blur

Im trying to get an .on blue to fire when the user leaves a input field which was changed on click of a cell of a table. Ive managed to easily get the cell to change from a text value to a input box via:-
$(document).on("click", ".requiredInput", function (e) {
	var textVal = $(this).text();
	$(this).html('<input class="cellInputChanged" type="text" value="' + textVal + '" />');
});

Open in new window


But my problem is turning it back, which Ive done as:-
$(document).on("focusout", ".cellInputChanged", function () {
	var textVal = $(this).text();
	$(this).parent().html(textVal );
});

Open in new window


Which I cannot get to fire at all, no errors, it doesnt seem to attach an event onto the blur event, even though Im using .on which from my knowledge should listen for future elements to match

Any ideas what Im doing wrong?
Avatar of tonelm54
tonelm54

ASKER

I forgot to attach the jsFiddle url to this, sorry:-
https://jsfiddle.net/zxhxsoz2/
Avatar of Alexandre Simões
HEre you go:
$(document).ready(function () {
    $(document).on("click", ".requiredInput", function (e) {
        var textVal = $(this).text();
        
        var $elem = $('<input class="cellInputChanged" type="text" value="' + textVal + '" />');
        $(this).html($elem);
        $elem.focus();
        
        
    });
    
    $(document).on("blur", ".cellInputChanged", function () {
        var textVal = $(this).val();
        $(this).parent().html(textVal);
    });
    
});

Open in new window


https://jsfiddle.net/AlexCode/zxhxsoz2/2/

Basically you need to set the focus to the textbox after you add it.
Also you weren't getting the textbox value properly.
ASKER CERTIFIED SOLUTION
Avatar of Alexandre Simões
Alexandre Simões
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
There's one more thing to consider.
To avoid accidental double-click to empty your values, consider toggleClass ".requiredInput" from the parent td.
Also consider keep using text() instead of html() to avoid security issues:
$(document).ready(function () {
    $(document).on("click", ".requiredInput", function (e) {
        var textVal = $(this).text();
        $(this).removeClass('requiredInput');
        var $elem = $('<input class="cellInputChanged" type="text" value="' + textVal + '" />');
        $(this).html($elem);
        $elem.focus();

    });

    $(document).on("blur", ".cellInputChanged", function () {
        var textVal = $(this).val();
        $(this).parent().text(textVal).addClass('requiredInput');
    });


});

Open in new window


when adding the class back you can also perform validation and / or. add additional css class to show correct edits or updated values.