I have a textbox with id txtAutocompletePortal.
How can I open autocomplete menu on focus of textbox?
Here is my code :
Mod.SmartSearch = function (smartSearchOptions) {
if (typeof (smartSearchOptions) == "undefined" || smartSearchOptions == null) { smartSearchOptions = {}; };
var sS = {
smartSearchOptions: $.extend({
'autoFocus': false,
'source': function (reuqest, resonse) {
},
'minLength': 0,
'delay': 100,
'select': function (event, ui) {
},
'messages': {
noResults: '',
results: function () { }
},
}, smartSearchOptions),
_form: '',
_searchFieldId: '',
_context: '',
_reset: {},
_validate: {},
_init: function () {
$(this.searchFieldId, this.context).autocomplete(this.smartSearchOptions);
$(this.searchFieldId, this.context).autocomplete("option", "appendTo", this._searchFieldId)
}
};
return {
form: sS._form,
searchFieldId: sS._searchFieldId,
context: sS._context,
init: sS._init,
reset: sS._reset,
validator: sS._validate,
smartSearchOptions: sS.smartSearchOptions
};
};
var source = function (request, response) {
if (request.term.search(/[a-z A-Z 0-9]\s/) > 0) {
return;
}
else {
$.ajax({
url: url + "/" + agentId + "/" +
Mod.ExtractLast(request.term),
dataType: "json",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.label,
value: item.value
}
}));
}
});
}
};
var select = function (event, ui) {
event.preventDefault();
if (ui.item) {
App.ContactInfo.portalId = ui.item.value;
App.ContactInfo.portalName = ui.item.label;
selctedPortalId = ui.item.value;
selctedPortalName = ui.item.label;
this.value = ui.item.label;
}
};
var ss = Mod.SmartSearch({ source: source, select: select });
ss.searchFieldId = '#txtAutocompletePortal';
ss.context = '#PortalBodySrch';
ss.init();
To make jQuery Autocomplete pop up when the user click the box, use this:
var field = $( /*whatever selector */ );
field.autocomplete({
minLength: 0,
/* extra settings, as needed */
}).focus(function(){
$(this).data("uiAutocomplete").search($(this).val());
});
Related
I am trying to call a vue method from javascript function but can't make it work. The method I am trying to call is app.onChangePlant(val) It turns out that the value is not called.
Is it because of the vue is not yet available when I declared the javascript function?
This is the error I am receiving
plant-consumer:222 Uncaught TypeError: app.onChangePlant is not a function
at onChangePlantSelect (plant-consumer:222)
at HTMLSelectElement.onchange (plant-consumer:399)
at Object.trigger (app.js:14973)
at HTMLSelectElement.<anonymous> (app.js:15045)
at Function.each (app.js:6863)
at jQuery.fn.init.ea
Code:
<script type="module" defer>
const setting = {
url: {
findUsage: "{{ route('admin.plant-consumer.find-usage') }}",
usageCsvDownload: "{{ route('admin.plant-consumer.usage-csv-download') }}",
},
date: {
date_default: moment("{{ $defaultDate }}", 'YYYY/MM/DD').toDate()
}
};
const app = new Vue({
el: '#app',
data: {
url: setting.url,
plantId: '',
isLoading: false,
rangeFilter: 'daily',
byMonth: false,
csvDownloadUrl: '',
date: setting.date.date_default,
month: setting.date.date_default,
// datepicker用設定
DatePickerFormat: 'yyyy/MM/dd',
MonthPickerFormat: 'yyyy/MM',
disabledDates: {
from: new Date()
},
ja_vdp: vdp_translation_ja.js
},
components: {
'vuejs-datepicker': vuejsDatepicker
},
watch: {
rangeFilter: function () {
this.byMonth = this.rangeFilter === 'monthly';
this.getData(1);
},
},
methods: {
onChangePlant: function(event) {
this.plantId = event.target.value;
this.getData(1);
},
onChangeDate: function () {
this.getData(1);
},
onChangeMonth: function () {
this.getData(1);
},
getData: function(page) {
let that = this;
let date = that.date;
that.isLoading = true;
that.csvDownloadUrl = '';
if (that.byMonth) {
date = that.month;
}
if(that.plantId && ((date)))
{
let data = {
plant : that.plantId,
date : that.formatDateForRequest(date),
byMonth: that.byMonth,
page : page,
};
let url = that.url.usageCsvDownload
+ '?plant=' + data.plant
+ '&date=' + data.date
+ '&byMonth=' + data.byMonth;
// console.log(url);
$.ajax(
{
url: that.url.findUsage,
type: "get",
datatype: "html",
data: data,
cache: false
}).done(function(data){
$("#consumer_table_generate").empty().html(data);
that.csvDownloadUrl = url;
}).fail(function(jqXHR, ajaxOptions, thrownError){
alert('No response from server');
}).always(function() {
that.isLoading = false;
});
}
else
{
$("#consumer_ratio_body").empty();
that.isLoading = false;
}
}
},
mounted: function () {
let vueObj = this;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).on('click', '.pagination a', function(event)
{
event.preventDefault();
let $this = $(this);
$('#consumer_table_generate li').removeClass('active');
$this.parent('li').addClass('active');
var page = $this.attr('href').split('page=')[1];
vueObj.getData(page);
});
}
});
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
</script>
<script>
function onChangePlantSelect(val) {
console.log(val);
app.onChangePlant(val);
};
</script>
const App = {
data: {
url: setting.url,
plantId: '',
isLoading: false,
rangeFilter: 'daily',
byMonth: false,
csvDownloadUrl: '',
date: setting.date.date_default,
month: setting.date.date_default,
// datepicker用設定
DatePickerFormat: 'yyyy/MM/dd',
MonthPickerFormat: 'yyyy/MM',
disabledDates: {
from: new Date()
},
ja_vdp: vdp_translation_ja.js
},
components: {
'vuejs-datepicker': vuejsDatepicker
},
watch: {
rangeFilter: function () {
this.byMonth = this.rangeFilter === 'monthly';
this.getData(1);
},
},
methods: {
onChangePlant: function(event) {
this.plantId = event.target.value;
this.getData(1);
},
onChangeDate: function () {
this.getData(1);
},
onChangeMonth: function () {
this.getData(1);
},
getData: function(page) {
let that = this;
let date = that.date;
that.isLoading = true;
that.csvDownloadUrl = '';
if (that.byMonth) {
date = that.month;
}
if(that.plantId && ((date)))
{
let data = {
plant : that.plantId,
date : that.formatDateForRequest(date),
byMonth: that.byMonth,
page : page,
};
let url = that.url.usageCsvDownload
+ '?plant=' + data.plant
+ '&date=' + data.date
+ '&byMonth=' + data.byMonth;
// console.log(url);
$.ajax(
{
url: that.url.findUsage,
type: "get",
datatype: "html",
data: data,
cache: false
}).done(function(data){
$("#consumer_table_generate").empty().html(data);
that.csvDownloadUrl = url;
}).fail(function(jqXHR, ajaxOptions, thrownError){
alert('No response from server');
}).always(function() {
that.isLoading = false;
});
}
else
{
$("#consumer_ratio_body").empty();
that.isLoading = false;
}
}
},
mounted: function () {
let vueObj = this;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).on('click', '.pagination a', function(event)
{
event.preventDefault();
let $this = $(this);
$('#consumer_table_generate li').removeClass('active');
$this.parent('li').addClass('active');
var page = $this.attr('href').split('page=')[1];
vueObj.getData(page);
});
}
}
const app = Vue.createApp(App)
const vm = app.mount('#blog-posts-demo')
vm.remove(123456)
//this way you guarantee the app is properly mounted, by the time you call
I don't know why would you like to do that but if it's neccessary you can try to use window eventlisteners:
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
In your component you can add an eventlistener that call your method, in js script tage you can fire an event, if your component ready it will call the method.
I never did this before it's just a theory :)
edit: I tried it, but your component is not mounted when you want to fire the event in script tag
I am trying to use "query" object to perform what i want. Everythings works except when i select an option nothing happen (placeholder is not replaced).
I have followed the instructing from this post Loading remote data only once with Select2
init() {
this.$view.select2({
theme: "bootstrap",
language: "fr",
allowClear: this.options.allowClear,
placeholder: this.options.placeholder,
query: (query) => {
if (this.items) {
query.callback({results: this.filterItems(query.term)});
} else {
this.loadData(query);
}
},
templateResult: (state) => {
return this.format(state);
}
});
}
loadData(query) {
$.ajax({
url: this.options.url,
dataType: 'json',
type: 'GET',
success: (data) => {
this.items = [];
for (let row of data) {
this.items.push({
id: row.id,
entity_id: row.entity_id,
text: row.label,
type: row.type,
disabled: !row.enable
});
}
query.callback({results: this.items});
}
});
}
filterItems(term) {
if (typeof term == "undefined" || term === null) {
return this.items;
}
const _term = $.trim(term.toLowerCase());
if (_term === '') {
return this.items;
}
return this.items.filter((item) => {
return item.text.toLowerCase().includes(term);
});
}
Thanx for help,
I think i have found a solution :
var s2data = $view.select2({
ajax: {
url: 'https://api.github.com/search/repositories',
data: {
q: 'select2'
},
dataType: 'json',
processResults: function(data) {
var items = [];
for (var row of data.items) {
items.push({
id: row.id,
text: row.name
});
}
this.options.set('cacheDataSource', {items: items});
return {
results: items
};
}
},
cacheDataSource: [],
allowClear: true,
placeholder: 'Select Values ...',
width: '100%',
}).data('select2');
s2data.dataAdapter.query = function(params, callback) {
var cacheDataSource = this.options.get('cacheDataSource');
if (cacheDataSource && cacheDataSource.items) {
var term = params.term;
if (typeof term == "undefined" || term == null) {
callback({results: cacheDataSource.items});
return
}
term = $.trim(term.toLowerCase());
if (term == "") {
callback({results: cacheDataSource.items});
return
}
callback({ results: cacheDataSource.items.filter(function(item) {
return item.text.toLowerCase().includes(term);
})
});
} else {
// call the original logic
var ajaxAdapterFunc = jQuery.fn.select2.amd.require('select2/data/ajax');
var ajaxAdapter = new ajaxAdapterFunc(this.$element, this.options);
ajaxAdapter.query(params, callback);
}
}
jsfiddle : https://jsfiddle.net/3kpu4htm/35/
sorry for my bad english. I just wanna ask about select2 ajax, i have problem with this, i don't know how to get other response from my API.
So this is the response from my API.
enter image description here
so i want to get zip_code value when select2 has on changed. but i don't know to get it.
this my code..
$(".myselect").select2(
{
theme: "bootstrap4",
placeholder: "Provinsi, Kota/Kab, Kecamatan, Kelurahan",
minimumInputLength: 3,
ajax: {
url: url, //changing by env
dataType: 'json',
type: "GET",
delay: 150,
data: function (params) {
return {
filter: params.term
};
},
processResults: function (data, params) {
var res = data.data.locations.map(function (item) {
return {
id: item.id,
text: item.name,
zip: item.zip_code
};
});
return {
results: res
};
},
templateResult: function(result) {
return result.text;
},
templateSelection: function(selection) {
return selection.text;
}
},
}).on('change.select2', function(e){
console.log($(this).val(e.text));
villText = $("#village option:last-child").text();
var villVal = $("#village option:last-child").val();
// console.log($("#village option:last-child").val())
// var villVal1 = $("#village option:last-child").val();
villKel = villText;
villKel = villKel.split(',')[2];
$("#village_kel").val(villKel);
var villx = $('#village_land');
var vill_land = $("#village_land option:last-child").text();
vill_land_kel = vill_land;
vill_land_kel = vill_land_kel.split(',')[2];
$("#villageland_kel").val(vill_land_kel);
$('input[name="domisili"]').click(function() {
if ($(this).attr("value") == "1") {
if(villx.empty()) {
villx.append($('<option></option>').attr('value', villVal).text(villText));
villx.prop('selectedIndex', 0);
}
else {
villx.append($('<option></option>').attr('value', "").text(""));
}
}
})
});
picture below is the result when i get the text of value from my API.
enter image description here
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
I write this jQuery after it works fine completely for first time it give this error then for second time none of function work.I also use jQuery UI you can see in code.
This error happens after first time complete:
Uncaught SyntaxError: Unexpected token } jquery-1.8.3.js:564
Markup and code:
<link href="../../StyleSheets/jquery-ui-1.9.2.custom.css" rel="stylesheet">
<script src="../../Scripts/jquery-1.8.3.js"></script>
<script src="../../Scripts/jquery-ui-1.9.2.custom.js"></script>
<script>
$(function () {
$(":checkbox").change(function () {
var $this = $(this);
if ($this.is(":checked")) {
$this.closest("tr").addClass("SlectedtRow");
} else {
$this.closest("tr").removeClass("SlectedtRow");
}
})
var tittle = '';
var url = '';
$("#dialog").dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
buttons: [
{
text: "بلی",
click: function () {
DoAction();
$(this).dialog("close");
}
},
{
text: "خیر",
click: function () {
$(this).dialog("close");
}
}
]
});
// Link to open the dialog
$('#ConfirmRiver , #DeleteRiver').click(function (event) {
var IsSelected = false;
var ModalText = " آیا رودخانه ";
$('#RiverForm input:checked').each(function () {
ModalText += this.value + " - "
IsSelected = true;
});
if (IsSelected) {
document.getElementById('ErrorContent').style.display = "none";
ModalText = ModalText.slice(0, -2);
if (this.id == 'DeleteRiver') {
ModalText += "حذف گردد" + "؟"
tittle = 'حذف رودخانه'
url = '#Url.Action("DeleteRiver", "WaterResourcesManagement")';
}
if (this.id == 'ConfirmRiver') {
ModalText += "تایید نهایی گردد" + "؟"
tittle = 'تایید اصلاح و بازبینی رودخانه '
url = '#Url.Action("ChangeRiverARStatus", "WaterResourcesManagement")';
}
$('#ModalMessgae').text(ModalText);
$("#dialog").dialog("open");
$("#dialog").dialog({ title: tittle });
event.preventDefault();
}
else {
document.getElementById('ErrorContent').innerHTML = " اطلاعات مورد نظر را انتخاب نمایید";
document.getElementById('ErrorContent').style.display = "block";
document.getElementById('ErrorContent').className = "msg-Yellow";
}
})
function DoAction() {
var list = [];
$('#RiverForm input:checked').each(function () {
if( url == '#Url.Action("ChangeRiverARStatus", "WaterResourcesManagement")')
{
var Ar= $('#RiverForm').find("input[value='"+this.id+"']").attr('id');
list.push(Ar);
}
else{
list.push(this.id);}
});
var parameters = {};
parameters = JSON.stringify({ "Id": list, AreaID: #Request.QueryString["AreaID"] });
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: "html",
traditional: true,
data: parameters,
success: function (data, textStatus, jqXHR) {
$('#updateAjax').html(data);
},
error: function (data) {
$('#updateAjax').html(data);
}
});
}
});
</script>
I add if (!request.isjax()) in all jquery code and it works