Deselect a textbox in jQuery - javascript

I have a Google Instant style jQuery search script that queries a PHP file then parses the results into an HTML div. It uses tabs for the user to define the search type that they want and when a search is made, a URL is created which is something like #type/query/.
Currently, the search box is selected on page load with the $('#query').focus(); function however I want it to be deselected when the page is reloaded and there is text in #query. How can I go about doing this? I hope you can understand my question.
My jQuery code is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
return false;
});
$('#query').focus();
if (window.location.hash != "") {
var full = window.location.hash.replace('#', '');
var queryType = full.substring(0, full.indexOf("/"));
$('#type_' + queryType).click();
} else {
$('#type_search').click();
}
$('#query').keyup(function () {
var query = $(this).val();
var url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search Script';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search Script';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
if (window.location.hash.indexOf('#' + type + '/') == 0) {
query = window.location.hash.replace('#' + type + '/', '').replace('/', '');
$('#query').val(decodeURIComponent(query)).keyup();
}
});

Remove $('#query').focus(); from where it is now, and add it in with an else like this:
if (window.location.hash.indexOf('#' + type + '/') == 0) {
query = window.location.hash.replace('#' + type + '/', '').replace('/', '');
$('#query').val(decodeURIComponent(query)).keyup();
}else {
$('#query').focus();
}

Related

Retrieving of Data with different JSON formats

