There is a Layout page in my MVC app and with the help of a menĂ¼ link on this Layout page, I render a PartialView having only 5-6 input with no css or js import. As it can bee seen on the image below, it takes approximately 4 second just loading this PartialView and I think there is a big mistake regarding to this logic. Could you please have a look at the page and clarify me about where I did mistake?
Note: As far as I see the time consuming part of the AJAx method is in the success part (until $("#div-page-content").html(''); line). Is it needed or how can I change that part with a faster code block?
LayoutPage:
<a href="#" id="register" class="nav-link" onclick="renderPartial(event, 'Account', 'Create')">
<div id="div-page-content" class="page-content">
#RenderBody()
</div>
<script>
function renderPartial(e, controller, action) {
e.preventDefault();
var controllerName = controller;
var actionName = action;
if (String(actionName).trim() == '') {
return false;
}
if (typeof (controllerName) == "undefined") {
return false;
}
var url = "/" + controllerName + "/" + actionName;
$.ajax({
url: url,
data: { /* additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
success: function (data) {
var requestedUrl = String(this.url).replace(/[&?]X-Requested-With=XMLHttpRequest/i, "");
if (typeof (requestedUrl) == "undefined" || requestedUrl == 'undefined') {
requestedUrl = window.location.href;
}
// if the url is the same, replace the state
if (typeof (history.pushState) != "undefined") {
if (window.location.href == requestedUrl) {
history.replaceState({ html: '' }, document.title, requestedUrl);
}
else {
history.pushState({ html: '' }, document.title, requestedUrl);
}
}
$("#div-page-content").html('');
$("#div-page-content").append(data);
},
error: function (data) { onError(data); }
});
};
</script>
_PartialView:
<div>
//... code omitted fr borevity (there is no js or css import in this view
</div>
Controller:
[HttpPost]
public ActionResult Create()
{
return PartialView("_Register");
}
i am filling up my dropdowns using this ajax call ..selectItems create select option tags in html using attribute_map
var $el = this.$el(model);
var rule_title = "Job Family: ";
var attribute_map = [];
var current_object = this;
$el.append(this.getRuleTitle(rule_title, model));
jQuery.ajax({
url : "<%= Rails.configuration.url_prefix %>/team/index/get_rule_attribute_values",
type : "GET",
data : { name : "jobFamily" },
dataType : "json",
success : function(data){
var attribute_array = data.value.rule_attribute_values;
attribute_array.sort(function(a,b){
if(a.display_name > b.display_name){
return 1;
}
if(a.display_name < b.display_name){
return -1;
}
return 0;
});
var index = 0;
var obj;
for (obj in attribute_array){
attribute_map[index] = [];
attribute_map[index][0] = attribute_array[index].display_name + " ( " + attribute_array[index].internal_name + " ) " ;
attribute_map[index][1] = attribute_array[index].internal_name;
index++;
}
current_object.selectItems($el,
attribute_map,
"jobFamily", model.jobFamily, {multiple : "multiple", "data-placeholder" : "Add Constraint..."}, "400px");
},
complete : function() {
console.log("completed");
},
error : function(jqXHR, textStatus,errorThrown){
var requestResponse = {
httpStatus: jqXHR.status,
error:jqXHR.statusText,
};
}
});
when i put async as false ..event handler works fine but in synchronous call , the just doesn't do anything
event handler looks like
$('.chosen-select jobFamily').on('change',function(evt, params){
console.log("completeddddddd");
var value = $('.chosen-select jobFamily').val();
console.log(value);
if (value == null) {
// Input is empty, so uncheck the box.
$('.jobFamily').prop("checked", false);
} else {
// Make sure the box is checked.
$('.jobFamily').prop("checked", true);
}
});
});
where '.chosen-select jobFamily' is class of select tag and '.jobFamily' is class of check box ... i have tried writing my jquery inside complete argument of ajax call , i tried writing my jquery inside
$('document).bind('ajaxComplete',function({
//above jquery
});
please help . i have spent more than 2 days on that . all code lies inside ready function.
I would like to load a twitter popup box in jquery using (ajax?)
Here is my original code, which loads the twitter box in a new window:
function twitter_click() {
var twtTitle = document.title;
var twtUrl = location.href;
var maxLength = 140 - (twtUrl.length + 1);
if (twtTitle.length > maxLength) {
twtTitle = twtTitle.substr(0, (maxLength - 3)) + '...';
}
var twtLink = 'http://twitter.com/home?status=' + encodeURIComponent(twtTitle + ' ' + twtUrl);
window.open(twtLink,'','width=565, height=540');
}
Here is the code for the jquery popup box.
function showUrlInDialog(url, options){
options = options || {};
var tag = $("<div></div>"); //This tag will the hold the dialog content.
$.ajax({
url: url,
type: (options.type || 'GET'),
beforeSend: options.beforeSend,
error: options.error,
complete: options.complete,
success: function(data, textStatus, jqXHR) {
if(typeof data == "object" && data.html) { //response is assumed to be JSON
tag.html(data.html).dialog({modal: options.modal, title: data.title}).dialog('open');
} else { //response is assumed to be HTML
tag.html(data).dialog({modal: options.modal, title: options.title}).dialog('open');
}
$.isFunction(options.success) && (options.success)(data, textStatus, jqXHR);
}
});
}
<img src="twitter_button.jpg>
I don't know anything about coding so if someone can please combine these two scripts so that the twitter content of the first script loads into the jquery popup script that would make my day! Thanks. Pia
Start by changing this:
window.open(twtLink,'','width=565, height=540');
to this:
showUrlInDialog(twtLink, {error: function() { alert('Could not load form') }});
Then to run it, use this:
<img src="twitter_button.jpg>
I have a jQuery search script that uses tabs for the user to define the search type they want. A tab is selected as the default by using $('#type_search').click(); however this causes a problem when refreshing a results page. If a different search type is selected and then the page is refreshed, the default tab is automatically selected so it doesn't return the correct results even though the page URL says it is correct.
My question is, how can I define the default tab from the section in the URL if a query is active and if there is no active query use the default tab? I hope you can understand what I'm saying.
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;
});
$('#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';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search';
$('#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();
}
var textlength = $('#query').val().length;
if (textlength <= 0) {
$('#query').focus();
} else {
$('#query').blur();
}
});
Ah, I had that problem too. It's pretty simple. On page ready you just take the anchor from the URL and simulate a click.
$(document).ready(function() {
url = document.location.href.split('#');
$('#'+url[1]).click();
});
I am implementing jQuery UI Autocomplete and am wondering if there is any way to only allow a selection from the suggested results that are returned as opposed to allowing any value to be input into the text box.
I am using this for a tagging system much like the one used on this site, so I only want to allow users to select tags from a pre-populated list returned to the autocomplete plugin.
You could also use this:
change: function(event,ui){
$(this).val((ui.item ? ui.item.id : ""));
}
The only drawback I've seen to this is that even if the user enters the full value of an acceptable item, when they move focus from the textfield it will delete the value and they'll have to do it again. The only way they'd be able to enter a value is by selecting it from the list.
Don't know if that matters to you or not.
I got the same problem with selected not being defined. Got a work-around for it and added the toLowerCase function, just to be safe.
$('#' + specificInput).autocomplete({
create: function () {
$(this).data('ui-autocomplete')._renderItem = function (ul, item) {
$(ul).addClass('for_' + specificInput); //usefull for multiple autocomplete fields
return $('<li data-id = "' + item.id + '">' + item.value + '</li>').appendTo(ul);
};
},
change:
function( event, ui ){
var selfInput = $(this); //stores the input field
if ( !ui.item ) {
var writtenItem = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val().toLowerCase()) + "$", "i"), valid = false;
$('ul.for_' + specificInput).children("li").each(function() {
if($(this).text().toLowerCase().match(writtenItem)) {
this.selected = valid = true;
selfInput.val($(this).text()); // shows the item's name from the autocomplete
selfInput.next('span').text('(Existing)');
selfInput.data('id', $(this).data('id'));
return false;
}
});
if (!valid) {
selfInput.next('span').text('(New)');
selfInput.data('id', -1);
}
}
}
http://jsfiddle.net/pxfunc/j3AN7/
var validOptions = ["Bold", "Normal", "Default", "100", "200"]
previousValue = "";
$('#ac').autocomplete({
autoFocus: true,
source: validOptions
}).keyup(function() {
var isValid = false;
for (i in validOptions) {
if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
isValid = true;
}
}
if (!isValid) {
this.value = previousValue
} else {
previousValue = this.value;
}
});
This is how I did it with a list of settlements:
$("#settlement").autocomplete({
source:settlements,
change: function( event, ui ) {
val = $(this).val();
exists = $.inArray(val,settlements);
if (exists<0) {
$(this).val("");
return false;
}
}
});
i just modify to code in my case & it's working
selectFirst: true,
change: function (event, ui) {
if (ui.item == null){
//here is null if entered value is not match in suggestion list
$(this).val((ui.item ? ui.item.id : ""));
}
}
you can try
Ajax submission and handling
This will be of use to some of you out there:
$('#INPUT_ID').autocomplete({
source: function (request, response) {
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: autocompleteURL,
data: "{'data':'" + $('INPUT_ID').val() + "'}",
dataType: 'json',
success: function (data) {
response(data.d);
},
error: function (data) {
console.log('No match.')
}
});
},
change: function (event, ui) {
var opt = $(this).val();
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: autocompleteURL,
data: "{'empName':'" + name + "'}",
dataType: 'json',
success: function (data) {
if (data.d.length == 0) {
$('#INPUT_ID').val('');
alert('Option must be selected from the list.');
} else if (data.d[0] != opt) {
$('#INPUT_ID').val('');
alert('Option must be selected from the list.');
}
},
error: function (data) {
$(this).val('');
console.log('Error retrieving options.');
}
});
}
});
I'm on drupal 7.38 and
to only allow input from select-box in autocomplete
you only need to delete the user-input at the point,
where js does not need it any more - which is the case,
as soon as the search-results arrive in the suggestion-popup
right there you can savely set:
**this.input.value = ''**
see below in the extract from autocomplete.js ...
So I copied the whole Drupal.jsAC.prototype.found object
into my custom module and added it to the desired form
with
$form['#attached']['js'][] = array(
'type' => 'file',
'data' => 'sites/all/modules/<modulname>_autocomplete.js',
);
And here's the extract from drupal's original misc/autocomplete.js
modified by that single line...
Drupal.jsAC.prototype.found = function (matches) {
// If no value in the textfield, do not show the popup.
if (!this.input.value.length) {
return false;
}
// === just added one single line below ===
this.input.value = '';
// Prepare matches.
=cut. . . . . .
If you would like to restrict the user to picking a recommendation from the autocomplete list, try defining the close function like this. The close function is called when the results drop down closes, if the user selected from the list, then event.currentTarget is defined, if not, then the results drop down closed without the user selecting an option. If they do not select an option, then I reset the input to blank.
//
// Extend Autocomplete
//
$.widget( "ui.autocomplete", $.ui.autocomplete, {
options: {
close: function( event, ui ) {
if (typeof event.currentTarget == 'undefined') {
$(this).val("");
}
}
}
});
You can actually use the response event in combination to the change event to store the suggested items like so:
response: function (event, ui) {
var list = ui.content.map(o => o.value.toLowerCase());
},
change: function (event, ui) {
if (!ui.item && list.indexOf($(this).val().toLowerCase()) === -1 ) { $(this).val('');
}