dynamically create radiobuttons and labels - javascript

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.

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) {
},
})

How to solve Uncaught TypeError: Cannot read property 'length' of null

I have installed a wp plugin , When I use default wp theme , it works fine but when I use another theme it does not loads one of the tabs , by inspect element I get this
Uncaught TypeError: Cannot read property 'length' of null
The code on the page it is mentioning is this
function show_submissions(page,search)
{
if (typeof page=='string')
{
var data = 'action=formcraft_page&page='+page;
}
else
{
var data = 'action=formcraft_page&search='+search;
var page = 0;
}
jQuery('#subs tbody').html('<tr><td colspan="6"><center><div style="margin: 30px auto; width: 30px;font-size: 14px; color: #888">loading...</div></center></td></tr>')
jQuery.ajax({
url: ajaxurl,
type: "POST",
dataType: "json",
data: data,
success: function (response) {
jQuery('.fc_pagination .active').removeClass('active');
jQuery('.fc_pagination .page:nth-child('+page+')').addClass('active');
if (response.length==0)
{
jQuery('#subs tbody').html('<center style="margin: 20px; font-size: 14px">No Results</center>');
return false;
}
for (var sub in response)
{
var read = response[sub]['seen'] == '' || response[sub]['seen'] == null ? 'Unread' : 'Read';
var shade = response[sub]['seen'] == '' || response[sub]['seen'] == null ? 'row_shade' : '';
var id = response[sub]['id'];
var name = response[sub]['name'] ? response[sub]['name'] : 'deleted';
var row = '<tr id="sub_'+id+'" class="'+shade+'">';
var row = row + '<td>'+id+'</td>';
var row = row + '<td id="rd_'+id+'">'+read+'</td>';
var row = row + '<td id="rd_'+id+'">'+response[sub]['added']+'</td>';
var row = row + '<td>'+name+'</td>';
var row = row + '<td><a class="fc-btn show-message" id="upd_'+id+'" data-target="#view_modal" data-toggle="fcmodal">View</a><div class="sub-content" id="sub-content-'+id+'">'+response[sub]['content']+'</div></td>';
var row = row + '<td><i class="formcraft-trash sub_upd" id="del_'+id+'" title="Delete message"></i> <i class="formcraft-bookmark-empty sub_upd" id="read_'+id+'" title="Mark as unread"></i></td>';
var row = row + '</tr>';
var html = html + row;
}
jQuery('#subs tbody').html('');
jQuery('#subs tbody').append(html);
},
error: function (response) {
jQuery('#save_form_btn').html(jQuery('#save_form_btn').attr('data-error'));
window.saving = false;
}
});
}
function drawChart(id, from, to)
{
jQuery('#chart-cover').addClass('loading')
if (id)
{
var jsonData = jQuery.ajax({
url: ajaxurl,
dataType: "json",
type: "POST",
data: 'id='+id+'&action=formcraft_chart&from='+from+'&to='+to,
async: false
}).responseText;
}
else
{
var jsonData = jQuery.ajax({
url: ajaxurl,
dataType: "json",
data: 'action=formcraft_chart&from='+from+'&to='+to,
async: false
}).responseText;
}
var jsonData = jQuery.parseJSON( jsonData );
var totalViews = 0;
for (values in jsonData.views)
{
totalViews = totalViews + parseInt(jsonData.views[values][1]);
}
var totalSubmissions = 0;
for (values in jsonData.submissions)
{
totalSubmissions = totalSubmissions + parseInt(jsonData.submissions[values][1]);
}
jQuery({someValue: parseInt(jQuery('#tvs').text())}).animate({someValue: totalViews}, {
duration: 900,
easing:'swing',
step: function() {
jQuery('#tvs').text(Math.ceil(this.someValue));
}
});
jQuery({someValue: parseInt(jQuery('#tss').text())}).animate({someValue: totalSubmissions}, {
duration: 900,
easing:'swing',
step: function() {
jQuery('#tss').text(Math.ceil(this.someValue));
}
});
jQuery({someValue: parseInt(jQuery('#tcs').text())}).animate({someValue: (Math.round((totalSubmissions/totalViews)*10000)/100)}, {
duration: 900,
easing:'swing',
step: function() {
jQuery('#tcs').text(Math.ceil(this.someValue)+'%');
}
});
setTimeout(function(){
jQuery('#tvs').text(totalViews);
jQuery('#tss').text(totalSubmissions);
jQuery('#tcs').text((Math.round((totalSubmissions/totalViews)*10000)/100)+'%');
}, 1000);
var plot = jQuery.plot("#chart-inner", [{
data: jsonData.views,
label: 'views',
color: 'rgb(255, 175, 80)',
bars: {show:true, align: 'center'}
},{
data: jsonData.submissions,
label: 'submissions',
color: 'rgb(28, 160, 28)',
lines: {show:true}
}], {
series: {
points: { show:true }
},
grid: {
hoverable: true,
clickable: true
},
xaxis: {
mode: "categories"
}
});
jQuery('#chart-cover').removeClass('loading')
jQuery("#chart-inner").bind("plothover", function (event, pos, item) {
if (item) {
if (previousPoint != item.dataIndex) {
previousPoint = item.dataIndex;
jQuery("#tooltip").remove();
var x = Object.keys(item.series.xaxis.categories)[item.datapoint[0]],
y = item.datapoint[1];
showTooltip(item.pageX, item.pageY,
y + ' ' + item.series.label + " on " + x);
}
} else {
jQuery("#tooltip").remove();
previousPoint = null;
}
});
jQuery("#chart-inner").bind("plotclick", function (event, pos, item) {
if (item) {
jQuery("#clickdata").text(" - click point " + item.dataIndex + " in " + item.series.label);
plot.highlight(item.series, item.datapoint);
}
});
}
function setupLabel()
{
if (jQuery('.label_check input').length) {
jQuery('.label_check').each(function(){
jQuery(this).removeClass('c_on');
});
jQuery('.label_check input:checked').each(function(){
jQuery(this).parent('label').addClass('c_on');
});
};
if (jQuery('.label_radio input').length) {
jQuery('.label_radio').each(function(){
jQuery(this).removeClass('r_on');
});
jQuery('.label_radio input:checked').each(function(){
jQuery(this).parent('label').addClass('r_on');
});
};
};
jQuery(function () {
jQuery('#import').fileupload({
dataType: 'json',
add: function (e, data)
{
var type = data.files[0].name;
var type = type.split('.');
var type = type[1];
if (type!='txt')
{
alert('Only .txt files');
return false;
}
data.submit();
jQuery('#fu-label').text('wait');
jQuery('#import').prop("disabled",true);
},
done: function (e, resp) {
if(resp.result.failed)
{
jQuery('#import').prop("disabled",false);
jQuery('#fu-label').text(resp.failed);
}
else
{
jQuery('#import_form').val(resp.result.files.new_name);
jQuery('#import').prop("disabled",true);
jQuery('#fu-label').html('<i class="formcraft-ok" style="font-size: 10px"></i> Done');
jQuery('#rand_b').trigger('click');
setupLabel();
jQuery('#import').parent().addClass('green');
}
},
fail: function (e, data){
jQuery('.import').prop("disabled",false);
jQuery('#import_field_label').text('Failed');
jQuery('#fu-label').text('Rety');
}
});
});
jQuery(document).ready(function () {
setTimeout(function(){
jQuery('#fc-page-1').trigger('click');
}, 1000);
/* Update Submissions */
jQuery('body').on('click','.sub_upd, .show-message',function(){
var id = jQuery(this).attr('id').split('_');
var id2 = jQuery(this).attr('id');
jQuery('#view_modal .modal-body').html(jQuery('#sub-content-'+id[1]).html());
if (id[0]=='upd')
{
jQuery('#view_modal .modal-body').html(jQuery('#upd_text_'+id[1]).html());
jQuery('#view_modal .myModalLabel').html(jQuery('#upd_name_'+id[1]).html());
jQuery('#rd_'+id[1]).html('Read');
jQuery(this).parent().parent().addClass('row_shade');
jQuery.ajax({
url: ajaxurl,
type: "POST",
data: 'action=formcraft_sub_upd&type=upd&id='+id[1],
success: function (response) {
jQuery('#'+id2).parent().parent().removeClass('row_shade');
},
error: function (response) {
}
});
}
else if (id[0]=='del')
{
jQuery.ajax({
url: ajaxurl,
type: "POST",
data: 'action=formcraft_sub_upd&type=del&id='+id[1],
success: function (response) {
if (response=='D')
{
jQuery('#'+id2).removeClass('formcraft-trash');
jQuery('#'+id2).addClass('formcraft-ok').css('color','green');
}
},
error: function (response) {
}
});
}
else if (id[0]=='read')
{
jQuery.ajax({
url: ajaxurl,
type: "POST",
data: 'action=formcraft_sub_upd&type=read&id='+id[1],
success: function (response) {
if (response=='D')
{
jQuery('#rd_'+id[1]).html('Unread');
jQuery('#'+id2).parent().parent().addClass('row_shade');
}
},
error: function (response) {
}
});
}
});
// Set up DataTable
if (jQuery('#subs').length)
{
jQuery('#ext').dataTable({
"sPaginationType": "full_numbers"
});
jQuery('#files_manager_table').dataTable({
"sPaginationType": "full_numbers"
});
}
jQuery('#new_form').submit(function(event){
event.preventDefault();
var data = 'action=formcraft_add&import_form='+jQuery('#import_form').val()+'&name='+jQuery('#new_name').val()+'&desc='+jQuery('#new_desc').val()+'&type_form='+jQuery('[name="type_form"]:checked').val()+'&duplicate='+jQuery('[name="duplicate"]').val();
jQuery('.response_ajax').html('processing ...');
jQuery.ajax({
url: ajaxurl,
type: "POST",
dataType: 'json',
data: data,
success: function (response) {
if (response.Added)
{
jQuery('.response_ajax').html('Added');
window.location.href = 'admin.php?page=formcraft_admin&id='+response.Added;
}
else if (response.Error)
{
jQuery('.response_ajax').html(response.Error);
}
},
error: function (response) {
jQuery('.response_ajax').html(response);
}
});
});
jQuery('#subs_search').submit(function(event){
event.preventDefault();
show_submissions(false,jQuery('#search_query').val());
});
drawChart();
jQuery('.datepicker-field').datepicker().on('changeDate', function(ev){
jQuery(this).datepicker('hide');
jQuery(this).trigger('change');
});
jQuery('.datepicker-field').wrap("<div class='datepicker-cover'></div>");
jQuery('body').on('click', '.datepicker-cover', function(){
jQuery(this).find('input').focus();
});
jQuery('body').on('click','.nav-main li', function(event)
{
event.preventDefault();
var index = jQuery(this).parent().index();
jQuery('.tab-content .tab-pane').removeClass('active');
jQuery('.tab-content .tab-pane:eq('+index+')').addClass('active');
jQuery('.nav-main table td li').removeClass('active');
jQuery('.nav-main table td:eq('+index+') li').addClass('active');
});
jQuery("input.rand2").focus(function(){
event.stopPropagation();
});
jQuery('#rand_a').change(function(){
jQuery('#rand_aa').trigger('click');
setupLabel();
});
jQuery('body').on('submit','#fc-pk',function(event){
event.preventDefault();
jQuery('#fc-pk .response').text('...');
jQuery.ajax({
type: "GET",
url: ajaxurl,
data: 'key='+jQuery('#fc-pk-input').val()+'&action=formcraft_verifyLicense',
dataType: "json",
success: function(response)
{
if (response.message)
{
jQuery('#fc-pk .response').text(response.message);
}
else
{
jQuery('#fc-pk .response').text('Unknown error');
}
},
});
});
jQuery('body').on('click','.delete_from_manager',function(){
jQuery(this).html(jQuery(this).attr('data-loading'));
if (jQuery(this).attr('data-name')){var data = 'name='+encodeURIComponent(jQuery(this).attr('data-name'));}
else if (jQuery(this).attr('data-key')){var data = 'key='+encodeURIComponent(jQuery(this).attr('data-key'));}
var id_this = this.id;
jQuery.ajax({
url: ajaxurl,
type: "POST",
data: 'action=formcraft_delete_file&'+data,
success: function (response) {
if (response=='Deleted')
{
jQuery('#'+id_this).removeClass('btn-danger');
jQuery('#'+id_this).addClass('btn-success');
jQuery('#'+id_this).html(jQuery('#'+id_this).attr('data-complete'));
}
},
error: function (response) {
}
});
});
jQuery('#export').click(function(){
window.open(Url.exporturl,'_blank');
});
jQuery('body').on('click', '.delete-row', function() {
if (confirm('Are you sure you want to delete the form? You can\'t undo this action.')) {
if(jQuery(this).hasClass('btn-danger'))
{
var this_id = jQuery(this).attr('id');
jQuery(this).html(jQuery(this).attr('data-loading'));
var id = jQuery(this).parent('td').parent('tr').attr('id');
jQuery.ajax({
url: ajaxurl,
type: "POST",
data: 'action=formcraft_del&id='+id,
success: function (response) {
if (response=='Deleted')
{
jQuery('#'+this_id).html(jQuery('#'+this_id).attr('data-complete'));
jQuery('#'+this_id).removeClass('btn-danger');
jQuery('#'+this_id).addClass('btn-success');
}
else
{
jQuery('#'+this_id).html(jQuery('#'+this_id).attr('data-reset'));
}
},
error: function (response) {
alert("There was an error.");
}
});
}
}
});
jQuery('body').on('click', '.row_click', function() {
var id = jQuery(this).parent('tr').attr('id');
window.location.href = 'admin.php?page=formcraft_admin&id='+id;
});
// Edit Form Name and Description
jQuery("body").on('click', '.edit_btn', function(event){
event.stopPropagation();
jQuery(this).hide();
jQuery(this).parent().children('.rand').hide();
var name = jQuery(this).prev('a').html();
jQuery(this).prev('input.rand2').show();
jQuery(this).prev('input.rand2').focus();
jQuery(this).next('a.save_btn').show();
});
jQuery('body').on('click','.rand2',function(event){
event.stopPropagation();
});
jQuery("body").on('click', '.save_btn', function(event){
event.stopPropagation();
jQuery(this).hide();
var this_id = jQuery(this).attr('id');
var id = jQuery(this).attr('id').split('_');
var val = jQuery(this).parents().children('.rand2').val();
jQuery.ajax({
url: ajaxurl,
type: "POST",
data: 'action=formcraft_name_update&name='+val+'&id='+id[1],
success: function (response)
{
if (response=='D')
{
jQuery('#'+this_id).parent().children('.rand').text(val);
jQuery('#'+this_id).parent().children('input.rand2').hide();
jQuery('#'+this_id).parent().children('.rand').show();
jQuery('#'+this_id).parent().children('.edit_btn').show();
}
else
{
jQuery('#'+this_id).show();
jQuery('#'+this_id).parent().children('input.rand2').hide();
jQuery('#'+this_id).parent().children('.rand').show();
jQuery('#'+this_id).parent().children('.edit_btn').show();
}
},
error: function (response)
{
jQuery('#'+this_id).show();
}
});
});
jQuery('#stats_select, #chart-from, #chart-to').change(function(){
var id = jQuery('#stats_select').val();
var from = jQuery('#chart-from').val();
var to = jQuery('#chart-to').val();
drawChart(id, from, to);
});
jQuery('#chart-to').datepicker('remove');
jQuery('#chart-to').datepicker({'endDate': new Date()});
jQuery('#chart-from').change(function(){
var sd = jQuery(this).val().split('/');
sd = new Date( parseInt(sd[0]), parseInt(sd[1])-1, parseInt(sd[2]) );
jQuery('#chart-to').datepicker('remove');
jQuery('#chart-to').datepicker({'startDate': sd}).on('changeDate', function(ev){
jQuery(this).datepicker('hide');
jQuery(this).trigger('change');
});
});
jQuery('#export_select').change(function(){
var val = jQuery(this).val();
if (val=='0')
{
var href = jQuery('#export_url').attr('href');
var href = href.replace('?id='+href.substring(href.indexOf('?id=')+4, href.length),'?id=0');
}
else
{
var href = jQuery('#export_url').attr('href');
var href = href.replace('?id='+href.substring(href.indexOf('?id=')+4, href.length),'?id='+val);
}
jQuery('#export_url').attr('href',href);
});
setupLabel();
jQuery('body').addClass('has-js');
jQuery('body').on("click",'.label_check, .label_radio' , function(){
setupLabel();
});
jQuery('body').on('click', '.show-message', function(){
var html = jQuery(this).parent().find('.sub-content').html();
jQuery('#print_area').html(html);
});
jQuery('body').on('click','.fc_pagination > .page',function(){
show_submissions(jQuery(this).text(),false);
});
});
Here is a screenshot on both theme from inspect element and working/non working page
http://i.stack.imgur.com/6TkWs.png

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

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();
});
});
});

