Jquery textarea.val('') adds line break on FIRST enter press? - javascript

I have a little chat setup, and on enter press if the text area is in focus I have it set to submit the chat to my database and clear the text area. Unfortunately though, the first time one presses enter it adds a linebreak in the text area, in any browser. If you type and press enter again, there's still only one line break there. Am I missing something?
Thanks!
$(document).keypress(function(keyPress) {
if (keyPress.which == 13) {
if ($('#chatText').is(':focus')) {
if ($('#chatText').val().length > 0) {
chatValue = $('#chatText').val();
$('#chatText').val($('#chatText').val().substring(0,0));
$.ajax({
type: 'POST',
url: 'submitChat.php',
data: { chatText: chatValue },
success: function(result) {
$('#chat_text').html(result);
document.getElementById('chat_text').scrollTop = 9999999;
}
});
}
}
}
});

Why don't you just clear it?
$('#chatText').keypress(function(e) {
if (e.which == 13) {
var value = $(this).val();
if (value.length > 0) {
$(this).val('');
$.ajax({
type: 'POST',
url: 'submitChat.php',
data: {
chatText: value
},
success: function(result) {
$('#chat_text').html(result);
this.scrollTop = 9999999;
}
});
}
}
});

Try this,
$(document).keypress(function(keyPress) {
if (keyPress.which == 13) {
keyPress.preventDefault();
if ($('#chatText').is(':focus')) {
if ($('#chatText').val().length > 0) {
chatValue = $('#chatText').val();
$('#chatText').empty();
$.ajax({
type: 'POST',
url: 'submitChat.php',
data: { chatText: chatValue },
success: function(result) {
$('#chat_text').html(result);
document.getElementById('chat_text').scrollTop = 9999999;
}
});
}
}
}
});

$(document).keypress(function(keyPress) {
if (keyPress.which == 13) {
keyPress.preventDefault();// Add this line
if ($('#chatText').is(':focus')) {
if ($('#chatText').val().length > 0) {
chatValue = $('#chatText').val();
$('#chatText').val($('#chatText').val().substring(0,0));
$.ajax({
type: 'POST',
url: 'submitChat.php',
data: { chatText: chatValue },
success: function(result) {
$('#chat_text').html(result);
document.getElementById('chat_text').scrollTop = 9999999;
}
});
}
}
}
});

Related

Separate Ajax Calls in the Same JS file

