I had this code and was working fine, just notices that the ‘event.keyCode’ is depricated as VScode saying
consumer.subscriptions.create("CommentsChannel", {
connected() {
// Called when the subscription is ready for use on the server
},
disconnected() {
// Called when the subscription has been terminated by the server
},
received(data) {
console.log(data.content)
$('#comments').append('<strong>' + data.content[1] + ': ' + '</strong>' + data.content[0] + ' ' + data.content[2] + ' <hr class="comments-hr">' )
// Called when there's incoming data on the websocket for this channel
}
});
var submit_messages;
$(document).on('turbolinks:load', function() {
submit_messages()
})
submit_messages = function (){
$('#new_comment').on('keydown', function (event){
if(event.keyCode === 13){
$('#send_button').click()
event.target.value = ''
event.preventDefault()
}
})
}
so i chagnged it to
submit_messages = function (){
$('#new_comment').on('keydown', function (event){
if(event.key === 'Enter'){
$('#send_button').trigger( "click" )
event.target.value = ''
event.preventDefault()
}
})
so the problem i face now with the both options above is that the input doesn’t get cleared after i press the button or clear press enter
if use this
$('#comment_field').val('')
and press enter i don’t get the value at all but i do when i click the button
this is the model
def self.post_comment(new_comment,ticket,user)
ticket.comment.tap do |post_new_comment|
post_new_comment.content << new_comment
post_new_comment.username << user
post_new_comment.sendtime << Time.now
if post_new_comment.save
ActionCable.server.broadcast 'comments_channel', content: [new_comment, user, Time.now.strftime("%H:%M:%S")]
end
end
end
the input field
<%= f.text_field :comment, class: "form-control", placeholder: "Write a Comment", id: "comment_field" if @ticket.status%>
and the button
def submit_comment_button
content_tag(:button, class: "btn btn-sm btn-primary", id: "send_button") do
content_tag(:i, class: "bi bi-arrow-right-square") do
end
end
end
Advertisement
Answer
The solution i found was to move
$('#comment_field').val('')
at received(data)
like that
received(data) {
console.log(data.content)
$('#comments').append('<strong>' + data.content[1] + ': ' + '</strong>' + data.content[0] + ' ' + data.content[2] + ' <hr class="comments-hr">' )
// Called when there's incoming data on the websocket for this channel
$('#comment_field').val('')
}
});
var submit_messages;
$(document).on('turbolinks:load', function() {
submit_messages()
})
submit_messages = function (){
$('#new_comment').on('keydown', function (event){
if(event.key === 'Enter'){
$('#send_button').trigger( "click" )
//$('#comment_field').val('')
//event.target.value = ''
event.preventDefault()
}
})
}
if someone could explain why i have to make that change and why it was working before i would be glad!

