How to enable ENTER button to send messages - javascript

How can I make the enter button instantly send a message with this script? I tried other solutions on the site, but I did not manage to code it myself.
$(document).ready(function () {
$("#send_massage").click(function () {
$("#send_massage").addClass("disabled");
var variabila = $("#text-massage").val();
var mesaj = "massage=" + variabila;
$.ajax({
type: "POST",
url: "/ajax/chat.php",
cache: false,
data: mesaj,
success: function (test) {
$("#text-massage").val('');
//$("#success").show("fast").delay(900).hide("fast");
$("#success").html(test);
$("#send_massage").removeClass("disabled");
}
});
});
});

You can try using the keyup function to bind the event on an element (like the document) to your function. In the function, you check the type of the first parameter (e) and see if it is the keyup event. If it is, only continue if enter key was pressed (keyCode of 13):
if(typeof e.type !== 'string' || (e.type == 'keyup' && e.keyCode != 13)) {
return;
}
Try clicking on and typing in different keys in the example below. You'll see that both enter key and clicking on the button will cause call to be made:
function sendMessage(e) {
$("#send_massage").addClass("disabled");
if(typeof e.type !== 'string' || (e.type == 'keyup' && e.keyCode != 13)) {
return $('#status').html('no call');
}
$('#status').html('made call');
var variabila = $("#text-massage").val();
var mesaj = "massage=" + variabila;
$.ajax({
type: "POST",
url: "/ajax/chat.php",
cache: false,
data: mesaj,
success: function (test) {
$("#text-massage").val('');
//$("#success").show("fast").delay(900).hide("fast");
$("#success").html(test);
$("#send_massage").removeClass("disabled");
}
});
}
$(document).ready(function () {
$("#send_massage").click(sendMessage);
$(document).keyup(sendMessage);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-primary" type="submit" data-loading-text="<i class='fa fa-spinner fa-spin'></i> WAIT..." id="send_massage" style="margin-right:6px;">SEND</button>
<div id='status'></div>

Please try this code. This should be helpful for you
function sendMessage(e) {
$("#send_massage").addClass("disabled");
if(typeof e.type !== 'string' || (e.type == 'keyup' && e.keyCode != 13)) {
return $('#status').html('no call');
}
$('#status').html('made call');
var variabila = $("#text-massage").val();
var mesaj = "massage=" + variabila;
$.ajax({
type: "POST",
url: "/ajax/chat.php",
cache: false,
data: mesaj,
success: function (test) {
$("#text-massage").val('');
//$("#success").show("fast").delay(900).hide("fast");
$("#success").html(test);
$("#send_massage").removeClass("disabled");
}
});
}
$(document).ready(function () {
$(document).focus();
$("#send_massage").click(sendMessage);
$(document).keyup(sendMessage);
$("input").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
sendMessage();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" style="width:300px;" placeholder="Please enter a value here and hit enter" />
<button class="btn btn-primary" type="submit" data-loading-text="<i class='fa fa-spinner fa-spin'></i> WAIT..." id="send_massage" style="margin-right:6px;">SEND</button>
<div id='status'></div>

Related

Google captcha v3 button twice click is need to complete action

I just installed recaptcha v3 on a form and I found that the submit button needs to be clicked 2x to make it work.First submit it will get the captcha validation. After the second click it will pass redirect.
Html code
<div class="form_wrpr">
<f:form.hidden id="g-recaptcha-response" property="g-recaptcha-response" />
<button class="g-recaptcha btn btn-blue" id="reg-submit"
data-sitekey="{fields.clientKey}" data-callback='onSubmit' data-action='submit' type= "submit">
{fields.Button}</button>
</div>
Script
$("#reg-submit").on('click', function(){if($('#company').val() == '') {
$('#company_error').text($('#company_error').data("error-mandatory"));
isvalid4 = false;
} if(!isvalid4) {
return false; }
if (grecaptcha.getResponse().length != 0) {
$("#reg-submit").attr("disabled", true);
$.ajax({
type: 'POST',
url: $('#form-ajaxurl').val(),
data: $('#demo_form').serialize(),
success: function(data){
$('#reg-submit').attr("disabled", false);
var output = JSON.parse(data);
if(output.error == 1) {
$('#form-errors').html(output.result);
}
else if(output.error == 2){
$('#form-errors').html(output.result);
} else {
window.location.href = 'test.com'+output.result;
} } }); }else { var elementClicked = 0;
$(".g-recaptcha").on('click', function(){
elementClicked = 1; if( elementClicked == 1)
{ $('#g_captchaerror').text(''); } }); if(elementClicked == 0)
{ isvalid4 = false;
$('#g_captchaerror').text($('#g_captchaerror').data("error-mandatory"));
} } });
The code creates a button that a user must click on in order to complete the CAPTCHA challenge. When the button is clicked, the grecaptcha.execute() function is called, which will trigger the reCAPTCHA v3 verification process.
$(document).ready(function() {
var alreadySubmitted = false;//adding a extra variable to check already submitted.
$("#reg-submit").on('click', function(){
if(!isvalid4) {
return false;
}
grecaptcha.ready(function() {
grecaptcha.execute('clientkey', {
action: 'submit'
}).then(function(token) {
$.ajax({
type: 'POST',
url: $('#form-ajaxurl').val(),
data: $('#demo_form').serialize(),
success: function(data){
// $('#reg-submit').attr("disabled", false);
var output = JSON.parse(data);
if (output.error == 1) {
$('#form-errors').html(output.result);
} else if(output.error == 2) {
$('#form-errors').html(output.result);
} else {
window.location.href = 'test.com'+output.result;
}
}
});
});
});
});

Search by pressing Enter

I would like, that when the Enter button is pressed, the application will search a city, the action now is started by pressing the Search button. Below is my code:
const ENTER_KEY_CODE = 13;
document.querySelector('#city').addEventListener('keyup', function(e) {
if (e.keyCode === ENTER_KEY_CODE) {
var city = $(this).val();
if (city !== '') {
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" +
"&APPID=bb037310921af67f24ba53f2bad48b1d",
type: "GET",
dataType: "json",
success: function (data) {
var widget = show(data);
$("#show").html(widget);
$("#city").val(' ');
}
});
} else {
$("error").html('Field cant be empty')
}
};
});
All you need to do is add a keyup events listener to your input element. When the handler is called, simply check the e.keyCode to see if it's enter was pressed. If it was, do your thing:
const ENTER_KEY_CODE = 13;
document.querySelector('#textEl').addEventListener('keyup', function(e) {
if (e.keyCode === ENTER_KEY_CODE) {
var city = $(this).val();
var url = `http://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(city)}&units=metric&APPID=bb037310921af67f24ba53f2bad48b1d`;
if (city !== '') {
console.log(`Make ajax call to ${url}`);
//Make your AJAX call here
} else {
console.log('City cannot be blank!');
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="textEl" type="text" />
<div id="error"></div>
This a sample code please use this a reference code.
HTML code
<input id="InputEnter" >
Javascript code
var input = document.getElementById("InputEnter");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
$(document).ready(function () {
$('#submitWeather').click(function () {
var city = $("#city").val();
if (city !== '') {
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" +
"&APPID=bb037310921af67f24ba53f2bad48b1d",
type: "GET",
dataType: "json",
success: function (data) {
var widget = show(data);
$("#show").html(widget);
$("#city").val(' ');
}
}
});
This should work. I assume that your ajax request is correct.
document.querySelector('#submitWeather').addEventListener('keypress', function(e){
if(e.which === 13){
// your ajax request
}
})

Prevent page reload on enter key pressed

i have the following input field:
<input type="text" id="txt_comment" class="form-control" placeholder="Skriv kommentar">
with this i have the following code
$('#txt_comment').keyup(function(e){
if(e.keyCode == 13)
{
addComment();
return false;
}
e.preventDefault();
});
However when i press enter it still reloads the page. Can anyone tell me what im doing wrong?
Update
function addComment()
{
var comment = $('#txt_comment').val();
{
$.ajax({
type: 'POST',
url: '/Comment/addComment',
dataType: 'json',
data: {
request: 'ajax',
reciver:user_id,
comment: comment
},
success: function (data)
{
$('#comment_list').prepend(
' <li class="list-group-item animated fadeInRightBig">'+
' <p><b class="text">'+data['sender']+'</b>:'+
'<br/>'+comment+' </p>'+
'<input type="hidden" class="timestamp" value="'+data["timestamp"]+'">'+
' <small class="block text-muted timeSmall"><i class="fa fa-clock-o"></i></small>'+
'</li>'
)
$('.timestamp').each(function()
{
var text = $(this).next()
var timer = $(this).val();
var new_text = moment(timer, "YYYY-MM-DD- HH:m:ss").fromNow();
text.html(new_text);
});
$('#txt_comment').val('');
}
})
}
}
And my function now look like this:
$('#txt_comment').keyup(function(e){
if(e.keyCode === 13)
{
addComment();
e.preventDefault();
return false;
}
});
Still having page reloads
For quick reference: To solve the issue, add a hidden input field to your form.
This is a relic from the an older version of HTML:
When there is only one single-line text input field in a form, the user agent should accept Enter in that field as a request to submit the form.
The return is firing before the preventDefault call, just re-arrange them:
$('#txt_comment').keyup(function(e){
e.preventDefault();
if(e.keyCode === 13) {
addComment();
return false;
}
});
Use the keydown function instead:
$('#txt_comment').keydown(function(e){
if(e.keyCode == 13)
{
addComment();
return false;
}
e.preventDefault(); });

Trigger event on submit

In a newsletter sign-up form, I would like to make the email disappear after the end user hits enter. I have already added JS to hide and unhide the placeholder text.
The code:
<form id="form" action="https://xxxx.com/subscribe/post-json?u=xxx&id=xx&c=?" method="GET">
<input type="hidden" name="u" value="xxx">
<input type="hidden" name="id" value="xxx">
<input id="email" type="EMAIL" autocapitalize="off" autocorrect="off" name="MERGE0" id="MERGE0" size="25" placeholder= "Type your email and press enter">
<p id="response"></p>
</form>
And the JS:
<script >
var text = document.getElementById("email");
text.onfocus = function() {
if ( text.placeholder == "Type your email and press enter") {
text.placeholder = "";
}
};
text.onblur = function() {
if ( text.placeholder == "") {
text.placeholder = "Type your email and press enter";
}
};
</script>
I tried to create a function to trigger the event but it still didn't work:
function checkEnter(event)
{
if (event.keyCode == 13) {text.placeholder = "cool";}
};
Could you all see what's wrong with my code?
Thank you.
You need to add a event listener for the enter key. You could remove your function checkEnter and use this instead:
document.querySelector('#email').addEventListener('keypress', function (e) {
var key = e.which || e.keyCode;
if (key == 13) {
text.placeholder = "cool";
}
};
I have integrated the code below with the mailchimp form and got the desired results:
var paragraph = document.getElementById('response');
$('#form').submit(function(e) {
var $this = $(this);
$.ajax({
type: "GET", // GET & url for json slightly different
url: "https://xxxxx.com/subscribe/post-json?u=xxxx&id=xxx&c=?",
data: $this.serialize(),
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server."); },
success : function(data) {
if (data.result != "success") {
paragraph.innerHTML = data.msg;
text.placeholder = "Oopsy daisy! Error :-(";
form.reset();
} else {
paragraph.innerHTML = data.msg;
text.placeholder = "Thanks so much!";
form.reset();
}
}
});
return false;
});

How to close the box if click anywhere?

I have an code that the function is autosuggestion. This code works good. And I just want to ask You about how to close the box after I input text in the textbox. In my code when I try to click anywhere, it didn't close the box. So what I want to do is when I click anywhere so the box must be close.
Here is my jQuery:
$(document).ready(function() {
$(".text_search").keyup(function() {
var searchbox = $(this).val();
var dataString = 'searchword=' + searchbox;
if (searchbox == '') {} else {
$.ajax({
type: "POST",
url: "search1.php",
data: dataString,
cache: false,
success: function(html) {
$("#display").html(html).show();
}
});
}
return false;
});
});​
HTML:
<div class="search">
<form method="get" action="search.php" autocomplete="off">
<input class="text_search" type="text" name="q" id="q" value="Search people" onfocus="if (this.value == 'Search people') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search people';}">
</form>
</div>
<div id="display">
</div>
Just add a event handler on the document body and close the box if it's open. Put that at the end of your body :
<script>
$(window).ready(function(){
$('body').click(function(){
$("#display").hide();
});
});
</script>
EDIT :
If you want also to have the search launched again when you click the search box, change your script to this :
$(document).ready(function() {
var launchSearch = function() {
var searchbox = $(this).val();
var dataString = 'searchword=' + searchbox;
if (searchbox == '') {} else {
$.ajax({
type: "POST",
url: "search1.php",
data: dataString,
cache: false,
success: function(html) {
$("#display").html(html).show();
}
});
}
return false;
};
$(".text_search").keyup(launchSearch).click(launchSearch);
$('body').click(function(){
$("#display").hide();
});
});​
Try this:
$('body').click(function(){
$("#display").hide();
});
$(document).click(function(e) {
if($(e.target).parents("#display").length == 0 &&
$(e.target).attr("id") != "display") {
$("#display").hide();
}
});
You must check if click is not in display div
Try this
$(document).ready(function(){
$('body').click(function(){
$("#display").hide();
});
$(".text_search").keyup(function()
{
var searchbox = $(this).val();
var dataString = 'searchword='+ searchbox;
if(searchbox=='')
{}
else
{
$.ajax({
type: "POST",
url: "search1.php",
data: dataString,
cache: false,
success: function(html)
{
$("#display").html(html).show();
}
});
}return false;
});
});

Categories

Resources