I am using jQuery and javascript in an ASP.NET Code
Below are the 2 functions that retrieve data in different formats
jQuery.ajax({
url: URL,
success: function (data) {
debugger;
try {
window["DataList"] = eval(data);
}
catch (e) {
window["DataList"] = [];
}
if (typeof (DataList) === "undefined" || !jQuery.isArray(DataList) || DataList.length === 0 || !DataList[0].id) {
jQuery("#" + divnomatch).text("No Matches Found.");
jQuery("#" + divnomatch).css("visibility", "visible");
jQuery("#" + divnomatch).css("display", "inline");
jQuery("#" + hdnid).val("");
jQuery("#" + hdnname).val("");
response([]);
}
else {
debugger;
jQuery("#" + divnomatch).css("visibility", "hidden");
jQuery("#" + divnomatch).css("display", "none");
fnShowHideObjTR("trResultsForRAUsers", false);
response(jQuery.map(DataList, function (item) {
return {
label: item.value,
value: item.value,
ID: item.id,
lNo: item.lNo,
eMail: item.eMail,
phyBUID: item.phyBUID
}
}));
}
}
});
For this, the data comes as below...
Below is the function that retrieves data in different format
jQuery.ajax({
url: URL,
success: function (data) {
switch (data) {
case 'NoMatch':
jQuery("#" + divnomatch).text("No User's last name starts with '" + searchtext + "'.");
jQuery("#" + divnomatch).css("visibility", "visible");
jQuery("#" + divnomatch).css("display", "inline");
jQuery("#" + hdnid).val("");
jQuery("#" + hdnname).val("");
break;
case data.charAt(0) == "|":
lblErrorMessage.innerHTML = "Error occurred while retrieving the data: " + data.substring(1);
fnShowHideSpan("spanError", true);
break;
case data.charAt(0) == "<":
lblErrorMessage.innerHTML = "The server has not responded promptly to your \"Search as you Type\" queries. Please try again after a few minutes.";
fnShowHideObj("spanError", true);
break;
default:
debugger;
jQuery("#" + divnomatch).css("visibility", "hidden");
jQuery("#" + divnomatch).css("display", "none");
var rows = data.split("|");
var jsStr = "var DataList=[";
for (var i = 0; i < rows.length - 1; i++) {
var s = rows[i].toString();
s = s.replace(/'/g, "\\'");
var row = s.split("~");
jsStr += "{id:'" + row[0].toString() + "'";
jsStr += ",value:'" + row[1].toString() + "'},";
}
jsStr = jsStr.slice(0, jsStr.length - 1);
jsStr += "];";
eval(jsStr);
if (typeof (DataList) != 'undefined') {
response(jQuery.map(DataList, function (item) {
return {
label: item.value,
value: item.value,
ID: item.id
}
}));
}
}
},
error: function (e) {
lblErrorMessage.innerHTML = "The server has not responded promptly to your \"Search as you Type\" queries. Please try again after a few minutes.";
fnShowHideObj("spanError", true);
}
});
Below is the data format in data variable
The second function works properly with the data and with its unique pipe seperator. How can I modify the code for first function which contains array of items to be pulled even with comma separator in the field in the front end as below...
So the problem that first function doesn't work at all or it formats the response to the incorrect format?
The suspicious thing I see now is the one of the conditions in the first if statement. !DataList[0].id would evaluate to true in case there is and object with ID equals to 0 which is incorrect logic I assume.

Passing URL variables in Ajax

I'm sure if I'm going about this the right way, but I need to pass the form variables in the URL redirect. The redirect is working, but I can't get the data to output.
$("#promoForm").on('submit', function(e) {
e.preventDefault();
var data = {
firstname: $("#firstname").val(),
lastname: $("#lastname").val(),
email: $("#email").val(),
code: $("#code").val()
};
if ( isValidEmail(data['email']) && (data['firstname'].length > 1) && (data['lastname'].length > 1) && (data['code'].length > 1) ) {
$.ajax({
type: "POST",
url: "php/promo.php",
data: data,
success: function() {
$('.success.pf').delay(500).fadeIn(1000);
$('.failed.pf').fadeOut(500);
setTimeout(function() {
window.location.href = "http://demo.example.com/signup?firstname=+data['firstname']+lastname=+data['lastname']+email=+data['email']+code=+data['code']"
}, 3000);
}
});
} else {
$('.failed.pf').delay(500).fadeIn(1000);
$('.success.pf').fadeOut(500);
}
return false;
});
Try this,
window.location.href = "http://demo.example.com/signup?firstname="+data['firstname']+"lastname="+data['lastname']+"email"=+data['email']+"code="+data['code']
You are not using variables to construct the URL:
window.location.href = "http://demo.example.com/signup?firstname=+data['firstname']+lastname=+data['lastname']+email=+data['email']+code=+data['code']"
Instead, close the string with " and append the values and follow-up strings:
window.location.href = "http://demo.example.com/signup?firstname=" + data['firstname'] + "lastname=" + data['lastname'] + "email=" + data['email'] + "code=" + data['code']
Additionally, you seem to be missing the parameter separators (&), so I should probably be:
window.location.href = "http://demo.example.com/signup?firstname=" + data['firstname'] + "&lastname=" + data['lastname'] + "&email=" + data['email'] + "&code=" + data['code']

Save Wikipedia text in English if German not available with $.getJSON in JQuery

I get the German text of a specific keyword (var title) and output it as html afterwards. This is working fine, but now I wanted to load the English text if the German text isn't available. This is also working fine with my code:
var length = 500;
var title = $('#title').attr('data-title');
var lang = 'de';
var url = 'https://' + lang + '.wikipedia.org/w/api.php?format=json&action=query' +
'&prop=extracts&exintro=&explaintext=&titles=' + title + '&redirects=0';
$.getJSON("http://query.yahooapis.com/v1/public/yql",
{
q: "select * from json where url=\"" + url + "\"",
format: "json"
},
function (data) {
$.each(data.query.results.json.query.pages, function (key, val) {
var text = val['extract'];
console.log('lang-' + lang + '-text: ' + text);
if (text) {
text = text.replace('Siehe auch:', '');
} else if (!text && lang != 'en') {
var url = 'https://en.wikipedia.org/w/api.php?format=json&action=query' +
'&prop=extracts&exintro=&explaintext=&titles=' + title + '&redirects=0';
$.getJSON("http://query.yahooapis.com/v1/public/yql",
{
q: "select * from json where url=\"" + url + "\"",
format: "json"
},
function (data) {
$.each(data.query.results.json.query.pages, function (key, val) {
text = val['extract'];
console.log('lang-en-text: ' + text);
});
});
}
console.log('lang-end-text: ' + text);
if (text) {
text = text.length > length ? text.substring(0, length - 3) + '...' : text;
$('#text').html(text);
} else {
setTimeout(function () {
$('#text').html('<?= __('EMPTY'); ?>');
}, 1000);
}
console.log(data);
});
});
But after the second $.getJSON is closed, text is empty again. That means that
console.log('lang-en-text: ' + text);
is working and outputs the correct English text in the console, but after closing the $.getJSON the variable text has no value anymore, what I can confirm with the output in the console:
console.log('lang-end-text: ' + text);
How can I keep the value? Also is there a better way to check if the specific content I want to get (the text in this case) is available BEFORE, so I don't have to make two $.getJSON requests? Or is my way the right way to do it?
EDIT: It's working now!
I found the solution thanks to moopet and used .done and a new function called .setText to set the text. Maybe this helps others too as the question seems to get upvoted a lot. This is my code now:
var length = 500;
var title = $('#title').attr('data-title');
var lang = 'de';
var url = 'https://' + lang + '.wikipedia.org/w/api.php?format=json&action=query' +
'&prop=extracts&exintro=&explaintext=&titles=' + title + '&redirects=0';
$.getJSON("http://query.yahooapis.com/v1/public/yql",
{
q: "select * from json where url=\"" + url + "\"",
format: "json"
},
function (data) {
$.each(data.query.results.json.query.pages, function (key, val) {
var text = val['extract'];
console.log('lang-' + lang + '-text: ' + text);
if (text) {
text = text.replace('Siehe auch:', '');
} else if (!text && lang != 'en') {
var url = 'https://en.wikipedia.org/w/api.php?format=json&action=query' +
'&prop=extracts&exintro=&explaintext=&titles=' + title + '&redirects=0';
$.getJSON("http://query.yahooapis.com/v1/public/yql",
{
q: "select * from json where url=\"" + url + "\"",
format: "json"
},
function (data) {
$.each(data.query.results.json.query.pages, function (key, val) {
text = val['extract'];
console.log('lang-en-text: ' + text);
});
}).done(function() {
setText(text);
});
}
console.log(data);
});
}).done(function() {
setText(text);
});
function setText(text) {
if (text) {
text = text.length > length ? text.substring(0, length - 3) + '...' : text;
$('#text').html(text);
} else {
$('#text').html('Text not available.');
}
}
You're running afoul of asynchronous javascript calls.
Your success callback:
function (data) {
$.each(data.query.results.json.query.pages, function (key, val) {
text = val['extract'];
console.log('lang-en-text: ' + text);
});
});
is called asynchronously. In other words, it's deferred until the HTTP request has finished.
Your
console.log('lang-end-text: ' + text);
is called immediately, before text is assigned, because that's how execution progresses. If you put the code for things you want to do with the text inside the callback function, you'll get the results you want.

