How to populate data in autocomplete textbox when a button is clicked? - javascript

I have a textbox with jquery autocomplete feature.It populates data based on a condition if '/' is entered and then a character.But i want to populate all the data in the autocomplete list when a button is clicked inspite of what ever data is there in the textbox.
My button :
<asp:Button ID="Button2" runat="server" Text="Button" />
And my autocomplete function with condition to populate data is:
<script type="text/javascript">
function pageLoad(sender, args) {
$(function () {
$("#<%=txtCu.ClientID %>").autocomplete({
source: function (request, response) {
if(request.term.indexOf("/") == (request.term.length-1) && enterFlag)
{
var term = request.term.slice(0,-1)
$.ajax({
url: '<%=ResolveUrl("~/Webservice.asmx/GetCus") %>',
data: "{ 'prefix': '" + term + "'}",
dataType: "json",
type: "POST",
async: false,
mustMatch: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('^')[0],
val: item.split('^')[1]
}
}))
},
error: function (response) {
},
failure: function (response) {
}
});
};
},
select: function (e, i) {
$("#<%=hdnCr.ClientID %>").val(i.item.val);
if (i.item.val == "No Records Found") {
$("#<%=hdnCr.ClientID %>").val(-1);
document.getElementById('<%=txtCu.ClientID%>').value = "";
return false;
}
checkddlcustomerinfo();
},
minLength: 0
}).bind('focus', function () { $(this).autocomplete("search"); })
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>").data("item.autocomplete", item).append("<div><table><tr><td width='200px'>" + item.label + "</td>" + "<td width='110px'>" + item.val.split('~')[6] + "</td>" + "<td>" + item.val.split('~')[4] + "</td></tr></table></div>").appendTo(ul);
};
});
}

Do this to get the expected result
ASP Button, add class property CssClass
<asp:Button ID="Button2" runat="server" Text="Button" CssClass="btn"/>
and jQuery Part
$(document).on("click","btn",function(e){
e.preventDefault();
$("#<%=txtCu.ClientID %>").autocomplete("search", "");
$("#<%=txtCu.ClientID %>").autocomplete("select",function (e, i) {
$("#<%=hdnCr.ClientID %>").val(i.item.val);
if (i.item.val == "No Records Found") {
$("#<%=hdnCr.ClientID %>").val(-1);
document.getElementById('<%=txtCu.ClientID%>').value = "";
return false;
}
checkddlcustomerinfo();
}
);
});
to close autocomplete on outside click
$(document).on('click', function(e){
var target = $(e.target);
if(target.attr("id") != "txtCu" && target.attr("class") != "btn")
{
$("#<%=txtCu.ClientID %>").autocomplete('close');
}
});
Note: You must set minLength: 0 in your autocomplete
Working DEMO

see this edit to your autocomplete code:
$.ajax({
url: '<%=ResolveUrl("~/Webservice.asmx/GetCus") %>',
data: "{ 'prefix': '" + term + "'}",
dataType: "json",
type: "POST",
async: false,
mustMatch: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('^')[0],
val: item.split('^')[1]
}
}))
$('.ui-autocomplete').hide(); // <-- this line
},
edit XHTML :
<asp:Button ID="Button2" runat="server" Text="Button" Class="myBtn"/>
ps. it might be CssClass="myBtn" haven't used web forms in a bit
then jQuery:
$(function(){
$(document).on('click', '.myBtn', function(e){
e.preventDefault();
//maybe a prevent propigation line too just for other browsers like IE
$('.ui-autocomplete').show();
});
});
});

Related

Jquery repeater with select2 not working properly

I am seaching from 2 days about this issue.
The first element is working perfectly. But after repeat the element, previous element's select2 fields destroyed automatically.
There is two rop divs in repeater. When first one selected by the ajax request I am appending the options to values section.
Here is the screenshot for reference.
Here is the code for repeater and select2 initialization.
<script>
$(function () {
$(".attribute_list").on('change', ".attribute", function (e) {
var attr_name = $(this).attr('name');
var attr_id = $(this).val();
$.ajax({
type: "POST",
url: "{{ route('products.getValue') }}",
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
},
contentType: "application/json",
dataType: "json",
data: '{"attr_id": "' + attr_id + '", "attr_name" : "' + attr_name + '"}',
success: function (data) {
var attribute_value = data.attribute_value;
var field_name = 'select[name="product_attribute[' + data.field_name + '][attribute_values][]"]';
if (attribute_value) {
$(field_name).empty();
$.each(attribute_value, function (key, value) {
$(field_name).append('<option value="' + value.id + '">' + value.value + '</option>');
});
// $(field_name).select2();
} else {
$(field_name).empty();
}
}
});
});
});
</script>
<script>
// $("#attribute_button").click(function(){
// $('#attribute_values').select2({
// placeholder: "select attribute value"
// });
// });
window.onload = function () {
$('.attribute_values').select2({
placeholder: "select attribute value",
allowClear: true
});
}
$('.repeater').repeater({
initEmpty: false,
show: function () {
$(this).slideDown();
$('.attribute_values').select2({
placeholder: "select attribute value"
});
},
hide: function (deleteElement) {
if (confirm('Are you sure you want to delete this element?')) {
$(this).slideUp(deleteElement);
}
},
ready: function (setIndexes) {
},
})

