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
This works: