简体   繁体   中英

Need to trigger a space keydown event when on button click using jquery

I need to trigger a space keydown event inside a text box when a button is clicked so that a space is achieved inside the text box using jquery

My code which i have Tried

var idz, valz;
$(document).ready(function () {
    $(document).delegate('#getRuleStr', 'click', function () {
        $('#' + idz).val($('#preTag').text());
        var e = jQuery.Event("keydown");
        e.which = 32;
        $('#' + idz).trigger(e);
    });
    $(document).delegate('.rulez', 'click', function () {
        idz = this.id;
        valz = $('#' + idz).val();
    });
});

If you want to add the space in text box then you can achieve this by

$('#' + idz).val( $('#' + idz).val()+" ");

But If you don't want to use this approach then post your complete code with html.

If you need to insert a character programatically into input element taking into account a caret position you can do this

$('.rulez').on('click', function () {
  var caret = document.getElementById(idz).selectionStart;
  var txtVal = jQuery('#' + idz).val();
  var characterToAdd = " ";
  jQuery('#' + idz).val(txtVal.substring(0, caret) + characterToAdd + txtVal.substring(caret) );
});

Note that line in your code

$('#' + idz).val($('#preTag').text());

will rewrite value in $('#' + idz) element and set caret position to end so there is no need to take caret position into account and thus there is no need to calc anything so you can just append space char to input element value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM