Run Function If user delete the word - javascript

So I have a jQuery code for sending keywords to another page.On that page I have names of all countries. my code works good also, I have defined my function in a condition that if the lenght of text of input was longer than 2 then runs the function inside it but, I have problem with this for Example when I write the city name it works good and returns the correct data from the ajax page my issue is when the user wants to delete that word with backspace or somthing else I want to remove all previous data was sent to ajax page but because of my condition it does not work.
how can I define if user delete the word run my function ?
here is my code :
var prevXHR = null; //global
$('.country').each(function() {
$(this).on('keyup', function(e) {
var _this = this;
var element = $(this).val().length;
if (e.which !== 0 &&
!e.ctrlKey && !e.metaKey && !e.altKey
){
if (element > 2) {
var val = $(this).val()
$(this).val(val)
prevXHR = $.ajax({
url: "ajaxpage.htm",
type: "get",
contentType: 'application/json; charset=utf-8',
data: {
key: $(this).val()
},
success: function(result) {
$(_this).closest(".search_div").find(".co").empty().html(result)
},
beforeSend: function(){
if(prevXHR && prevXHR.readyState != 20){
//before sending any new request neutralize any pending ajax call
prevXHR.abort();
prevXHR = null;
}
}
});
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="search_div">
<input type="text" value="" class="country" autocomplete="off" />
<div class="result"></div>
</div>

In your code, you are already checking to see if the length of the input was greater than 2, then proceeding with ajax call.
Just add else part afterwards.
if (element > 2) {
// ...do the ajax stuff here
} else {
// the input length was shorter than 2 characters...
// remove all HTML elements here
$('div#to_be_removed').remove(); //or something like that
}

Related

how do make waiting for ajax to complete

I newbie.
I have a function application for employment (apply-job).What I do is submit the request with an ordinary link, with a click-function applied on it but processing time is quite long. I want disable "#apply-job" avoid click too much or disable window and fade for ajax to complete. Thank.
My JS:
$("#apply-job").click(function() {
if($('#jobcandidate-name').val() != '' && $('#jobcandidate-email').val() != '' && $('#jobcandidate-phone').val().length >= 10 && $('#jobcandidate-address').val() != '' && ($("input[name='CandidateAttachment[2][fileAttachment][path]']").val() != undefined || $('#jobcandidate-curriculum_vitae').val() != '') ){
let data = $('#apply-job-form').serialize();
let roleArticle = $('.show_new_role :input').serialize();
if ($('#apply-job-form').find('.has-error').length){
swal("Thử lại", "Vui lòng kiểm tra lại thông tin!", "error");
} else {
$.ajax({
url: '$urlRequest',
type: 'POST',
dataType: 'html',
data : data + '&' + roleArticle
}).done(function(result) {
response = JSON.parse(result);
if (response.type == "success"){
let checkReload = swal("Thành công", "Cảm ơn bạn đã ứng tuyển!", "success");
checkReload.then(function() {
location.reload();
});
}
});
}
} else {
if ($("input[name='CandidateAttachment[2][fileAttachment][path]']").val() == undefined && $('#jobcandidate-curriculum_vitae').val() == '') {
$('#jobcandidate-curriculum_vitae').parents('.form-group').find('.txt-lable').css('color','red');
$('#jobcandidate-curriculum_vitae').parents('.form-group').find('.show_error2').text('* Không được bỏ trống');
}
swal("Thử lại", "Vui lòng kiểm tra lại thông tin!", "error");
}
});
ajax has await option. You can use it to make the execution wait till the ajax all is done. Make sure you combine it with async which will tell there's an asynchronous step in the function. See below snippet
$("#apply-job").click(async function() {
......
await $.ajax({
......
});
Update: to make sure the click is disabled while ajax is working, add a disabled attribute and assign the click only when the attribute is not present. Clear the attribute once process is complete.
$("#apply-job:not([disabled])").click(async function() {
$("#apply-job").attr("disabled","disabled")
......
await $.ajax({
......
$("#apply-job").remoeAttr("disabled")
});

How to create search button for existing code which execute search on enter press? php/javascript/mysql

I have a website which someone else have been coding for me and i'm trying to understand how to change a simple thing.
I am not webdeveloper but on the last days I got familiar a bit with php, mysql and javascript (i'm familiar with java).
****The Question:****
On my website I have search form which works without search button (search function works on enter press or when choosing from autocomplete). How do i change it to work only with search button ?
The web developed with framework called CodeIgniter.
This is how controller looks like:
public function searchGym()
{
if($_POST)
{
$gym_name=$_POST['gym_name'];
$gym_name=trim($gym_name," ");
$data['details']=$this->user_model->getGymByName($gym_name);
$data['gym_name']=$gym_name;
$this->load->view('he/searched_gym',$data);
}
}
This is how model look like:
public function getGymByName($query_string)
{
$query_string=mysql_real_escape_string($query_string);
$query=$this->db->query("select * from gym_members_table where member_title like '%$query_string%'");
return $query->result_array();
}
</code>
And this is the index.php search form :
<div class="search-home">
<input type="text" onkeypress="gymhandle(event);" class="form-control gym_search" id="gym" name="gym" placeholder="
Search by Name
" >
<div class="autosuggest1"></div>
<div class="autosuggest"></div>
</div>
<script>
function settextbox(rval){
$('.autosuggest').hide();
$('#gym').val(rval);
$('#gym_search2').val(rval);
searchGymByName(rval);
}
$(document).ready(function(){
$('.autosuggest').hide();
$('#gym').keyup(function(e)
{
var code = (e.keyCode || e.which);
// do nothing if it's an arrow key
if(code == 37 || code == 38 || code == 39 || code == 40 || code==13) {
return;
}
var search_term = $(this).val();
var getdata = { 'search_term': search_term};
if(search_term!=''){
$.ajax({
url: "<?php echo site_url('hebrew/searchGymAuto');?>",
data: getdata,
type: 'POST',
success: function(data){
$('.autosuggest').show();
$('.autosuggest').html(data);
}
});
}
else
{
$('.autosuggest').hide();
}
});
});
$('.autosuggest').hide();
function searchGymByName(rval)
{
$('.autosuggest').hide();
var gym_name=rval;
$.ajax({
url:"<?php echo site_url();?>hebrew/searchGym",
type: "POST",
data:{gym_name: gym_name},
success:function(res){
$('html, body').animate({ scrollTop: 0 }, 0);
$("#ajax-map").hide();
$("#city").val('');
$("#city1").val('');
$("#ajax-page-hide").show();
$("#ajax-page-hide").html(res);
}
});
}
Thanks!!
You can cancel the enter keypress on those fields like this:
$('.gym_search').keypress(function(e){
if ( e.which == 13 ) return false;
//or...
if ( e.which == 13 ) e.preventDefault();
});
Remove the id attribute from the search input field, and place id="gym" on the search button. And then in $('#gym').click(function(e) [note: 'click' instead of 'keyup'], change the search_term to
var search_term = $("gym_search").val();
Remove onkeypress event from text box. Add ajax call for search in java script function and call that function on button click event

jQuery updates DOM, browser does not

I am working on a project where for example field number 3 on the webpage should be updated with values from a database when a user enters data into field number 1. This already works fine without any problems.
But if the user modifies field number 3 first and field number 1 at a later time, just the DOM gets updated (as I can tell from Firebug) but there isn't any visible change on field number 3 to the user.
I created a very basic version of this problem and still I am not able to tell what's wrong here.
HTML
<div id="container1">
<textarea id="container1.1">Entry 1.1</textarea>
<textarea id="container1.2">Entry 1.2</textarea>
<textarea id="container1.3">Entry 1.3</textarea>
</div>
jQuery
$(document).ready(function() {
$('textarea').change(function() {
var clickedObject = $(this);
var id = $(this).attr('id').substr(9);
var value = $(this).val();
var dataString = "id=" + id + "&value=" + value;
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
cache: false,
success: function(Result)
{
if(Result == '-')
{
console.log('Nothing to do');
} else {
clickedObject.next().next().html(Result);
}
}
});
});
});
PHP
<?php
if ($_POST['id'] == '1.1') {
echo 'Modified string';
} else {
echo '-';
}
?>
You must set values of textarea by .val() method, instead of html().
And maybe it will be more descriptive if you will use only one id of textarea that should call request on changes.

How can I ensure that a javascript function will work on multiple calls?

I have a basic search feature where I can enter a search query into a field which will display a drop down list of suggested results. I can click on any of the suggested results and the value for that record (stored in a MySQL database) is inserted into the field, as I have intended. However, if I try to do the same thing immediately after the first run of the script, then it doesn't work. But, if I reload the page, then it will work again. In other words, it will work the first time I run the script, but not on subsequent runs of the script, unless I reload the page. It's as if by running the script it 'turns itself off' after the first run, not letting me run the script again. Any ideas? Here is the code:
<script>
$(function(){
var index = -1;
$('#myID').keyup(function(e){
if (e.keyCode == 38){
index = (index == 0) ? 0 : index - 1;
$('tr.myRow').removeClass('gray');
$('tr.myRow:eq(' + index + ')').addClass('gray');
return false;
}
else if (e.keyCode == 40){
index = (index + 1 >= $('tr.myRow').length) ? $('tr.myRow').length - 1 : index + 1;
$('tr.myRow').removeClass('gray');
$('tr.myRow:eq(' + index + ')').addClass('gray');
return false;
}
else
{
var str = $('#myID').val();
mySearch(str);
}
index = -1;
});
});
</script>
<script>
$(function(){
$('#myID').keydown(function(e){
if (e.keyCode == 13){
var functionName = $('#pageSearch1 > tbody > tr.gray').attr("onclick");
setTimeout(functionName, 0)
$('#pageSearch').css({'visibility': 'hidden'});
return false;
}
});
});
</script>
The "onClick" attribute is the following script:
function insertPageIDIntoHiddenField(pageID,pageName)
{
$('tr#eventPageID td#loc input#locationID').val(pageID);
$('tr#eventPageID td#loc input#myID').replaceWith('<input id="myID" class="event_form_long" type="text" name="location" value="'+pageName+'" autocomplete="off" />');
$('tr#eventPageID td#loc input#myID').text(pageName);
$('#pageSearch').replaceWith('<div id="pageSearch"></div>');
}
I have used the autocomplete function of jquery to achieve the suggestion on keypress I hope this could help u
$('#txtSearchText').autocomplete({
source: function(request, response) {
$.ajax({
url: SearchPath + "SearchWebService.asmx/GetUserList",
data: JSON2.stringify({ userName: $('#txtSearchText').val()}),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value:item.UserName
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1
});

How to run a JavaScript code inside of a jquery dialog

I open a jquery dialog, it opens very good, the content of this dialog is a form, one input of that form is:
<input onkeyup="testOnKeyUp();" type="text" name="userName" id="userName">
Here is where come my problem, it's suppose that when someone type a Key in this input the following code is activated and should run, but it just does not work.
var validateUserNameSpan = $j('#userNameSpan');
function testOnKeyUp(){
validate(this, validateUserNameSpan, 'username');
}
function validate(field, span, property) {
if (field.value != field.lastValue) {
if (field.timer) clearTimeout(field.timer);
field.timer = setTimeout(function () {
span.value = "";
span.removeClass('error').html('checking ...');
$j.ajax({
url: '/signup/'+property,
data: property + '=' + field.value,
dataType: 'json',
type: 'post',
success: function (json) {
updateMessage(span, json.success, json.message);
if(property=="email"){
emailValid = true;
}else if(property=="username"){
userNameValid = true;
}
},
error: function() {
ajFailureInitSignup(span);
if(property=="email"){
emailValid = false;
}else if(property=="username"){
userNameValid = false;
}
}
});
}, 400);
if(userNameValid && emailValid) document.getElementById('buttonLink').onclick=null ;
field.lastValue = field.value;
}
}
What am I doing wrong ?
I don't know but googling I've got info that make me feel that the:
$j.ajax({
that I'm running inside of this dialog (validate function) is not being executed, why I say that ? because this dialog is created in the DOM and after be created there this $j.ajax is not executed.
is this true ?
I really thank any help.
Ok, the main problem is that your AJAX call returns IMMEDIATELY after you issue it - this is normal (it's the first 'A' in ajax - asynchronous). That means your code continues on immediately to the if (usernamevalid && emailvalid) code section. Those variables do not exist at that point, as the AJAX call has not yet returned. So you're comparing undefined variables, which will also fail.
You have to move that comparison inside your ajax success/error handlers, so that the comparison will only be done when the ajax call has actually produced data that can be compared.

Categories