jquery ui- Autocomplete selects value instead of label

This is my coding
$("#txtBox").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
url: '#Url.Action("Get", "Ctrl")',
dataType: 'json',
data: "{ 'mode': 'associate','prefix': '" + request.term + "' }",
contentType: "application/json;charset=utf-8",
success: function (data) {
var transformed = $.map(data, function (item) {
return {
label: item.Name,
value: item.Id
};
});
response(transformed);
},
error: function() {
alert('error');
},
});
},
minLength: 3,
select: function (event, ui) {
console.log('ui.item.label', ui.item.label);
$('#txtBox').val(ui.item.label);
},
focus: function (event, ui) {
console.log('ui.item.label - focus', ui.item.label);
$('#txtBox').val(ui.item.label);
}
});
});
I am getting Name and Id from c# controller as Json. I want to the auto complete textbox to display Name and while sending it back to backend while saving, I wanted to send the Id of the Name. But now when I type the name and select the name from the list of suggestions. The Id gets displayed in the text box instead of name.Where am i making the mistake. Can some one guide me on this.
I would suggest you to keep two <input /> one type=text and other type=hidden. You can initialize autocomplete on the type=text, and set the value in type=hidden and in server you can access the value of type hidden.
e.g.
<input type="text" id="txtBox" name="label" />
<input type="hidden" id="valBox" name="value" />
$("#txtBox").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
url: '#Url.Action("Get", "Ctrl")',
dataType: 'json',
data: "{ 'mode': 'associate','prefix': '" + request.term + "' }",
contentType: "application/json;charset=utf-8",
success: function (data) {
var transformed = $.map(data, function (item) {
return {
label: item.Name,
value: item.Id
};
});
response(transformed);
},
error: function() {
alert('error');
},
});
},
minLength: 3,
select: function (event, ui) {
console.log('ui.item.label', ui.item.label);
$('#txtBox').val(ui.item.label);
$('#valBox').val(ui.item.value);
},
focus: function (event, ui) {
console.log('ui.item.label - focus', ui.item.label);
$('#txtBox').val(ui.item.label);
}
});
});
In your controller, you can access both values Request["label"], Request["value"]

jQuery UI autocomplete no response bind or select is called

Jquery autocomplete for textbox search is not working ,webservice is called but the value is not binded to the textbox .please let me know what's wrong in this code.
.aspx page:
<asp:TextBox ID="tbStudentName" runat="server" class="tbStudentName" />
<asp:Button ID="btnStudentSearch" runat="server" meta:resourcekey="btnSearch" OnClick="btnStudentSearch_Clicked" />
Script:
function AutoCompleteName(target) {
var xhr;
$j("." + target.className).autocomplete({
source: function (request, response) {
if (xhr && xhr.readystate != 4) {
xhr.abort();
}
xhr = $j.ajax({
url: "../ServiceInterface/StudentLookupService.asmx/StudentSearch",
data: "{'pStudentId': '', 'pStudentName': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($j.map(data.d, function (item) {
return {
label: item.StudentId + ' : ' + item.LastName + ', ' + item.FirstName + ' ' + item.MiddleName,
value: item.FirstName + ' ' + item.LastName
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
response([]);
}
});
},
select: function (event, ui)
{
$j("." + target.className).val = ui.item.firstName + ' ' + ui.item.lastName;
return true;
},
minLength: 1
});
}
Also when i enter two character in search box am getting error function,for 3 or more characters only the web service is called.
Please let me know your suggestions to make it work

how enable a button if entered text is valid for autocomplete function?

