javascript - Call function on 'Enter' press -
here html code:
<div class="panel-footer"> <div class="input-group"> <input id="btn-input" class="form-control input-sm chat_input message" type="text" placeholder="write message here..." ng-model="messagetosend"> <span class="input-group-btn"> <button id="btn_chat" class="btn btn-primary btn-sm btn_chat" value="79">send</button> </span> </div> </div>
and here jquery code:
$('.message').keypress(function (e) { if (e.which == 13) { var msg = $(this).val(); var id = $(this).closest('span').next('button.btn_chat').val(); alert(id+" "+msg); sendmessage(msg,id); } e.preventdefault(); });
here send message function:
var sendmessage = function(messagetosend,id) { // $log.debug(messagetosend); id = parseint(id); if(messagetosend.length != 0){ $http.post('/chat/send/',{message:messagetosend,chat_room_id:id}).then(function (response) { $log.debug(response.data); $('input.message').val(""); }); } };
now want call sendmessge
function in it, when enter button press after message written.
but when press enter button jquery not run. how can solve problem?
angular provides mechanism, can create form
, use ngsubmit
bind function execute when form submitted.
so, when enter pressed form submitted.
html
<div class="panel-footer"> <div class="input-group"> <form ng-submit="sendmessage(messagetosend, 79)"> <input id="btn-input" class="form-control input-sm chat_input message" type="text" placeholder="write message here..." ng-model="messagetosend" /> <span class="input-group-btn"> <button id="btn_chat" class="btn btn-primary btn-sm btn_chat" value="79">send</button> </span> </form> </div> </div>
add method in controller
$scope.sendmessage = function(messagetosend,id) { // $log.debug(messagetosend); id = parseint(id); if(messagetosend.length != 0){ $http.post('/chat/send/',{message:messagetosend,chat_room_id:id}).then(function (response) { $log.debug(response.data); $('input.message').val(""); }); } };
if don't want use form
, can use ngkeyup
<input ng-keyup="$event.keycode == 13 ? sendmessage(messagetosend, 79): null" ng-model="messagetosend" >
Comments
Post a Comment