Handling json data using jQuery sent by using Newtonsoft.Json

I have tried searching all possible matches of my problem and also have tried a couple of solutions but unfortunately none worked
My backend code:
Person p;
foreach(DataRow dr in dt.Rows)
{
p = new Person();
p.id = Convert.ToInt16(dr["Id"]);
p.name = dr["Name"].ToString();
p.phone = Convert.ToInt64(dr["Phone"]);
pList.Add(p);
}
string ans = JsonConvert.SerializeObject(pList, Formatting.Indented);
jQuery.ajax
function ShowData() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/Data",
data: "{}",
dataType: "json",
success: function (data) {
alert(data.d);
var list = { "Person": +data };
for (i = 0; i < list.Person.length; i++) {
alert('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
console.log('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
}
console.log(list.Person.length);
},
error: function (result) {
alert("Error");
}
});
}
Alert output
[
{
"id": 1,
"name": "Bhavik",
"phone": 9601109585
},
{
"id": 2,
"name": "Xyz",
"phone": 1234567890
},
{
"id": 3,
"name": "Abc",
"phone": 9876543210
}
]
console.log(list.Person.length); returns undefined and hence does not enters the for loop.. So to work out with it.. and why is it necessary to specify contentType while dataType already exist.. Also can I use $.getJSON instead of $.ajax.
You should change your code to be var list = {"Person": data.d}; to reflect what you're alerting.
function ShowData() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/Data",
data: "{}",
dataType: "json",
success: function (data) {
alert(data.d);
var list = { "Person": +data.d };
for (i = 0; i < list.Person.length; i++) {
alert('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
console.log('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
}
console.log(list.Person.length);
},
error: function (result) {
alert("Error");
}
});
}
Also this should be a GET request not a post, then you would be able to use $.getJSON.

