Search code examples
javascriptjqueryhtmlinputkeypress

Insert keypress in input value


Hi i have a problem with insert value in input

You might ask why I did put keypress input field with JS? I have the compiled program emscripten and it has driver input that intercepts all keypress, keydown, keyup and returns false for other element on page. That blocks all input fields on page. I have no way to fix this in the emscripten program, and I decided to fix it by jQuery on html side

   jQuery(function() {
        var $input = jQuery("#search-area228");
        $input
            .attr("tabindex", "0")
            .mousedown(function(e){ jQuery(this).focus(); return false; })
            	.keypress(function(e){
					var data = jQuery(this).val
				var text = String.fromCharCode(e.keyCode || e.charCode)
				for(var i = 0; i < text.length; i++)
				jQuery(this).val(text[i])
		  return false; });
		 
	});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="search-area228">
This will unlock the input field, but the problem is that allows you to write only one character and when you click on the following replaces it! Please, help !


Solution

  • Just add the new text to the pre-existing text in that field which you already defined (in a wrong way) as data and didn't use it

    when you call the method val of an input you should use it with braces jQuery(this).val() NOT jQuery(this).val because this is a function method of jQuery not a variable.

    jQuery(function() {
            var $input = jQuery("#search-area228");
            $input
                .attr("tabindex", "0")
                .mousedown(function(e){ jQuery(this).focus(); return false; })
                	.keypress(function(e){
    					var data = jQuery(this).val();
    				var text = String.fromCharCode(e.keyCode || e.charCode)
    				for(var i = 0; i < text.length; i++)
    				jQuery(this).val(data + text[i])//<<< here
    		  return false; });
    		 
    	});
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <input type="text" id="search-area228">