Reputation: 321
What I am trying to do is when I put the email address like [email protected], [email protected], etc, and I hit on the space, I want to check that if the cursor is at the end of the input text before I could add HTML in the element.
if (selectionEndofText) {
if (e.which == 32) {
$('#oI').append('<div class="vR"><span class="vN" data-hovercard-name="'+name+'" data-hovercard-email="'+email+'" data-hovercard-owner-id="137"><div class="vT">'+name+'</div><div class="vM"></div></span><input name="to" type="hidden" value="<'+name+'>"></div>');
$('.vR').insertBefore('#domodal_email_receipt');
$('#domodal_email_receipt').val('');
}
}
Full code:
$(document).on('keydown', '#domodal_email_receipt', function(e) {
var fullname = $(this).val();
var name = fullname.split(' <');
var selectionEndofText = $(this).val().length;
var name = name[0];
var email = '';
if (fullname.indexOf('<') > -1) {
email = fullname.split('<');
email = email[1].replace('>', '');
}
alert("selectionEndofText................."+selectionEndofText);
//if (!selectionEndofText)
if (e.which == 32) {
$('#oI').append('<div class="vR"><span class="vN" data-hovercard-name="'+name+'" data-hovercard-email="'+email+'" data-hovercard-owner-id="137"><div class="vT">'+name+'</div><div class="vM"></div></span><input name="to" type="hidden" value="<'+name+'>"></div>');
$('.vR').insertBefore('#domodal_email_receipt');
$('#domodal_email_receipt').val('');
}
});
Upvotes: 0
Views: 1999
Reputation: 5411
In addition to checking space keyword in the if statement, you can also check the caret position with .selectionStart
that returns a number. So, if the current position is equal to the length, that means it is in the end of the input.
To clear the input, use a setTimeOut
to make it run last. Otherwise, there will be a space inside it.
if (e.which == 32 && selectionEndofText === this.selectionStart) {
$('#oI').append('<div class="vR"><span class="vN" data-hovercard-name="'+name+'" data-hovercard-email="'+email+'" data-hovercard-owner-id="137"><div class="vT">'+name+'</div><div class="vM"></div></span><input name="to" type="hidden" value="<'+name+'>"></div>');
$('.vR').insertBefore('#domodal_email_receipt');
setTimeout(function(){
$('#domodal_email_receipt').val('');
}, 0);
}
Upvotes: 1