Benjamin W Benjamin W - 9 days ago 5
Javascript Question

Javascript button click trigger keypress and add text into input text

<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?

Answer

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>