Ajax success function not waiting on internal script to complete before leaving scope

I have this chunk of code:
$.ajax({
type: "POST",
async: true,
url: "Notes/ViewAttachments.aspx/CompressFiles",
data: "{ 'hidBinaryFileIDs': '" + csList + "', 'userID' : '" + userID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.Zebra_Dialog(data.d, {
'type': 'information',
'title': 'Confirmation',
'buttons': [{
caption: 'Ok',
callback: function () {
}
}]
});
},
error: function (xhr, ajaxOptions, thrownError) {
$.Zebra_Dialog('Error : ' + xhr.status + ' - ' + xhr.statusText + ' : ' + thrownError, {
'type': 'error',
'title': 'Confirmation',
'buttons': [{
caption: 'Ok',
callback: function () {}
}]
});
}
});
When the ajax return success it displays the dialog box for a whole 2 seconds or so (not long enough for a user to read the message that it contains) then closes it. Using chrome's debugger, I've determined that it runs out of scope without waiting for a confirmation on the dialog box inside the success function. Does anyone know how I would go about halting the code until the user clicks ok?
Here is the full chunk of code for that ajax call..
var leZDB = null;
function zipSelectedAttachments() {
var ids = getSelectedTaskIDs();
if (ids.length > 0) {
leZDB = $.Zebra_Dialog('Do you want to zip the attachment(s)?', {
'type': 'question',
'title': 'Confirmation',
'buttons': ['Yes', 'No'],
'onClose':function (caption) {
if(caption = 'Yes') {
LinkAndPass(ids);
}
}
});
} else {
$.Zebra_Dialog('No attachments are selected.', {
'type': 'error',
'title': 'Error',
'buttons': [
{ caption: 'Ok', callback: function () { } }
]
});
}
}
function LinkAndPass(ids) {
leZDB.close();
if (true)
{
SendIDSForZipping(ids);
}
}
function SendIDSForZipping(ids) {
var csList = '';
var userID = $('#hiduserID').val();
for (var i = 0; i < ids.length; ++i) {
csList += ids[i] + ',';
}
var $this = $(this);
$this.die('click');
$.ajax({
type: "POST",
//async: true,
url: "Notes/ViewAttachments.aspx/CompressFiles",
data: "{ 'hidBinaryFileIDs': '" + csList + "', 'userID' : '" + userID+ "'}",
contentType: "application/json; charset=utf-8",
context:this,
dataType: "json",
success: function (data) {
var hasClickedOK = false;
var hasDisplayed = false;
if (!hasDisplayed) {
hasDisplayed = true;
$.Zebra_Dialog(data.d, {
'type': 'information',
'title': 'Confirmation',
'buttons': [
{
caption: 'Ok',
callback: function () {
hasClickedOK = true;
}
}
]
});
}
},
error: function (xhr, ajaxOptions, thrownError) {
$.Zebra_Dialog('Error : ' + xhr.status + ' - ' + xhr.statusText + ' : ' + thrownError, {
'type': 'error',
'title': 'Confirmation',
'buttons': [
{
caption: 'Ok',
callback: function () {
}
}
]
});
}
});
}
The getSelectedIDs() returns an array of numbers.
The Code behind returns a string.
try asyn:false in $.ajax({
type: "POST",
async: true
});
The problem consisted of the web method being called from the code behind. A faulty piece of logic caused it to refresh the page, instantly closing the box.

Categories