HTML
<body>
<section class="main-content">
</section>
</body>
JS
$(document).ready(function() {
var observer = new MutationObserver(function(mutations) {
console.log(mutations);
$.each(mutations, function(k, v) {
$.each(v.addedNodes, function(k2, v2) {
$('div.alert', v2[0]).each(function() {
$alert = $(this);
setTimeout(function() {
$alert.fadeOut(1000);
}, 2000);
});
});
})
});
observer.observe(document, {attributes: false, childList: true, characterData: false, subtree:true});
$('section.main-content').prepend(
createAlert({
type: 'success',
content: 'success'
})
).prepend(
createAlert({
type: 'warning',
content: 'warning'
})
);
});
function createAlert(alert) {
var alert_default = {
type: 'primary',
content: 'Content'
}
var alert = $.extend(alert_default, alert);
return (
'<div class="alert alert-' + alert.type + ' alert-dismissible fade show" role="alert">' +
'<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
'<span aria-hidden="true">×</span>' +
'</button>' +
alert.content +
'</div>'
);
}
The code shoudld fadeOut all inserted <div class"alert"> even if they are inserted at the same time. but it just doesn't work properly, only the last div.alert that fadeOut.
Here is the https://jsfiddle.net/u58xezqv/
thanks for helping!
Pass the jQuery object to setTimeout() for $alert to reference the same element, also inner nested $.each() is not necessary
var observer = new MutationObserver(function(mutations) {
console.log(mutations);
$.each(mutations, function(k, v) {
console.log(v);
$.each(v.addedNodes, function(k2, v2) {
var $alert = $(v2);
setTimeout(function(el) {
el.fadeOut(1000);
}, 2000, $alert);
});
})
});
jsfiddle https://jsfiddle.net/u58xezqv/3/
Related
I want to select all my data rows and automatically goes into another table,
but i didnt find a way to do it.
my current condition using Jquery to move it 1 by 1 using code below
$("#tblcandidate").on("change", ".chkCheckBoxId", function () {
if ($(".chkCheckBoxId").is(":checked")) {
$(".fail").hide();
var trItem = $(this).closest("tr");
trItem.find(".chkCheckBoxIdFail").closest("td").remove();
trItem.add("<tr>").append("</tr>");
$("#tblcandidateprocess").append(trItem);
}
});
and my target is making function that can append all my row into another table using button
EDIT:
My datatables come from ajax belox
function loadData(monthyear) {
return $.ajax({
url: "#Url.Action("ListCandidate", "Recruitment")?monthyear=" + monthyear,
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
beforeSend: function () {
swal.fire({
title: "Please wait a moment",
text: "Loading data...",
showConfirmButton: false,
allowOutsideClick: false,
willOpen: () => {
Swal.showLoading()
},
});
},
success: function (data) {
var getTemp = "#TempData["Allert"]";
if (getTemp === "Data successfully selected") {
Swal.fire({
text: getTemp,
icon: "success",
buttonsStyling: false,
confirmButtonText: "Ok, got it!",
customClass: {
confirmButton: "btn btn-primary"
}
});
}
else if (getTemp === "Something Went Wrong") {
Swal.fire({
text: getTemp,
icon: "error",
buttonsStyling: false,
confirmButtonText: "Ok, got it!",
customClass: {
confirmButton: "btn btn-primary"
}
});
}
else {
swal.close();
}
var html = '';
// delete existing row if any
table.clear().draw();
$.each(data, function (key, item) {
var TglLahir = item.TglLahir;
var cvTglLahir = moment(TglLahir).format('YYYY-MM-DD') ;
if (item.NamaS2 != null || item.NamaS2 != "") {
var namas2 = item.NamaS2;
}
else {
var namas2 = "A";
}
if (item.NamaS1 != null || item.NamaS1 != "") {
var namas1 = item.NamaS1;
}
else {
var namas1 = "A";
}
if (item.NamaD3 != null || item.NamaD3 != "") {
var namad3 = item.NamaD3;
}
else {
var namad3 = "A";
}
html += '<tr class="text-capitalize">';
html += '<td><span class="d-none">' + "'" + '</span> <div class="d-flex flex-column justify-content-start fw-bold">' + item.NomorKTP+'</div></td>';
html += '<td class="text-gray-800 text-hover-primary mb-1">' + item.NamaLengkap.toLowerCase() + '</td>';
html += '<td class="text-gray-800 text-hover-primary mb-1">' + item.PosisiYangDilamar.toLowerCase() + '</td>';
and etc
Then I want to move the shown row from this table A to my Table B
Here is an updated version of my Vanilla-JavaScript implementation that transfers individual <tr>s between the <tbody>s of the two tables:
document.querySelectorAll("button").forEach(b=>b.onclick=ev=>{
let tr=b.closest("tr");
document.querySelector((tr.closest("table").id=="source"?"#target":"#source")+" tbody").append(tr);
});
<div id="content">
<table id="source">
<thead>
<tr><th>A</th><th>B</th><th>C</th><th>D</th></tr>
</thead>
<tbody>
<tr><td>1 one</td><td>two</td><td>three</td><td>four</td><td><button>transfer</button></td></tr>
<tr><td>2 one</td><td>two</td><td>three</td><td>four</td><td><button>transfer</button></td></tr>
<tr><td>3 one</td><td>two</td><td>three</td><td>four</td><td><button>transfer</button></td></tr>
<tr><td>4 one</td><td>two</td><td>three</td><td>four</td><td><button>transfer</button></td></tr>
</tbody>
</table>
<hr>
<table id="target">
<thead>
<tr><th>A</th><th>B</th><th>C</th><th>D</th></tr>
</thead>
<tbody></tbody></table>
</div>
I want to do a search that can be triggered by given a specific URL (I tried with ajax and javascript here but im happy with a php variant also). I have 2 requirement phases (both should be displayed with pagination.js):
When I access eg.: https://<.myDomain.>/search/234x15 to put
the value inside the input and the filter automatically or make the
search over the whole database.
When I would go to eg.: https://<.myDomain.>/search I want to make POST search over the whole database.
My general problem is that I cannot include MySQL or other databases, I am limited to either JSON or objects/arrays (JS/php).
With my current solution processing 900 items using a big JSON file gets me a response after 5-8 seconds which is too long. And I will need to fill in with at least 3500 items.
Here is the solution I made:
<script>
var currentKeywords = $(location).attr('pathname');
var currentKeywordsFiltered = currentKeywords.replaceAll('+',' ');
const toBeSearched = currentKeywordsFiltered.split('/')[2];
$('#search-input').attr('value', toBeSearched);
var myArray = <?php echo json_encode($products_merged) ?>;
$(document).ready(function(){
console.log('Url keyword: ', toBeSearched);
var data = searchTable(toBeSearched, myArray);
buildTable(data);
(function(name) {
var container = $('#pagination-' + name);
container.pagination({
dataSource: data,
locator: 'dataSource',
totalNumber: 50,
pageSize: 20,
showPageNumbers: true,
showPrevious: true,
showNext: true,
showNavigator: true,
showFirstOnEllipsisShow: true,
showLastOnEllipsisShow: true,
ajax: {
beforeSend: function() {
container.prev().html('Loading...');
}
},
callback: function(response, pagination) {
window.console && console.log(22, response, pagination);
var dataHtml = '';
$.each(response, function (index, dataSource) {
dataHtml +=
'<div style="border: 1px solid #888888; border-radius: 5px; margin: 15px;" class="col-md-2">'
+ '<div class="card-body">'
+ '<b>'+ dataSource.title +'</b></h5>'
+ 'Vezi specificatii'
+ '</div>'
+ '</div>';
});
dataHtml += '';
container.prev().html(dataHtml);
}
})
})('demo');
});
$('#search-input').on('keyup', function(){
var value = $(this).val();
console.log('value: ', value);
var data = searchTable(value, myArray);
buildTable(data);
(function(name) {
var container = $('#pagination-' + name);
container.pagination({
dataSource: data,
locator: 'dataSource',
totalNumber: 50,
pageSize: 20,
showPageNumbers: true,
showPrevious: true,
showNext: true,
showNavigator: true,
showFirstOnEllipsisShow: true,
showLastOnEllipsisShow: true,
ajax: {
beforeSend: function() {
container.prev().html('Loading data from db...');
}
},
callback: function(response, pagination) {
window.console && console.log(22, response, pagination);
var dataHtml = '';
$.each(response, function (index, dataSource) {
dataHtml +=
'<div style="border: 1px solid #888888; border-radius: 5px; margin: 15px;" class="col-md-2">'
+ '<div class="card-body">'
+ '<b>'+ dataSource.title +'</b></h5>'
+ 'Vezi specificatii'
+ '</div>'
+ '</div>';
});
dataHtml += '';
container.prev().html(dataHtml);
}
})
})('demo');
});
$(function(){
if(toBeSearched === undefined){
buildTable(myArray);
(function(name) {
var container = $('#pagination-' + name);
container.pagination({
dataSource: myArray,
locator: 'dataSource',
totalNumber: 50,
pageSize: 20,
showPageNumbers: true,
showPrevious: true,
showNext: true,
showNavigator: true,
showFirstOnEllipsisShow: true,
showLastOnEllipsisShow: true,
ajax: {
beforeSend: function() {
container.prev().html('Loading...');
}
},
callback: function(response, pagination) {
window.console && console.log(22, response, pagination);
var dataHtml = '';
$.each(response, function (index, dataSource) {
dataHtml +=
'<div style="border: 1px solid #888888; border-radius: 5px; margin: 15px;" class="col-md-2">'
+ '<div class="card-body">'
+ '<b>'+ dataSource.title +'</b></h5>'
+ 'Vezi specificatii'
+ '</div>'
+ '</div>';
});
dataHtml += '';
container.prev().html(dataHtml);
}
})
})('demo');
}
});
function searchTable(value, data){
var filteredData = [];
for(var i = 0; i < data.length; i++){
value = value.toLowerCase();
var name = data[i].title.toLowerCase();
if(name.includes(value)){
filteredData.push(data[i])
}
}
return filteredData;
}
function buildTable(data){
var table = document.getElementById('myTable');
table.innerHTML = '';
for (var i = 0; i < data.length; i++){
var row = `<tr>
<td>${data[i].title}</td>
<td></td>
<td></td>
</tr>`;
table.innerHTML += row;
}
};
</script>
My question would be which architectural solutions i could go towards or how can I improve my code so it can be more efficient.
PS: I tried doing it first with php submission by grabbing the url and I was ending up in infinite loop using header on processing page.
I have used fancybox and appended a text div content to every images. The text div content appended is working well.But as I click to next button, the text div content is appended twice for each images.How to append that div content only once ?
$('.proBox').fancybox({
thumbs : {
autoStart : true,
axis : 'x'
},
idleTime : 0,
buttons : [
'info', 'close','thumbs'
],
afterShow: function( instance, current ) {
var url = window.location.href;
var cat = url.substring(url.lastIndexOf('#') + 1);
var cats = cat.split('-');
catId= cats[0];
var toolbar = "<div id='tools'>"+$('#addscetion div').eq(this.index).html()+ "</div>";
var index=catId+$("[data-fancybox-index]").html();
$('.fancybox-slide').children(".imagecontainer").remove();
// This is the div content that I am appending
$(".fancybox-slide").append(toolbar);
$(".fancybox-slide").append($('#'+index).html());
},
caption : function( instance, obj ) {
return '<div><p class="fancy-nav"><a data-fancybox-prev title="Previous" tabindex="1">‹</a> <a data-fancybox-next title="Next" tabindex="2">›</a> <span data-fancybox-index></span> of <span data-fancybox-count></span> images</p>' + $(this).find('.caption').html() + '</div>';
},
onInit: function(instance) {
instance.$refs.container.on('touchstart', '[data-fancybox-info]', function(e) {
e.stopPropagation();
e.preventDefault();
instance.$refs.container.toggleClass('fancybox-vertical-caption');
});
instance.$refs.container.on('mouseenter', '[data-fancybox-info]', function(e) {
instance.$refs.container.addClass('fancybox-vertical-caption');
instance.$refs.caption.one('mouseleave', function(e) {
instance.$refs.container.removeClass('fancybox-vertical-caption');
});
});
instance.$refs.container.on('click', '[data-fancybox-captionimg]', function(e) {
$(".fancybox-image").attr("src",this.src);
});
instance.$refs.container.on('click', '[data-fancybox-captionbtn]', function(e) {
$('.fancyRightCont').slideToggle('slow');
});
}
});
You can first remove appended html data from .fancybox-slide and then after append HTML like this
$(".fancybox-slide").html('');
$(".fancybox-slide").append(toolbar);
$(".fancybox-slide").append($('#' + index).html());
Try below code.
$('.proBox').fancybox({
thumbs: {
autoStart: true,
axis: 'x'
},
idleTime: 0,
buttons: [
'info', 'close', 'thumbs'
],
afterShow: function(instance, current) {
var url = window.location.href;
var cat = url.substring(url.lastIndexOf('#') + 1);
var cats = cat.split('-');
catId = cats[0];
var toolbar = "<div id='tools'>" + $('#addscetion div').eq(this.index).html() + "</div>";
var index = catId + $("[data-fancybox-index]").html();
$('.fancybox-slide').children(".imagecontainer").remove();
// This is the div content that I am appending
$(".fancybox-slide").html('');
$(".fancybox-slide").append(toolbar);
$(".fancybox-slide").append($('#' + index).html());
},
caption: function(instance, obj) {
return '<div><p class="fancy-nav"><a data-fancybox-prev title="Previous" tabindex="1">‹</a> <a data-fancybox-next title="Next" tabindex="2">›</a> <span data-fancybox-index></span> of <span data-fancybox-count></span> images</p>' + $(this).find('.caption').html() + '</div>';
},
onInit: function(instance) {
instance.$refs.container.on('touchstart', '[data-fancybox-info]', function(e) {
e.stopPropagation();
e.preventDefault();
instance.$refs.container.toggleClass('fancybox-vertical-caption');
});
instance.$refs.container.on('mouseenter', '[data-fancybox-info]', function(e) {
instance.$refs.container.addClass('fancybox-vertical-caption');
instance.$refs.caption.one('mouseleave', function(e) {
instance.$refs.container.removeClass('fancybox-vertical-caption');
});
});
instance.$refs.container.on('click', '[data-fancybox-captionimg]', function(e) {
$(".fancybox-image").attr("src", this.src);
});
instance.$refs.container.on('click', '[data-fancybox-captionbtn]', function(e) {
$('.fancyRightCont').slideToggle('slow');
});
}
});
I have a log in button that when a user clicks on it a terms and condition dialog pops up and overlaps the contents on a page as follows
TermsSuccess: function (result, context) {
var topTerms = findSetByInArray(result.Data, 'ParentId', 0);
var termsHTML = '<div id="terms"><ul class="termsList">';
for (var i = 0; i < topTerms.length; i++) {
var cls = (topTerms[i].isNew) ? 'newTerm' : 'Term';
termsHTML += '<li id=' + topTerms[i].ID + ' class=' + cls + '>'
termsHTML += topTerms[i].PageIndex + '. ' + topTerms[i].Detail;
termsHTML += getChildrenTerms(result.Data, topTerms[i].ID, topTerms[i].PageIndex + '. ');
termsHTML += '</li>';
}
termsHTML += '</ul></div>';
$(termsHTML).dialog({
modal: true,
resizable: false,
width: 400,
height: 600,
closeOnEscape: false,
open: function (event, ui) {
$(this).parent().children().children('.ui-dialog-titlebar-close').hide();
},
title: "Terms & Conditions",
buttons: [{
text: "Decline",
"class": 'btnDialog',
click: function () {
$(this).dialog("close");
}
},
{
text: "Accept",
"class": 'btnDialog',
click: function () {
betEvents.btnAccept_onClick();
$(this).dialog("close");
}
}]
});
}
I want this dialog to be appended to the following div on the page instead of it poping up over all the contents
<div id="mainarea"></div>
i tried to do something as the following but it doesnt work
function onClick(){
if $("#btnLogin").click(function(){
$('termsHTML').append('#mainarea');
});
}
your guidance will be appreciated.
Change this line:
$('termsHTML').append('#mainarea');
to
$(#mainarea).append(termsHTML);
and try again.
Explanation: $('termsHTML').append('#mainarea'); // here your selector is wrong
I have the form inside the Jquery-UI-Dialog.
I understand of how to validate all field in the form.
Using the plugin of this site
Example:
$(document).ready(function () {
$('#dialog').validate({
rules: {
category:
{
required: true
},
},
submitHandler: function (form) { // for demo
if ($('#ccategory').val() == 0){
document.getElementById('choose_own_text').innerHTML = "Please change here";
return false;}
// console.log($('#ccategory').val());
alert('valid form'); // for demo
return false; // for demo
}
});
});
But I have the id and name that I created via Javascript.
For example id="inputp"+j+"_id" where j is a number.
Now I want to validate this field but i have the error:
SyntaxError: missing : after property id
I use this method because I declare with the number the data.
How to correct this error for that I can use always this technique's validate.
$( "#wnd_Add" ).dialog({
autoOpen: false,
height: 'auto',
width: 350,
modal: true,
resizable:false,
buttons: {
"Add": function() {
var j=(parseInt(contapara)+1);
$('#formparam').validate({
rules: {
"inputp"+j+"_id":
{
required: true
},
},
submitHandler: {
contapara=(parseInt(contapara)+1);
document.getElementById("sorpara").innerHTML+="<li id=\"inputp"+contapara+"_id\" class=\"ui-state-default\"><span class=\"ui-icon ui-icon-arrowthick-2-n-s\"></span>"+$('#inputp'+contapara+'_id').val()+"</li>";
var $fm = $("#formparam");
$.get($fm.attr('${nextstep}'))
.done(function(data, ok){
var fr=$fm.serialize();
fr=fr.replace(/\&/g,"+%23+");
fr=replacew(fr,/\=/g, "%24+"); // //fr=fr.replace(/\=/g,"%24+");
if(document.getElementById("inputp"+contapara+"_visible").checked==false)
fr=fr+"+%23+inputp"+contapara+"_visible%24+off";
// data is the content of the response
document.location.href="index2?"+fr;})
.fail(function(data){
alert('call failed');
// call failed for some reason -- add error messaging?
});
// $( this ).dialog( "close" );
return false; },
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
$( this ).dialog( "close" );
}
});
I created a demo on Jsfiddle but not function because I have this error but may help
I hope the title of the question is correct...
UPDATE:
Now I have this script but I have the error SyntaxError: missing : after property id on
function(form) {
This is last script:
$( "#wnd_Addparam" ).dialog({
autoOpen: false,
height: 'auto',
width: 350,
modal: true,
resizable:false,
buttons: {
"Add": function() {
var j=(parseInt(contapara)+1);
var rules= {};
rules["inputp" + j + "_id"]=
{
required: true
};
$('#formparam').validate({
rules: rules,
submitHandler: {
function(form) {
contapara=(parseInt(contapara)+1);
document.getElementById("sorpara").innerHTML+="<li id=\"inputp"+contapara+"_id\" class=\"ui-state-default\"><span class=\"ui-icon ui-icon-arrowthick-2-n-s\"></span>"+$('#inputp'+contapara+'_id').val()+"</li>";
var $fm = $("#formparam");
$.get($fm.attr('${nextstep}'))
.done(function(data, ok){
var fr=$fm.serialize();
fr=fr.replace(/\&/g,"+%23+");
fr=replacew(fr,/\=/g, "%24+"); // //fr=fr.replace(/\=/g,"%24+");
if(document.getElementById("inputp"+contapara+"_visible").checked==false)
fr=fr+"+%23+inputp"+contapara+"_visible%24+off";
// data is the content of the response
document.location.href="index2?"+fr;})
.fail(function(data){
alert('call failed');
// call failed for some reason -- add error messaging?
});
return false; } },
});
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
$( this ).dialog( "close" );
}
});
You can't use a variable as a key in a object like that, instead you can do something like
var rules = {};
rules["inputp"+j+"_id"] = {
required: true
};
$('#formparam').validate({
rules: rules,
submitHandler: {
Ex;
var contapara = 3;
var regex, v, l, c, b;
$("#wnd_Addparam").dialog({
autoOpen : false,
height : 'auto',
width : 350,
modal : true,
resizable : false,
buttons : {
"Add" : function() {
var j = (parseInt(contapara) + 1);
var rules = {};
rules["inputp" + j + "_id"] = {
required : true
};
$('#formparam').validate({
rules : rules,
submitHandler : function(form) {
contapara = (parseInt(contapara) + 1);
document.getElementById("sorpara").innerHTML += "<li id=\"inputp"
+ contapara
+ "_id\" class=\"ui-state-default\"><span class=\"ui-icon ui-icon-arrowthick-2-n-s\"></span>"
+ $('#inputp' + contapara + '_id').val() + "</li>";
var $fm = $("#formparam");
$.get($fm.attr('${nextstep}')).done(function(data, ok) {
var fr = $fm.serialize();
fr = fr.replace(/\&/g, "+%23+");
fr = replacew(fr, /\=/g, "%24+"); // //fr=fr.replace(/\=/g,"%24+");
if (document.getElementById("inputp" + contapara
+ "_visible").checked == false)
fr = fr + "+%23+inputp" + contapara
+ "_visible%24+off";
// data is the content of the response
document.location.href = "index2?" + fr;
}).fail(function(data) {
alert('call failed');
// call failed for some reason -- add error
// messaging?
});
return false;
}
})
},
Cancel : function() {
$(this).dialog("close");
}
},
close : function() {
$(this).dialog("close");
}
});
$("#btn_Addpar").click(function() {
i = (parseInt(contapara) + 1);
$("#formparam").remove();
$("#wnd_Addparam")
.append('<form method="GET" name="formparam" id="formparam" action="${nextstep}">\
<input type="hidden" name="json_data" value="${json_data}">\
<input type="hidden" name="tag" value="${tag}">\
<table><tr><td><label>ID</label></td><td>\
<textarea class="expand" name="inputp'
+ i
+ '_id" id="inputp'
+ i
+ '_id"></textarea></td></tr>\
<tr><td><label>Type</label></td><td><select name="inputp'
+ i
+ '_type" id="inputp'
+ i
+ '_type">\
<option value="text">Text</option><option value="integer">Integer</option><option value="float">Float</option>\
<option value="list_values">List of values</option><option value="range">Range</option>\
<option value="selection_collapsed">Selection (collapsed)</option>\
<option value="selection_expanded">Selection (expanded)</option>\
<option value="subimage">Subimage selection</option>\
<option value="polygon">Polygon selection</option>\
<option value="horizontal_separator">Horizontal separator</option>\
</select></td></tr><tr><td><label> Description</label></td>\
<td><textarea class="expand" name="inputp'
+ i
+ '_description" id="inputp'
+ i
+ '_description"></textarea></td></tr>\
<tr><td><label>Value</label></td><td><textarea class="expand" name="inputp'
+ i
+ '_value" id="inputp'
+ i
+ '_value"></textarea></td></tr>\
<tr><td><label>Info (help)</label></td><td><textarea class="expand" id="inputp'
+ i
+ '_info" name="inputp'
+ i
+ '_info"></textarea></td></tr>\
<tr><td><label> Visible?</label></td><td><input type="checkbox" id="inputp'
+ i
+ '_visible" name="inputp'
+ i
+ '_visible" checked></td></tr></table></form>');
$("#wnd_Addparam").dialog("open");
});