0
<input class="foo" type="text" />
<button>click</button>

$('button').click(function(){
    var e = $.Event('keypress');
    e.which = 65; // Character 'A'
    $('.foo').trigger(e);   
});

I try to trigger a keyboard event and add text into input text.

for some reason, I cant use = html or text(), I must trigger keyboard event

anyone know how to fix this?

1
  • 1
    input has value (or in jQueryland where things have to be different, just for the sake of being different, val ) - not text or html Commented Nov 30, 2016 at 4:22

1 Answer 1

2

TRY like this : String.fromCharCode(e.which) .Add to the input use with $(element).val() .No need to use trigger event .simply load data to element. its enough.

$('button').click(function(){
    var e = $.Event('keypress');
    e.which = 65; // Character 'A'
    $('.foo').val(String.fromCharCode(e.which));   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="foo" type="text" />
<button>click</button>

Another answer for contentEditable

$('button').click(function(){
    var e = $.Event('keypress');
    e.which = 65; // Character 'A'
    $('.foo').text(String.fromCharCode(e.which));   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo" contentEditable="true" ></div>
<button>click</button>

Sign up to request clarification or add additional context in comments.

2 Comments

This won't trigger keypress event :
also no need of creating event object also

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.