required on selectpicker based on div - validation

I am learner in javaScript
How to write required on selectpicker based on
var typeSelectBox = "<select id='depprojsDevice' class='selectpicker'>";
typeSelectBox += "<option value=''> -- SELECT --</option>";
if (arr) {
for (var i in arr) {
typeSelectBox += "<option value='" + arr[i][2] + "'>" + arr[i][0] + " " + arr[i][1] + "</option>";
}
}
typeSelectBox + "</select>";
$('#depprojsDevice_Div').html(typeSelectBox);
$("div#depprojsDevice_Div select[id = 'depprojsDevice']").attr('required','required');

$(function(){
$("#depprojsDevice").prop('required',true);
});
Try This Code

Related

Ajax function is never called inside dynamically generated buttons

This loop generate buttons in my HTML inside an AJAX function.
for( var i = 0; i<len; i++){
var d = new Date(response[i]['date']);
dformat = [d.getDate() + '/' +
(d.getMonth()+1) + '/' +
d.getFullYear() + ' ' +
d.getHours() + ':' +
d.getMinutes()];
console.log(response[i])
var bons = "<tbody>" +
"<th>" + response[i]['id'] + "</th>" +
"<td>" + dformat + "</td>" +
"<td>" + response[i]['poids'] + "</td>" +
"<td>" + response[i]['origine'] + "</td>" +
"<td>" + response[i]['type'] + "</td>" +
"<td>" + response[i]['famille'] + "</td>"
if(response[i]['localisation'] != "Expédié"){
bons = bons + "<td> <input class='evacuate' id='" + response[i]['id'] + "' type='button'" + "value='Evacuer'> </td>"
}else{
bons = bons + "<td>" + response[i]['localisation'] + "</td>"
}
bons = bons + "</tr>" +
"</tbody>"
$("#index").append(
bons
);
}
Then I have another AJAX function which makes every buttons previously generated clickable like :
$(".evacuate").on('click', function(){
console.log("test des boutons")
});
Problem is, the console.log isn't displayed, as if the function is never called. What am I doing wrong here ?
Try this:
$(document).on('click','.evacuate', function(){
console.log("test des boutons")
});
You should define the click event on elements that already exist on the page. So for your situation, select the parent element and then add click event. For example if the element with evacuate class is inside an element with someclass class, this will work:
$(".someclass").on('click', '.evacuate', function(){
console.log("test des boutons")
});
According to your code, you can use tbody tag as parent:
$("tbody").on('click', '.evacuate', function(){
console.log("test des boutons")
});
I don't really understand how this works but thanks to the answers given above I managed to display my console.log.
$(document.getElementsByName).on('click', '.evacuate', function(){
console.log("Test des boutons")
});

How to load data on scroll in select2 dropdown without using pagination?

I have more than 1000 rows and it is taking much time in taking AJAX response and loading data in dropdwon.
I am using below code .
function fillperson() {
$.ajax({
// delay: 250 ,
url: Url,
type: "GET",
minimumInputLength:0,
data: { isGetAll: false, Id1: 0, ID2:0},
complete: function (data) {
var ele = document.getElementById('ddlperson');
ele.innerHTML = '';
var persondata = JSON.parse(data.responseText);
ele.innerHTML = '<option value="' + -1 + '">Select Person</option>';
ele.innerHTML += '<option value="' + 0 + '">ALL Person</option>';
var totaldata = persondata.length;
var i = 0;
for ( i ; i < data.length; i++) {
ele.innerHTML = ele.innerHTML +
'<option value="' + data[i]['Id'] + '">' +data[i]['name'] + '(' + data[i]['code'] + ')' + '</option>';
}
$('#ddperson').select2();
},
});
}

For every new ajax call it takes a little more time than the previous call

