Search by pressing Enter - javascript

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
}
})

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;
}
}
});
});
});
});

How to stop blur() event function to trigger twice?

I am trying to fetch the records from the database using blur function. There are two input fields where this function triggers. I have used different names, variables, javascript, controller using laravel to fetch the records. I am able to fetch the records through ajax and successfully opens the modal. When the modal pop ups when the blur function triggers, it also triggers the function for the second field.
I just want to trigger the modal according to the field, where the blur triggers and not to trigger twice.
//input field: originS
<script type="text/javascript">
$(document).ready(function(){
var origin = "";
var _token = "";
var ovalue = "";
$('#originS').blur(function(){
ovalue = "";
origin = $(this).val();
_token = $('input[name="_token"]').val();
$.ajax({
type: 'POST',
url: '{{ route('pagescontroller.fetchOrigin') }}',
data:{origin:origin, _token:_token},
success: function(response){
if(response){
$("#originSelect").modal('show');
console.log(response);
$(".result").html(response);
$(document).on('change', '#selectSuburb', function () {
ovalue = $(this).val();
if ($(this).is(':checked')) {
$('#originS').val(ovalue);
$("#originSelect").modal('hide');
$this.die('blur');
}
});
$('#originSelect').on('hidden.bs.modal', function (e) {
if (ovalue == "") {
$("#originS").val('');
$(".result").html(response);
}
});
}
},
});
});
});
</script>
//input field: destS
</script>
<script type="text/javascript">
$(document).ready(function(){
var dest = "";
var _token = "";
var dvalue = "";
$('#destS').blur(function(){
dvalue = "";
dest = $(this).val();
_token = $('input[name="_token"]').val();
$.ajax({
type: 'POST',
url: '{{ route('pagescontroller.fetchdest') }}',
data:{dest:dest, _token:_token},
success: function(response){
if(response){
$("#destSelect").modal('show');
console.log(response);
$(".dresult").html(response);
$(document).on('change', '#selectSuburbdest', function () {
dvalue = $(this).val();
if ($(this).is(':checked')) {
$('#destS').val(dvalue);
$("#destSelect").modal('hide');
$this.die('blur');
}
});
$('#destSelect').on('hidden.bs.modal', function (e) {
if (dvalue == "") {
$("#destS").val('');
$(".dresult").html(response);
}
});
}
},
});
});
});
</script>

How to display data storing in ajax global variable?

The user selects one of the options and submits the form.
Then without submitting the form, I need to display data from json file.
I am storing ajax call in a global variable display_this and calling that variable as a function after form is submitted.
When I select option and press submit I get this error:
TypeError: display_this is not a function
When I refresh the page, it displays the data.
My code:
<form id="form">
<select name="op" id="op">
<option value="A">A</option>
<option value="B">B</option>
</select>
<input value="Submit" type="submit" id="submit">
</form>
My JSON data:
[
{"key":"A","val":"apple"},
{"key":"A","val":"orange"},
{"key":"B","val":"carrot"},
{"key":"B","val":"onion"}
]
My jQuery code:
$(document).ready(function () {
var output;
var display_this = function () {
var val = $("#op").val();
$.ajax({
async: 'false',
type: 'post',
url: 'abc.php',
data: {
"val": val
},
dataType: 'json',
success: function (response) {
var data = JSON.stringify(response);
var resp = JSON.parse(data);
$.each(resp, function (i, item) {
if (val == "A" && resp[i].key == "A") {
output += resp[i].val + "</br>";
} else if (val == "B" && resp[i].key == "B") {
output += resp[i].val + "</br>";
}
});
return results.html(output);
}
});
}();
$('#form').submit(function (e) {
e.preventDefault();
display_this();
});
});
You function is not available to your form submit. I suggest this
$(function () {
$('#form').submit(function (e) {
e.preventDefault();
var output;
var val = $("#op").val();
$.ajax({
// async: 'false', // do NOT use async false
type: 'post',
url: 'abc.php',
data: {
"val": val
},
dataType: 'json',
success: function (resp) {
$.each(resp, function (i, item) {
if (val == "A" && resp[i].key == "A") {
output += resp[i].val + "</br>";
} else if (val == "B" && resp[i].key == "B") {
output += resp[i].val + "</br>";
}
});
$("#results").html(output);
}
});
});
});

How to enable ENTER button to send messages

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>

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(); });

Categories

Resources