problem ajax load with autocomplete.?

i created a jquery autocomplete it work true, but loading LOADING... it after removed value by Backspace don't work true. it not hide and Still is show.
how can after removed value by Backspace, hide LOADING... ?
EXAMPLE: Please click on link and see problem
my full code:
$(document).ready(function () {
/// LOADING... ///////////////////////////////////////////////////////////////////////////////////////
$('#loadingDiv')
.hide() // hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
});
/// autocomplete /////////////////////////////////////////////////////////////////////////////////////////
$('.auto_complete').keyup(function () {
var specific = '.' + $(this).closest('div.auto_box').find('b').attr('class');
var cl_list = '.' + $(this).closest('div.auto_box').find('ul').attr('class');
var id = '#' + this.id;
var url = $(id).attr('class');
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
dataType: 'json',
url: url,
data: dataObj,
cache: false,
success: function (data) {
//alert(url)
var cl_list = '.' + $('.auto_box '+ specific +' ul').attr('class');
var id_name = $(cl_list).attr('id');
$(cl_list).show().html('');
if (data == 0) {
$(cl_list).show().html('<p><b>There is no</b></p>');
}
else {
$.each(data, function (a, b) {
//alert(b.name)
$('<p id="' + b.name + '">' + b.name + '</p>').appendTo(cl_list);
});
$(cl_list + ' p').click(function (e) {
e.preventDefault();
var ac = $(this).attr('id');
$('<b>' + ac + '، <input type="text" name="'+id_name+'[]" value="' + ac + '" style="border: none; display: none;" /></b>').appendTo($('.auto_box ' + specific + ' span'));
$(this).remove();
return false;
});
$('.auto_box span b').live('click', function (e) {
e.preventDefault();
$(this).remove();
return false;
});
}
if ($(specific + ' input').val() == '') {
$(cl_list + " p").hide().remove();
$(cl_list).css('display','none');
$(".list_name").show().html('');
};
$('body').click(function () {
$(cl_list + " p").hide().remove();
$('.auto_complete').val('');
$(cl_list).show().html('');
$(cl_list).css('display','none')
});
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
});
I recommend you to use jsfiddle next time you post code examples in a link.
Nevermind. The "loading" message keeps there because there's no fallback to empty values on results.
A quick fix could be just by test that there's a value in the input before making any post like if(this.value == ""){
$(cl_list).css('display', 'none');
return false;
}
Here's how it works with it

Defining jQuery variable from url

I have a jQuery search script that uses tabs for the user to define which search type they want to use. When a user searches, a URL is created which is something like #type/query/. I need to somehow define the query terms in my window.location.hash.replace so I am just left with the search type from the URL. How can I go about changing the QUERYGOESHERE in my example below to the query the user has made? I hope people can understand my question.
My jQuery Script is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
return false;
});
if (window.location.hash != "") {
url = window.location.hash.replace('#', '').replace('/QUERYGOESHERE/', '');
$('#type_' + url).click();
} else {
$('#type_search').click();
}
$('#query').keyup(function () {
var query = $(this).val();
var url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search Script';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search Script';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
var textlength = $('#query').val().length;
if (textlength <= 0) {
$('#query').focus();
} else {
$('#query').blur();
}
});
This should do it.
var full = window.location.hash.replace('#', '')
var queryType = full.substring(0,full.indexOf("/"))
var query = full.replace(queryType, '');
EDIT: Updated code
if (window.location.hash != "") {
var full = window.location.hash.replace('#', '');
var queryType = full.substring(0,full.indexOf("/"));
console.log('#type_' + queryType);
$('#type_' + queryType).click();
}

Categories

Resources