i have a textbox with autocomplete feature,and a button.I want to enable the button only when a value is selected from the autocomplete list.
how to do this?
Here is my autocomplete function:
<script type="text/javascript">
$(document).ready(function () {
$("#<%=xyz.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/WebService.asmx/Get") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#<%=abc.ClientID %>").val(i.item.val);
},
minLength: 0
}).bind('focus', function () { $(this).autocomplete("search"); });
});
</script>
In your select function add this:
select: function (e, i) {
$("#<%=abc.ClientID %>").val(i.item.val);
$("#buttonid").prop("disabled", true); // true disabled, false enabled
},
EDIT:
$("#buttonid").prop("disabled", false); // this put button enabled
JsFiddle - Example
For a plain button you'll want to set the the button as disabled when the document loads, e.g.
$(document).ready(function () {
$('#btn')[0].disabled = true;
...
and then enable it with the select function, e.g.
select: function (e, i) {
$("#<%=abc.ClientID %>").val(i.item.val);
$('#btn').disabled = false; // <-- enables button
},
Try This: The following will be called when you perform select (use keyboard to select, dont know about mouse select)
$( "#<%=xyz.ClientID %>"" ).on( "autocompleteselect", function( event, ui ) {
$("#buttonid").prop("disabled", false);
});

dynamically create radiobuttons and labels

Ok what I want to achieve is that it creates this automatically for each record I got back from my webservice.
<label for="ZAALID_1">Zaal 1</label>
<input id="ZAALID_1" type="radio" name="RESERVATIE.ZAALID" value="1" MSGCHECKED="~IF(CHKPROP(#RESERVATIE.ZAALID,'1'),CHECKED,)~" />
I am calling this webservice with an ajax call. There is nothing wrong with this call. I tested it with printing down the values.
$.ajax({
url: "~SYSTEM.URL~~CAMPAIGN.URL~/SelligentMobile/Webservice/WebService.asmx/getReservaties",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'DATUM_BEGIN':'2012-05-09 10:10:36','DATUM_EINDE':'2012-05-09 12:10:45'}",
success: function (response) {
var zalen = response.d;
if (zalen.length > 0) {
$.each(zalen, function (index, zaal) {
createRadioElement(zaal.zaalId);
createLabel(zaal.zaalNaam,zaal.zaalId);
});
}
}
});
So I think there is an mistake in CreateRadioElement and createLabel.
Here are these two functions.
function createRadioElement( id ) {
var radioInput;
try {
var radioHtml = '<input id="ZAALID_' + id + '" type="radio" name="RESERVATION.ZAALID" value="' + id + '" MSGCHECKED="~IF(CHKPROP(#RESERVATIE.ZAALID,' + 1 + '),CHECKED,)~ ';
radioHtml += '/>';
radioInput = document.createElement(radioHtml);
} catch( err ) {
radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', 'RESERVATION.ZAALID');
}
return radioInput;
}
function createLabel(name,id) {
var label;
var labelHTML = '<label for="ZAALID_' + id + '">'+ name +'</label>';
label = document.createElement(labelHTML);
return label;
}
Now another thing that I want to do is that is places these radiobuttons inside the div with id=zaalField
here is the HTML of that div
<div id=ZaalField data-role="fieldcontain" class="knoppen_boven">
<LABEL for=zaal>Zalen ter beschikking: </LABEL>
//Here should go the radiobuttons and labels.
</div>
Can anybody help ?
Kind regards
---EDIT---
function getZalen()
{
var dateB = $("#DATUM_BEGIN").val();
var dateE = $("#DATUM_EINDE").val();
console.log(dateB);
$.ajax({
url: "~SYSTEM.URL~~CAMPAIGN.URL~/SelligentMobile/Webservice/WebService.asmx/getReservaties",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'DATUM_BEGIN':'2012-05-09 10:10:36','DATUM_EINDE':'2012-05-09 12:10:45'}",
success: function (response) {
var zalen = response.d;
alert(JSON.stringify(zalen));
if (zalen.length > 0) {
$.each(zalen, function (i, entity) {
$('ZaalField ').append(
$('<label />', { 'for': 'ZAALID_' + entity.zaalId, 'text': entity.zaalNaam }),
$('<input />', { 'id': 'ZAALID_' + entity.zaalId, 'type': 'radio', 'name': 'RESERVATION.ZAALID', 'value': entity.zaalId, 'MSGCHECKED': '~IF(CHKPROP(#RESERVATIE.ZAALID,' + 1 + '),CHECKED,)~ ' }), $('<br />'));
});
}
}
});
}
$(document).ready(function () {
var data = { "d": [{ "__type": "Reservatie", "zaalId": 2, "opmerking": null, "zaalNaam": "Zaal 2" }, { "__type": "Reservatie", "zaalId": 3, "opmerking": null, "zaalNaam": "Zaal 3"}] };
// $.ajax({
// url: "/SelligentMobile/Webservice/WebService.asmx/getReservaties",
// type: "POST", contentType: "application/json; charset=utf-8",
// dataType: "json", data: { 'DATUM_BEGIN': '2012-05-09 10:10:36', 'DATUM_EINDE': '2012-05-09 12:10:45' },
// success: function (data) {
if (data.d.length > 0) {
$.each(data.d, function (i, entity) {
$('body').append(
$('<label />', { 'for': 'ZAALID_' + entity.zaalId, 'text': entity.zaalNaam }),
$('<input />', { 'id': 'ZAALID_' + entity.zaalId, 'type': 'radio', 'name': 'RESERVATION.ZAALID', 'value': entity.zaalId, 'MSGCHECKED': '~IF(CHKPROP(#RESERVATIE.ZAALID,' + 1 + '),CHECKED,)~ ' }), $('<br />'));
});
}
// }
// });
});
function createLabel(id, name){
var name = "Zaal 2";
var label = document.createElement("label");
label.setAttribute("for","RANDOM"+id);
label.innerHTML = name;
return label;
}
var label = createLabel(2, "Zaal 2");
$(document.body).append(label); //add it to the body, or to whatever else you want to add it to.
This code works for me, while the code you have written doesn't.

Categories