javascriptjqueryselection-api

Delete characters from my last focused text field when div in pressed


I have a div (button) that when is pressed it deletes the characters of an specific text field. Now I am trying to change the code in a way that delete the characters of the last focused text field.

This is the code that only delete the characters of one text field:

$(".delete").on("mousedown",function(evt) {
        var nameInput = document.querySelector("#name")
        var cursorPosition = nameInput.selectionStart;

    $("#firstName").val(
        function(index, value){
            return value.substr(0,cursorPosition - 1) + value.substr(cursorPosition);
    });

    nameInput.selectionStart = cursorPosition - 1;
    nameInput.selectionEnd = cursorPosition - 1;

    return false;
});

And this is what I haver for now:

$(".delete").on("mousedown",function(evt) {

    var lastFocused;
    $(".item").focusout( function(e) {
      lastFocused = e.target;
    });

    var cursorPosition = lastFocused.selectionStart;

    lastFocused.val(
        function(index, value){
            return value.substr(0,cursorPosition - 1) + value.substr(cursorPosition);
    });

    lastFocused.selectionStart = cursorPosition - 1;
    lastFocused.selectionEnd = cursorPosition - 1;

    return false;
});

The HTML:

<div class="delete key-btn">
<input id="firstName" name="firstName" type="text" class="item" required/>
<input id="firstName" name="firstName" type="text" class="item" required/>

In console, I'm getting the error: "Cannot read property 'selectionStart' of undefined". Can someone please tell me how to achive this? Thanks


Solution

  • This works:

    // 1. this has to be declared globally
    var lastFocused;
    
    // 2. you need to set the event handler for the 'item' elements outside of the delete handler
    //    I'd also suggest using the 'focus' event here instead of 'focusout'
    $(".item").focus(function(e) {
        lastFocused = e.target;
    });
    
    $(".delete").on("mousedown", function(evt) {
        // 3. need the null check if none of the inputs have been focused yet
        if (!lastFocused) {
            return;
        }
    
        var cursorPosition = lastFocused.selectionStart;
    
        // 4. need to wrap this in the jQuery function to use val()
        $(lastFocused).val(
            function(index, value){
                return value.substr(0,cursorPosition - 1) + value.substr(cursorPosition);
        });
    
        lastFocused.selectionStart = cursorPosition - 1;
        lastFocused.selectionEnd = cursorPosition - 1;
    
        return false;
    });