I have a few buttons on one page in which I need different ajax calls for. In Chrome, this is working perfectly, but in Firefox, it seems that it's always pulling that first ajax call in the file, no matter what button is pressed. The main difference between the two calls is the action. Do I need to fix my code in order for Firefox to recognize the different calls/actions?
(function ($) {
$(document).ready(function() {
$(document).on('click', '.js-filter-item > a', function(e){
e.preventDefault();
var profCategory = $(this).data('category')
$.ajax({
url: wpProfAjax.ajaxProfUrl,
data: { action: 'profFilter', profCategory: profCategory },
type: 'post',
success: function(result) {
$("#professionals-container").hide().html(result).fadeIn(1000);
$(".misha_loadmore").hide();
},
error: function(result) {
console.warn(result);
}
});
});
$('div.sidebar-filter form').find('button').click(function(e){
e.preventDefault();
var title = $('#title').val();
$.ajax({
url: wpProfAjax.ajaxProfUrl,
data: { action: 'lnFilter', title: title },
type: 'post',
success: function(result) {
var profs = $(result).find('.professionals-column');
if(profs.length < 9){
$('.misha_loadmore').css('display', 'none');
$('#page').val('1');
}
else{
$('.misha_loadmore').css('display', 'block');
}
$("#professionals-container").hide().html(result).fadeIn(1000);
},
error: function(result) {
console.warn(result);
}
});
});

Prevent ajax call if input is blank

What is the correct way of preventing an ajax call if someone where to enter a blank space in an input field?
The code I am trying to do would look something like this (obviously this does not work)
$(document).ready(function() {
$(document).on('click', '#insert_btn', function() {
if ($("#first_name").val().length > 0)) {
$.ajax({
type: 'POST',
url: 'add.php',
datatype: "json",
data: {
first_name: $("#first_name").val(),
last_name: $("#last_name").val(),
position: $("#position").val(),
date: $("#date").val(),
updated: $("#updated").val(),
},
success: function(result) {
if (result == ADD_OK) {
alert('OK')
} else {
alert('wrong');
}
}
})
});
});
Since you're using jQuery already you can go for something like the code below where I've added the use of jQuery.trim before checking for the length
$(document).ready(function() {
$(document).on('click', '#insert_btn', function () {
// Utilizing https://api.jquery.com/jQuery.trim/
var first_name = $.trim($("#first_name").val());
if (first_name.length > 0) {
$.ajax({
type: 'POST',
url: 'add.php',
datatype: "json",
data: {
first_name: $("#first_name").val(),
last_name: $("#last_name").val(),
position: $("#position").val(),
date: $("#date").val(),
updated: $("#updated").val(),
},
success: function (result) {
if (result == ADD_OK) {
alert('OK')
} else {
alert('wrong');
}
}
})
}
});
});
jQuery Trim:
jQuery.trim(' ') // returns ""
jQuery.trim(' ') // returns ""
jQuery.trim(' this is my search text ') // returns "this is my search text"

get the notification length depends on ReadFlag

JS:
function getJSON(){
$.ajax({
url: "getgroupednotification.json",
type: "GET",
crossDomain: true,
success:function(res){
$.each(res,function(index, value){
//console.log(res);
//console.log(value);
$.each(value.Notifications, function(index_, value_){
if(value.Source == 'CIRIS'){
var i = value.Notifications.length;
if(value_.ReadFlag != 1){
}
}
});
});
});
i want to get the notification.length if ReadFlag == 0. Im using Source == CIRIS for this example.
This is the link to my JSON
https://api.myjson.com/bins/navph
You could use something like this:
function getJSON() {
$.ajax({
url: "https://api.myjson.com/bins/navph",
type: "GET",
crossDomain: true,
success: function(res) {
var lens = res.filter(function(item) {
// filter by source
return item.Source === 'CIRIS';
}).map(function(item) {
// get only Notifications
return item.Notifications;
}).map(function(notification){
// get lengths of notifications which have at least 1 RedFlag not 0
return (notification.filter(function(item){
return item.RedFlag !== 0;
}).length)
})
console.log(lens[0]);
}
})
}
getJSON();

Jquery autocomplete and enter key pressed

I have a jQuery autocomplete which reads from a database.
Everything works well, but when I press enter I need to go the database and check if the entered text exists in the table so I can select it - else I will alert invalid input.
My Attempt
I implemented the source and select method and also implemented the onkeypress method of the textbox. I am getting the result I need but even after I press enter the autocomplete is still searching for the values from the database.
How do I stop this because it is slowing my page.
Code:
$("#<%=txtSearch_Doc.ClientID%>").autocomplete({
delay:1000,
source: function (request, response) {
var m_Subtype = $("#<%=hdn_Subtype_Doc.ClientID%>").val();
var m_ConSocStr = $("#<%=hdn_ConSocStr_Doc.ClientID%>").val();
var jsonObjects = { "prefixText": request.term, "m_Subtype": m_Subtype, "m_ConSocStr": m_ConSocStr };
var jsonString = JSON.stringify(jsonObjects);
$.ajax({
url: '<%=ResolveUrl("AutoCompleteForFile.asmx/AutoSelectDoc")%>',
data: jsonString,
dataType: "json",
delay: 0,
autoFocus: true,
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('|')[0],//show key
val: item.split('|')[1], //documentnumber
}
}))
}
,
error: function (response) {
if (response.responseText != "") {
alert(response.responseText);
}
},
failure: function (response) {
if (response.responseText != "") {
alert(response.responseText);
}
}
});
},
//begin select event
select: function (e, i) {
$("#<%=hdn_Number_Doc.ClientID%>").val(i.item.val);
$("#<%=txtSearch_Doc.ClientID%>").val(i.item.val.trim());
if (i.item.val == "") {
$("#<%=hdn_Number_Doc.ClientID%>").val("0");
$("#<%=txtSearch_Doc.ClientID%>").val("");
}
return false;
},
//end select event
minLength: 1,
autoFocus: false //IF TRUE IT WILL SELECT THE FIRST ROW BY DEFAULT, IF FALSE IT WILL NOT SELECT THE FIRST ROW
})
//end autocomplete
//key press event to handle enter pressed added by chahid on 12-jan-2016
.keypress(function (e) {
$("#<%=hdn_key_pressed.ClientID%>").val(e.keyCode);
if (e.keyCode == 13) {
e.preventDefault();
var x = $("#<%=txtSearch_Doc.ClientID%>").val();
var m_Subtype = $("#<%=hdn_Subtype_Doc.ClientID%>").val();
var m_ConSocStr = $("#<%=hdn_ConSocStr_Doc.ClientID%>").val();
var jsonObjects = { "prefixText": x, "m_Subtype": m_Subtype, "m_ConSocStr": m_ConSocStr };
var jsonString = JSON.stringify(jsonObjects);
$("#<%=hdn_is_alert.ClientID%>").val("1");
$.ajax({
url: '<%=ResolveUrl("AutoCompleteForFile.asmx/CheckForDocExistance")%>',
data: jsonString,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (dat) {
var json = JSON.stringify(dat);
obj = JSON.parse(json);
if (obj.d == "2") { // if it is empty
$("#<%=txtSearch_Doc.ClientID%>").val("");
$("#<%=hdn_Number_Doc.ClientID%>").val("0");
}
else {
if (obj.d.split('|')[0] == "1") {
$("#<%=txtSearch_Doc.ClientID%>").val(obj.d.split('|')[1].trim());
$("#<%=hdn_Number_Doc.ClientID%>").val(obj.d.split('|')[1]);
return false;
} else {
alert("Invalid input");
$("#<%=txtSearch_Doc.ClientID%>").val("");
$("#<%=txtSearch_Doc.ClientID%>").focus();
$("#<%=hdn_Number_Doc.ClientID%>").val("0");
}
}
},
error: function (response) {
if (response.responseText != "") {
alert(response.responseText);
}
},
failure: function (response) {
if (response.responseText != "") {
alert(response.responseText);
}
}
});
$("#<%=txtSearch_Doc.ClientID%>").autocomplete('close');
}
})
OK I manage to found a solution : I added the search event to the autocomplete where I am checking the keypresscode and returning false when it is the enter key:
search: function (event, ui) {
var key = $("#<%=hdn_key_pressed.ClientID%>").val();
if (key == 13)
return false;
else
return true;
},

How to repeat ajax request depending return

I have this code :
.on('finish.countdown', function() {
var onEndAuction = function () {
$.ajax({
type: "POST",
url: "{{path('app_auction_end')}}",
data: {auctionId:{{ aReturn.oAuction.getId()}}},
success: function (data) {
console.log(data);
if (data == 0) {
setTimeout(onEndAuction, i_timer);
} else {
document.location.reload(true);
}
}
});
};
});
I want if data == 0 need to make another call on app_auction_end after 10 sec. Can you help me please ? Thx in advance and sorry for my english
Give the operation a named function:
var someFunction = function () {
$.ajax({
//...
});
};
Which you would then use for your .on() call:
.on('finish.countdown', someFunction)
And in the success handler, set a timeout for that function:
if (data == 0) {
setTimeout(someFunction, i_timer);
}
.on('finish.countdown', function() {
var onEndAuction = function () {
$.ajax({
type: "POST",
url: "{{path('app_auction_end')}}",
data: {auctionId:{{ aReturn.oAuction.getId()}}},
success: function (data) {
console.log(data);
if (data == 0) {
setTimeout(onEndAuction, i_timer);
} else {
document.location.reload(true);
}
}
});
};
//do our initial call otherwise it will never get called.
onEndAuction();
});

Categories