I have two textboxes (input type text) on the same HTML that use the same autocomplete. The first text box works fine, but the second text box do not render the results. It communicate with the server and I get the results, but the rendering function is not even called. The only difference between the inputs is that one is in a div that start hidden and I show kind like Dialog window by setting z-order high and masking the HTML.
Here is the CSS for the div where the second input box is located.
.windowBooking {
position:absolute;
width:450px;
/* height:200px; */
display:none;
z-index:9999;
padding:20px;
}
The autocomplete function:
$(".makeClass").autocomplete({
source: function (request, response) {
$('#Code').val(); //clear code value
$.ajax({
url: "myUrl",
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json', //What kind of Result is expected. (Ex json, xml, etc)
data: "{'searchItem':'" + request.term + "'}",
success: function (data) {
var item = [];
var len = data.d.length;
for (var i = 0; i < len; i++) {
var obj = { name: data.d[i].MakeReport, code: data.d[i].MakeCode };
item.push(obj);
}
response(item);
}
})
},
focus: function (event, ui) {
$(this).val(ui.item.name);
return false;
},
select: function (event, ui) {
$('#Code').val(ui.item.code);
$('#Name').val(ui.item.name);
$(this).val(ui.item.name);
return false;
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
},
minLength: 2,
delay: 250
}).data("autocomplete")._renderItem = function (ul, item) {
var temp = item.name;
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.name + "</a>")
.appendTo(ul);
};
The input boxes use the same class to call the autocomplete.
<input id="OtherMake" type="text" maxlength="30" size="20" class="makeClass"/> <!-- It works -->
<div id="dialogPlus" class="windowBooking">
:
<input type="text" id="MakeName" class="makeClass" /> <!-- doesn't work.-->
:
</div>
Any ideas, why render on one input box and no in the other input box? Let me make clear, on the second input box the only thing not working is the renderItem function which for some reason it doesn't get executed. On the screen, you can see a lot of undefined but if you select any of the undefined values then the input box is filled with the correct value.
I had a similar issue applying _renderItem() on a class selector but solved it with
$.each($( ".makeClass" ), function(index, item) {
$(item).data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.value + " - " + item.label + "</a>")
.appendTo(ul);
};
});
I still don't know what is causing the problem, but I was able to make it work by using the ID instead of using a class to access autocomplete. My guess is that an appended render function cannot be shared between two input boxes? I don't know, if somebody knows the answer and could share with us, it would be great.
Anyway, if somebody happen to have the same weird problem as me and it is stuck with the problem, here is how I solved it. As, I didn't want to repeat the same code twice, I moved all the autocomplete logic to a var and the render function to another var and used the input box ID to assign autocomplete.
var makeAutocomplete = {
source: function (request, response) {
$('#Code').val(); //clear code value
$.ajax({
url: myUrl,
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json', //What kind of Result is expected. (Ex json, xml, etc)
data: "{'searchItem':'" + request.term + "'}",
success: function (data) {
var item = [];
var len = data.d.length;
for (var i = 0; i < len; i++) {
var obj = { name: data.d[i].MakeReport, code: data.d[i].MakeCode };
item.push(obj);
}
response(item);
}
})
},
focus: function (event, ui) {
$(this).val(ui.item.name);
return false;
},
select: function (event, ui) {
$('#Code').val(ui.item.code);
$('#Name').val(ui.item.name);
$(this).val(ui.item.name);
return false;
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
},
minLength: 2,
delay: 250
};
var renderList = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.name + "</a>")
.appendTo(ul);
};
$("#OtherMake").autocomplete(makeAutocomplete).data("autocomplete")._renderItem = renderList;
$("#MakeName").autocomplete(makeAutocomplete).data("autocomplete")._renderItem = renderList;
I have this bug too. This is strange that with id as selector _renderItem works correct. I found a quick hack for this issue:
$.ui.autocomplete.prototype._renderItem = function (ul, item) {}
For me, what fixed it was using the appendTo option from the jQuery UI AutoComplete.
My problem was that this input field was inside a modal that wasn't shown at first. Affecting it to the input's parent fixed the problem!
Related
I have a Kendo Grid where I have column that has a autocomplete on it where a user enters letters for a part nbr search. (On a side note - I tried the Kendo autocomplete and could not get that going so went with the Jquery autocomplete instead)
This works fine, but would like to have when a user types, it transforms their lower case letters to uppercase.
Is this possible in jquery or do I have to use an event inside the grid.
I've tried different scenarios and none seem to work. As you can see, I commented out what I tried.
I do have this code in other functions and this does work great, but cannot use it within a grid it seems.
$(this).val($(this).val().toUpperCase());
//Dropdown Autocomplete Part Nbr within Kendo Grid...
function AutoSearchPartNbrGrid(container, options){
var y = $('<input data-bind="value:' + options.field + '"/>')
.appendTo(container)
.autocomplete({
minLength: 4,
autoFocus: false,
source: function (request, response) {
$.ajax({
url: String.format('{0}/{1}', $('#hfAutoCompletePartsApiUrl').val(), request.term.toUpperCase()),
type: 'GET',
cache: false,
dataType: 'json',
success: function (json) {
response($.map(json, function (data, id) {
return {label: data.label,value: data.value }
}));
}
});
},
edit: function (e) {
//$(this).val($(this).val().toUpperCase());
//autopartnbr = $(this).val();
//Search Fields to populate the parts grid...
//$(this).on('keypress', function (e) {
// var txt = $(this);
// if (e.keyCode === 13) {
// if (txt.val() !== '') {
// autopartnbr = $(this).val();
// }
// return false;
// }
//});
//var grid = $('#divconfigs').data('kendoGrid');
return false;
},
select: function (e, ui) {
autopartnbr = $(this).val().toUpperCase();
var grid = $('#divconfigs').data('kendoGrid');
return false;
},
error: function (xhr, textStatus, errorThrown) {
console.log('error', textStatus, errorThrown);
},
failure: function (response) { alert(response.responseText) }
});
}
I expect that when you type a part nbr in and if you have a lowercase letter, it would automatically transform it to an uppercase.
Thanks
I suppose that the purpose of such a transformation (lowercase to uppercase) is to compare it with your database entries. In this case, you could use the autocomplete-function and add a matcher-function to perform the transformation :
<input type="text" name="query" id="query" value="" />
<script>
var names=["MYUPPERCASE-ENTRY1","MYUPPERCASE-ENTRY2","MYUPPERCASE-ENTRY3"];
$( "#query" ).autocomplete({
source: function( request, response ) {
matcher=new RegExp("^"+ $.ui.autocomplete.escapeRegex(request.term ), "i" );
response( $.grep( names, function( value ) {
value = value.label || value.value || value;
return matcher.test(value.toString().toUpperCase());
}) );
},
minLength: 3
});
</script>
More info : https://jqueryui.com/autocomplete/
I have a dropdown which gets its value from a model and is first populated. On click of that dropdown, I populate other values using AJAX. I am able to populate the dropdown but once I select an option from the dropdown, it gets reset to first value in the dropdown. What I want is the dropdown to populate once on click and then function like a normal dropdown. How do I put a condition for it?
This is the code for initially setting the dropdown value with the defined value 'field.Value'
ddlValue = "<option value="+field.Value+ " selected='selected'>" + field.Value+"</option>";
<td><select id='#String.Format("selValue{0}", field.Field)' class='ddlValue'>#Html.Raw(ddlValue)</select></td>
And this is the AJAX function which populates it.
$('body').on('click', '.ddlValue', function () {
var target = event.target.id;
var rowId = $('#' + target).closest("tr").prop("id");
var field = $('#' + rowId).find(".fieldvalue").html();
$.ajax({
cache: false,
url: '#Url.Action("PopulateDropdown", "AdvancedSearch")',
type: "POST",
data: { Field: field }
}).done(function (data) {
var listb = $('#' + target);
listb.empty();
$.each(data.value, function (index, value) {
listb.append($('<option>', {
value: value,
text: value
}, '<option/>'))
});
});
});
If you want the ajax population to happen only once, you need to remove the event listener after it has occurred. Something like so:
$('.ddlValue').on('click', function () {
$(this).off('click'); //This removes the event after it has happened once.
var target = event.target.id;
var rowId = $('#' + target).closest("tr").prop("id");
var field = $('#' + rowId).find(".fieldvalue").html();
$.ajax({
cache: false,
url: '#Url.Action("PopulateDropdown", "AdvancedSearch")',
type: "POST",
data: { Field: field }
}).done(function (data) {
var listb = $('#' + target);
listb.empty();
$.each(data.value, function (index, value) {
listb.append($('<option>', {
value: value,
text: value
}, '<option/>'))
});
});
});
Please note, the follow will not work:
$('body').on('click', '.ddlValue', function () {
$(this).off('click');
...
This seems like a silly way of doing this. You could do the same operation on loan without having any interaction with the user to populate the dropdown.
That being said to fix your solution simply add a global variable
$first = true
$('body').on('click', '.ddlValue', function () {
if($first) {
$first = false
var target = event.target.id;
var rowId = $('#' + target).closest("tr").prop("id");
var field = $('#' + rowId).find(".fieldvalue").html();
$.ajax({
cache: false,
url: '#Url.Action("PopulateDropdown", "AdvancedSearch")',
type: "POST",
data: { Field: field }
}).done(function (data) {
var listb = $('#' + target);
listb.empty();
$.each(data.value, function (index, value) {
listb.append($('<option>', {
value: value,
text: value
}, '<option/>'))
});
}
});
});
Hello everyone I am newbie in java-script. So I hope that you can help me. When user set data into city field, i want to set data in country field automatically.
I have an xml file:
<ROWSET>
<ROW>
<city></city>
<country></country>
</ROW>
</ROWSET>
In html document I have two input fields
<input id="id_city">
<input id="country">
Here is my js code:
$.ajax({
url: "/media/xml/country.xml", //your url
type: "GET", //may not need this-fiddle did-default is GET
dataType: "xml",
success: function(xmlResponse) {
var data = $("ROW", xmlResponse).map(function() {
return {
value: $("city", this).text() + ", " + ($.trim($("country", this).text()) || "(unknown country)")
};
}).get();
$("#id_city").autocomplete({
source: function(req, response) {
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp("^" + re, "i");
response($.grep(data, function(item) {
return matcher.test(item.value);
}));
},
minLength: 2,
select: function(event, ui) {
$("p#result").html(ui.item ? "Selected: " + ui.item.value + ", cityId: " + ui.item.id : "Nothing selected, input was " + this.value);
}
});
}
});
I don't know how to set automatically data to country field
Thanks.
Ok this should do it for you. I've change the definition of data so it now has three properties:
label which is the same as your original value.
city so you can put it into your #city input.
country so you can put it into your #country input.
This means you can use ui.item.city and ui.item.country in the select property of the autocomplete.
Because there are now have three properties you need to customise the autocomplete and tell it to use label for it's options which is what the _renderItem section does.
$.ajax({
url: "/media/xml/country.xml",
type: "GET",
dataType: "xml",
success: function (xmlResponse) {
var data = $("ROW", xmlResponse).map(function () {
return {
label: $("city", this).text() + ", " + ($.trim($("country", this).text()) || "(unknown country)"),
city: $.trim($("city", this).text()),
country: $.trim($("country", this).text())
};
}).get();
$("#id_city").autocomplete({
source: function (req, response) {
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp("^" + re, "i");
response($.grep(data, function (item) {
return matcher.test(item.city);
}));
},
minLength: 2,
select: function (event, ui) {
$("p#result").html(ui.item ? "Selected: " + ui.item.label + ", cityId: " + ui.item.city : "Nothing selected, input was " + this.value);
$("#id_city").val(ui.item.city);
$("#country").val(ui.item.country);
return false;
},
_renderItem: function (ul, item) {
return $("<li></li>")
.data("value", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
}
});
}
});
Also I've created a "working" Fiddle (because your code is using an ajax XML source I've hardcoded the response in a variable and generated the autocomplete in the error property as the ajax request will always fail from jsfiddle.net).
I have setup select2 exactly as the example mentioned in this link Load ajax data into select2.
In that example control i can type some text press the arrow keys and when i hit tab it selects the item i was highlighted on.
But in my case when i hit tab nothing happens, i have to hit ENTER key to have it selected.
Or click the mouse which is bad when my users are filling out forms.
How to make it so that it does the selection on hitting TAB key as well?
Code -
<input id="taskRelationShip" name="RelatedToId" type="hidden" value="" />
$('#taskRelationShip').css('width', '400px').select2({
minimumInputLength: 2,
ajax: {
quietMillis: 10,
url: '/Tasks/TaskRelatedToItemsSearch',
dataType: 'json',
data: function(term, page) {
return {
query: term
};
},
results: function (data, page) {
return { results: data };
}
},
initSelection: function (element, callback) {
var id = $(element).val();
if (id !== "") {
$.ajax("/Tasks/LoadRelatedItem/" + id).done(function(data) {
callback(data);
});
}
},
formatResult: function (item) {
var img = item.id.substring(0, 3) === 'OPP' ? 'opportunity' : 'project';
var format = '<i class="icon-{0} avatar link-icon"></i> ';
img = ins.utils.formatString(format, img);
return '<div>' + img + item.value + '</div>';
},
formatSelection: function (item) {
return item.value;
},
dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
escapeMarkup: function (m) { return m; }
});
You need to add selectOnBlur: true, I believe.
I have this code using this code I am inserting an item from one list box to other list box. I need to set the default selection for tagrget list box item when it is added.
please can any body help me out how to set the deafult selection to the list box.
How to set the default selection to the currently added item to the list box
function DoInsert(ind) {
var sourceIndex = $("#lstAvailableCode").val(); /// Selected Item to add
var targetIndex = $("#lstCodelist").val(); /// added item to the list box(target list box)
var success = 0;
var rightSelectedIndex = $("#lstCodelist").get(0).selectedIndex;
var functionName = "/Ajax/SaveCodeforInsert";
if (ind == "plan") {
functionName = "/Ajax/SaveCodeforInsertForPlan";
}
$.ajax({
type: "POST",
traditional: true,
url: functionName,
async: false,
data: "ControlPlanNum=" + $("#ddControlPlan").val() + "&LevelNum=" + $("#ddlLevel").val() + "&ColumnNum=" + $("#ddlColumn").val() + "&SourcbaObjectID=" + sourceIndex + "&TargetbaObjectID=" + targetIndex + "&userID=<%=Model.userID%>",
dataType: "json",
error: function (data) {
alert("Error Adding Code");
FinishAjaxLoading();
},
success: function (data) {
if (data == 0) { success = 1; } else { success = data; }
FinishAjaxLoading();
}
});
could you use
.focus()
Example:
$("#lstCodelist").focus();
you can use .focus in the success callback to set the focus
$("element").focus()