I am trying to change some data with an ajax call, but the problem is that every new call takes a little more time than the previous one.
So after 10-15 calls, the time from when the ajax request starts and when ajax returns data is like 20 seconds per request.
I also tried to debug, and it seems that the problem is that when I trigger an ajax call, it takes all that time till the controller detects the call, and after controller detects it, it gets executed and returns data immediately.
P.S. When i comment out these 2 intervals, it works perfectly. So i guess these intervals are blocking this request form happening immediately.
Also can it be a problem with Google Chrome? Because i guess in Microsoft Edge works perfectly (as far i made a test 2 times).
html:
<div class="table-responsive">
<table class="table table-condensed table-hover usersTable">
<thead>
<tr>
<th style="width: 20%">Benutzer</th>
<th></th>
<th></th>
#foreach (var item in Model.Skills)
{
<th title="#item.Name">#item.ShortName</th>
}
<th class="text-center">Extension</th>
<th class="text-center">Total Calls</th>
<th class="text-center">Calls per hour</th>
<th class="text-center">Average Call Duration</th>
</tr>
</thead>
<tbody class="usersTableBody"></tbody>
</table>
<div class="col-md-12 text-center noSignedInUser" style="display: none;">
<h4 style="color: lightgrey">There is no signed in user</h4>
</div>
js:
$(function () {
$('.usersTableBody').on('click', '.hasSkill', function () {
var userId = $(this).parent().data('id');
var skillId = $(this).data('id');
if ($(this).hasClass('skillIsActive')) {
addRemoveSkill(userId, skillId, false, $(this))
}
else {
addRemoveSkill(userId, skillId, true, $(this))
}
});
//add or remove a skill to a user with ajax
function addRemoveSkill(userId, skillId, add, element) {
$.ajax({
url: '#Url.Action("AddRemoveSkill","Home")',
data: { userId: userId, skillId: skillId, add: add },
success: function (data) {
if(data == true) {
if (add == false)
{
$(element).addClass('skillIsInactive')
$(element).removeClass('skillIsActive')
}
else {
$(element).addClass('skillIsActive')
$(element).removeClass('skillIsInactive')
}
$(element).addClass('recentlyUpdated');
hasAllSkillsDisabled($(element));
}
}
});
}
function hasAllSkillsDisabled(element) {
parent = $(element).parent();
var hasAllDisabled = true;
$.each(parent.children('td'), function (i, item) {
if ($(item).hasClass('skillIsActive'))
{
hasAllDisabled = false;
}
});
if (hasAllDisabled == true)
{
$(parent).addClass('hasAllSkillsDisabled');
}
else {
$(parent).removeClass('hasAllSkillsDisabled');
}
}
})
two other functions that gets data every 1000ms
getUserDatas();
getSkillHeader();
var detectClass = 0;
function getUserDatas() {
var type = $('#Type').val();
var skill = $('#Skill').val();
$.ajax({
url: '#Url.Action("GetUsersDataWithAjax", "Home")',
data: { type: type, skill: skill },
success: function (data) {
if (data.length == 0) {
$('.noSignedInUser').show();
}
else {
$('.noSignedInUser').hide();
}
if (data != false) {
$.each(data, function (i, item) {
var tr = $('tr[data-id="' + item.Id + '"].agentTr');
//if that row already exists or its new
if (!tr.length)
{
//if new create html and append to table body
var dontHaveSkills = "dontHaveSkills";
if (item.hasSkills) {
dontHaveSkills = "";
}
var hasAllSkillsDisabled = "";
if (item.hasSkills && item.HasAllSkillsDisabled) {
hasAllSkillsDisabled = "hasAllSkillsDisabled";
}
var html = '';
html += '<tr data-id="' + item.Id + '" class="agentTr ' + dontHaveSkills + ' ' + hasAllSkillsDisabled + ' time' + detectClass + '">';
html += '<td>' + item.Name + '</td>';
html += '<td class="stateName"><div class="text-right ' + item.State.NameClass + '">' + item.State.Name + '</div></td>';
html += '<td class="stateCircle"><div class="statusCircle ' + item.State.CircleClass + '"</div></td>';
$.each(item.Skills, function (j, skill) {
var klasa = "";
if (skill.IsActive == true) {
klasa = "hasSkill skillIsActive";
}
else if (skill.IsActive == false) {
klasa = "hasSkill skillIsInactive";
}
else {
klasa = "unableSkill";
}
html += '<td data-id="' + skill.Id + '" class="' + klasa + '" title="' + skill.Name + '">' + skill.ShortName + '</td>';
if (j == 25) {
return false;
}
});
html += '<td class="text-center extension">' + item.Extension + '</td>';
html += '<td class="text-center totalCalls">' + item.AvgCalls.TotalCalls + '</td>';
html += '<td class="text-center callsPerHour">' + item.AvgCalls.CallsPerHour + '</td>';
html += '<td class="text-center avgCallDuration">' + item.AvgCalls.AvgCallDuration + '</td>';
html += '</tr>';
$('.usersTableBody').append(html);
}
else {
//else if its existing update datas
tr.removeClass('dontHaveSkills hasAllSkillsDisabled');
var detect = 'time' + (detectClass - 1);
tr.removeClass(detect);
if (!item.hasSkills) {
tr.addClass('dontHaveSkills');
}
if (item.hasSkills && item.HasAllSkillsDisabled) {
tr.addClass('hasAllSkillsDisabled');
}
var stateName = tr.children('.stateName');
stateName.children('div').text(item.State.Name);
stateName.children('div').removeClass('bereitName besetzName nbzName pauseName abgemeldetName');
stateName.children('div').addClass(item.State.NameClass);
var stateCircle = tr.children('.stateCircle');
stateCircle.children('div').removeClass('Online OnCall AfterTime Pause LoggedOff');
stateCircle.children('div').addClass(item.State.CircleClass);
$.each(item.Skills, function (j, skill) {
var skillElement = tr.children('td[data-id="' + skill.Id + '"]');
if (!skillElement.hasClass('recentlyUpdated')) {
skillElement.removeClass('hasSkill skillIsActive skillIsInactive unableSkill');
if (skill.IsActive == true) {
skillElement.addClass('hasSkill skillIsActive');
}
else if (skill.IsActive == false) {
skillElement.addClass('hasSkill skillIsInactive');
}
else {
skillElement.addClass('unableSkill');
}
}
else {
skillElement.removeClass('recentlyUpdated');
}
if (j == 25) {
return false;
}
});
var extension = tr.children('.extension');
var totalCalls = tr.children('.totalCalls');
var callsPerHour = tr.children('.callsPerHour');
var avgCallDuration = tr.children('.avgCallDuration');
extension.text(item.Extension);
totalCalls.text(item.AvgCalls.TotalCalls);
callsPerHour.text(item.AvgCalls.CallsPerHour);
avgCallDuration.text(item.AvgCalls.AvgCallDuration);
tr.addClass('time' + detectClass);
}
var allTr = $('tr.agentTr');
});
}
$('tr.agentTr').each(function (i, item) {
if (!$(item).hasClass('time' + detectClass)) {
item.remove();
}
});
detectClass++;
$('.usersTable').waitMe('hide');
}
});
}
function getSkillHeader() {
$.ajax({
url: '#Url.Action("GetSkillHeaderWithAjax", "Home")',
success: function (data) {
if (data.length == 0) {
$('.allSkillsHidden').show();
}
else {
$('.allSkillsHidden').hide();
}
if (data != false) {
$.each(data, function (i, item) {
var tr = $('tr[data-id="' + item.Id + '"].skillTr');
if (!tr.length) {
var html = '';
html += '<tr data-id="' + item.Id + '" class="skillTr">';
html += '<th class="name">' + item.Name + '</th>';
html += '<th class="text-center waitingQueue">~</th>';
html += '<th class="text-center activeCalls">~</th>';
html += '<th class="text-center totalFreeAgents">' + item.TotalFreeAgents + '</th>';
html += '<th class="text-center totalSignedInAgents">' + item.TotalSignedInAgents + '</th>';
html += '</tr>';
$('.skillsHeaderTableBody').append(html);
}
else {
var name = tr.children('.name');
name.text(item.Name);
var totalFreeAgents = tr.children('.totalFreeAgents');
totalFreeAgents.text(item.TotalFreeAgents);
var totalSignedInAgents = tr.children('.totalSignedInAgents');
totalSignedInAgents.text(item.TotalSignedInAgents);
}
});
}
$('.skillHeaderTable').waitMe('hide');
}
});
}
//call getUserDatas method every 1 seconds
setInterval(function () {
getUserDatas();
},1000);
setInterval(function () {
getSkillHeader();
}, 1000);
C#:
public ActionResult AddRemoveSkill(string userId, string skillId, bool add)
{
try
{
var skill = _sysCfgContext.GetUserSkill(Guid.Parse(userId), Guid.Parse(skillId));
if (add)
skill.IsActive = true;
else
skill.IsActive = false;
_sysCfgContext.EditUserSkill(skill);
_sysCfgContext.SaveChanges();
return Json(true, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
I'm using the assumption that those two functions aren't dependent upon one another.
function getUserDatas() {
var type = $('#Type').val();
var skill = $('#Skill').val();
return $.ajax(function() {
//Code omitted for brevity
});
}
function getSkillHeader() {
return $.ajax(function() {
//Code omitted for brevity
});
}
getUserDatas();
getSkillHeader();
var interval = setInterval(function(){
$.when(getUserDatas(), getSkillHeader())
.then(function(resultUserDatas,resultSkillHeader)
},1000);
I have to add that this is the untested code.

Does not want to be inserted as html in CKeditor

onOk: function() {
var dialog = this;
var contentFromTextarea = dialog.getValueOf('tab-main','content');
var rowArray = new Array();
var cellArray = new Array();
var row = '';
rowArray = contentFromTextarea.split(';');
for (var i = 0; i < rowArray.length-1; i++)
{
cellArray[i] = rowArray[i].split(':');
row += '<div>' + '<span>' + cellArray[i][0] + '</span>' + '<span>' + cellArray[i][1] + '</span>' + '</div>'
}
row = '<div>' + row + '</div>';
editor.insertHtml(row);
}
Does not want to be inserted as html in CKeditor. Why?
Thanks for help.
Try displaying "row" just before you run the editor.insertHtml(row);
command just to make sure you html tags are well formed. why are you adding a div tag inside another div tag?

Ajax requests in a loop- refresh div after each request not working in IE8

I have a loop in which I'm making Ajax xmlhttp requests. This occurs within a function triggered by a window.onload event.
The Ajax calls are being made with async=false, because they need to occur in a specific order that relies on each step completing before the next can occur.
With each successive request in the loop, I'm updating a div with the xmlhttp.responseText.
Firefox is refreshing between calls as desired.
IE is not. When the loop begins, the div is populated with the pre-loop content. When the loop finishes, the div is populated with the first refresh that occurs outside of the loop.
Can someone please help?
Two attempted solutions:
1. Adding a random string to the end of the GET query string to ensure a unique url
2. Submitting with the POST method
No luck with either.
Thanks.
Code...
<script type="text/javascript">
function order_process() {
var err;
var queue_id = "<?= implode(':',$plans[$_REQUEST['order_queue_id']]); ?>".split(':'); // Queue ID
var queue_ax = "<?= implode(':',array_keys($plans[$_REQUEST['order_queue_id']])); ?>".split(':'); // Queue Action
i = 0;
for (step in queue_id) {
// The DIV contents that display during each loop iteration
document.getElementById("barber_pole").innerHTML='\
<center>\
<table style="align:left" border="0" cellpacing="1" cellpadding="1">\
<tr><td><B>Processing Order</B><span style="float:right;">Step ' + (i + 1) + '/' + queue_id.length + '</span></td></tr>\
<tr><td style="background-color:#FFFFFF;height:1.5px"></td></tr>\
<tr><td height="20" style="text-align:center">' + queue_ax[i] + '...</td></tr>\
<tr><td height="20"><IMG SRC="../../_include/images/barber_pole.gif" style="vertical-align: middle;"></td></tr>\
</table>\
</center>';
xmlhttp = ajax_request(); // Create request object
xmlhttp.onreadystatechange=function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
1;
}
}
var url = '../../../api/order_process.php?api_login=' + "<?=$api_login?>" + '&api_pass=' + "<?=$api_pass?>" + "&order_id=<?= $_REQUEST['order_id']?>" + '&order_action_id=' + queue_id[step] + '&timeid=' + Math.random();
xmlhttp.open("GET",url,false);
xmlhttp.send();
// If the response includes the string 'failed' exit the loop and render error error message
if (xmlhttp.responseText.split(',')[0] == 'failed') {
err = queue_ax[i] == 'Registering Domain'
? "<h1 class=\"landing-title\">" + fname + ', ' + "<?=$feedback[domain_register][title]?>" + "</h1><DIV class='landing-body'><?=$feedback[domain_register][body]?></DIV>"
: queue_ax[i] == 'Provisioning cPanel Account'
? "<h1 class=\"landing-title\">" + fname + ', ' + "<?=$feedback[cpanel_provision][title]?>" + "</h1><DIV class='landing-body'><?=$feedback[cpanel_provision][body]?></DIV>"
: queue_ax[i] == 'Credit Card Fraud Protection'
? "<h1 class=\"landing-title\">" + fname + ', ' + "<?=$feedback[maxmind_minfraud][title]?>" + "</h1><DIV class='landing-body'><?=$feedback[maxmind_minfraud][body]?>\"" + xmlhttp.responseText + '"</DIV>'
: queue_ax[i] == 'Verifying Payment'
? "<h1 class=\"landing-title\">" + fname + ', ' + "<?=$feedback[verify_payment][title]?>" + "</h1><DIV class='landing-body'><?=$feedback[verify_payment][body]?>\"" + xmlhttp.responseText + '"</DIV>'
: xmlhttp.responseText == 'failed,'
? "<h1 class=\"landing-title\">" + fname + ', ' + "<?=$feedback[gen_err][title]?>" + "</h1><DIV class='landing-body'><?=$feedback[gen_err][body]?></DIV>"
: "<h1 class=\"landing-title\">" + fname + ', ' + "<?=$feedback[gen_err][title]?>" + "</h1><DIV class='landing-body'><?=$feedback[gen_err][body]?>\"" + xmlhttp.responseText + '"</DIV>';
break;
}
i++;
}
if (err) {
document.getElementById("landing-pres").innerHTML = err;
Cufon.replace('.landing-title');
} else {
document.getElementById("barber_pole").innerHTML = "<?= $thank[$_REQUEST['order_queue_id']][1] ?>";
}
}
window.onload=order_process;
</script>
async=false is not recommended [third parameter in xmlhttp.open("GET",url,false);], and we should not write onreadystatechange function if we are using async=false [Also, you are doing nothing in that function]. Please refer http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
Here is the good way that collecting / preparing all HTML once and update your "barber_pole" div like this..
<script type="text/javascript">
function order_process()
{
var err;
var queue_ids = "<?php echo implode(':',$plans[$_REQUEST['order_queue_id']]); ?>"; // Queue IDs separated by ':'
var queue_axns = "<?php echo implode(':',array_keys($plans[$_REQUEST['order_queue_id']])); ?>"; // Queue Actions separated by ':'
var xmlhttp = ajax_request(); // Create request object
var url = '../../../api/order_process.php?api_login=' + "<?=$api_login?>" + '&api_pass=' + "<?=$api_pass?>" + "&order_id=<?= $_REQUEST['order_id']?>" + '&order_action_ids=' + encodeURIComponent(queue_ids) + '&order_actions=' + encodeURIComponent(queue_axns) + '&timeid=' + Math.random();
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState == 4)
{
document.getElementById("barber_pole").innerHTML = xmlhttp.responseText;;
}
else
{
document.getElementById("barber_pole").innerHTML = "Processing..";
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
window.onload=order_process;
</script>
in order_process.php file...
<?php
//Checking whether logged in or not blah blah..
$action_ids = $_REQUEST['order_action_ids'];
$order_actions = $_REQUEST['order_actions'];
$actions_ids_array = explode(":", $action_ids);
$order_actions_array = explode(":", $order_actions);
$strHTML = '';
for($cnt=0; $cnt < count($actions_ids_array); $cnt++ )
{
$each_action_id = $actions_ids_array[$cnt];
$each_action = $order_actions[$cnt];
//Process each action collect $fname and $status value and generate HTML
//blah blah..
$strHTML .= "<h1 class=\"landing-title\">" . $fname . $status . "</h1>";
}
echo $strHTML;
exit;

Resources