For of loop only removes half of the items (Javascript) - javascript

I tried to build a filter for some posts. When a year is selected the other year should be removed from the page. But only the half of the unselected year posts gets deleted. What am I doing wrong?
var filter2020 = document.getElementById('filter20');
var filter2021 = document.getElementById('filter21');
var posts = document.getElementsByClassName('article');
if (filter2020) {
for (item of posts) {
if (item.dataset.year == "Y2020") {
item.remove();
} else {
console.log("no")
}
}
} else if (filter2021) {
for (item of posts) {
if (item.dataset.year == "Y2021") {
item.remove();
} else {
console.log("no")
}
}
} else {
}
<div class="row filtered-news">
<div class="article col-lg-4" data-year="Y2021"> </div>
<div class="article col-lg-4" data-year="Y2020"> </div>
</div>

Related

Target first element of accordion menu with JS

I'm working on a Drupal website and I'm working on revising a component. I would like the first accordion menu item open by default, I have been kind of stuck on this for a little while.
I can not add to html because content is dynamic so has to be done with JS. Here is the script so far.
Any help would be great.
Bellow is the JS and HTML
jQuery(document).ready(() => {
const buttons = document.querySelectorAll('[data-accordion-button]');
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', (e) => {
const toggle = (e.target.getAttribute('aria-expanded') === 'true') ? false : true;
const root = buttons[i].closest('[data-accordion-container]');
const panel = buttons[i].closest('[data-accordion-panel]');
const panelSiblings = getSiblings(panel);
const firstChild = getFirstChild();
const window = panel.querySelector('[data-accordion-window]');
const content = panel.querySelector('[data-accordion-content]');
buttons[i].setAttribute('aria-expanded', toggle);
buttons[i].setAttribute('tabindex', '0');
toggle ?
window.setAttribute('style', `height: ${content.offsetHeight}px; visibility: visible;`) :
window.setAttribute('style', 'height: 0; visibility: hidden;');
if (root.getAttribute('data-accordion-config-single') === 'true') {
panelSiblings.forEach((sibling) => {
const siblingButton = sibling.querySelector('[data-accordion-button]');
const siblingWindow = sibling.querySelector('[data-accordion-window]');
siblingButton.setAttribute('aria-expanded', 'false');
siblingWindow.setAttribute('style', 'height: 0; visibility: hidden;');
});
}
});
// Arrow key controls
buttons[i].addEventListener('keydown', (e) => {
if (e.keyCode === 38) {
if (i === 0) {
buttons[buttons.length - 1].focus();
} else {
buttons[i - 1].focus();
}
}
if (e.keyCode === 40) {
if (i === buttons.length - 1) {
buttons[0].focus();
} else {
buttons[i + 1].focus();
}
}
});
}
function getSiblings(element) {
let siblings = [];
let sibling = element.parentNode.firstChild;
while (sibling) {
if (sibling.nodeType === 1 && sibling !== element) {
siblings.push(sibling);
}
sibling = sibling.nextSibling
}
return siblings;
};
});
```
<div class="accordion" data-accordion-container data-accordion-config-single="false">
<article class="accordion__panel-container" data-accordion-panel>
<h3 class="accordion__header">
<button class="h4 accordion__button" data-accordion-button aria-expanded="false" tabindex="0">
Taxation & Regulation in a Token Economy
</button>
</h3>
<div class="accordion__window" data-accordion-window>
<div class="accordion__content wysiwyg" data-accordion-content>
<p>
This text is for placement only. Vestibulum id ligula porta felis euismod semper.
</p>
</div>
</div>
</article>
<article class="accordion__panel-container" data-accordion-panel>
<h3 class="accordion__header">
<button class="h4 accordion__button" data-accordion-button aria-expanded="false">
Regulatory Content Aggregation
</button>
</h3>
<div class="accordion__window" data-accordion-window>
<div class="accordion__content wysiwyg" data-accordion-content>
<p>We demonstrate our commitment to Total Rewards through:</p>
</div>
</div>
</article>
</div>

Tabs component in javascript class should be reusable

I have a component that should be reusable within a page. And it should be called only when in view.
I've added an extra class function outside class Tabs which is called class Pagination.
this class is not within class Tabs which is breaking the component if reused within the page (multiple times).
Would anyone help me to move the class Pagination inside Tabs? My goal is having a unique class, so I can reuse the component multiple times and only when is in view. I really hope it makes sense,
here you have a Pen demo, as you can see the pagination is not in the right constuctor. I brake the function everytime I try to move it.
class Pagination {
constructor(tabComponent, prevBtnId, nextBtnId) {
this.arrayUtils = new ArrayUtils();
this.tabComponent = tabComponent;
this.prevBtn = document.querySelector(prevBtnId);
this.nextBtn = document.querySelector(nextBtnId);
// listen to tabComponents newly created Toggle event
// in which we wanna make sure to disable Btns or something..
this.tabComponent.onTabsToggle((tabs, tabIndex) => {
this.applyPaginationRules(tabs, tabIndex);
});
}
setDisabled(btn, value) {
if (value) {
btn.setAttribute("disabled", "true");
} else {
btn.removeAttribute("disabled");
}
}
applyPaginationRules(tabs, newActiveIndex) {
const nextBtnDisabled = newActiveIndex === tabs.length - 1;
const prevBtnDisabled = newActiveIndex === 0;
this.setDisabled(this.nextBtn, nextBtnDisabled);
this.setDisabled(this.prevBtn, prevBtnDisabled);
}
paginate(btn, action) {
const block = btn.closest(".tabs-block");
const panels = block.querySelectorAll(".panel");
const tabs = block.querySelectorAll(".tab-wrapper > li > button");
const activeIndex = Array.from(tabs).findIndex(
(t) => t.getAttribute("data-open") === "true"
);
if (tabs.length < 2) {
console.log("0 OR 1 tabs to toggle so no action.");
return;
}
var newActiveIndex;
if (action === "next") {
newActiveIndex = this.arrayUtils.nextIndex(activeIndex, tabs);
} else if (action === "prev") {
newActiveIndex = this.arrayUtils.previousIndex(activeIndex, tabs);
} else {
throw "Invalid toggle action " + action;
}
// enable / disable next and previous btns..
this.applyPaginationRules(tabs, newActiveIndex);
this.tabComponent.toggleTabs(tabs[newActiveIndex], panels);
}
addPaginationListener(btn, action) {
btn.addEventListener("click", (e) => {
this.paginate(btn, action);
});
}
init() {
this.addPaginationListener(this.prevBtn, "prev");
this.addPaginationListener(this.nextBtn, "next");
// disable prev button on beggining since we start at 0..
this.setDisabled(this.prevBtn, true);
}
}
class ArrayUtils {
// getting next index in array
nextIndex(currentIndex, array) {
// if 0 OR 1 elements, index stays the same..
if (array.length < 2) return currentIndex;
// if possible increment.
if (currentIndex < array.length - 1) {
return currentIndex + 1;
}
// if index would exceed array size go to start.
return 0;
}
// getting previous INdex in array:
previousIndex(currentIndex, array) {
// if 0 OR 1 elements, index stays the same..
if (array.length < 2) return currentIndex;
// if possible decrement!
if (currentIndex > 0) {
return currentIndex - 1;
}
// start at the end of array when end is reached ofc.
return array.length - 1;
}
}
class Tabs {
constructor() {
this.tabsBlocks = document.querySelectorAll(".tabs-block");
this.onToggleHandlers = [];
}
onTabsToggle(fn) {
this.onToggleHandlers.push(fn);
}
emitTabsToggle(tabs, tabIndex) {
this.onToggleHandlers.forEach((fn) => fn(tabs, tabIndex));
}
init() {
if (this.tabsBlocks.length > 0) {
Array.prototype.forEach.call(this.tabsBlocks, (tabBlock, index) => {
const tabContainer = tabBlock.querySelector(".tab-wrapper");
const tabs = tabBlock.querySelectorAll(".tab-wrapper li button");
const panels = tabBlock.querySelectorAll(".panel");
tabContainer.setAttribute("role", "tablist");
Array.prototype.forEach.call(tabs, (tab, tabIndex) => {
if (tab.dataset.open === "true") this.toggleTabs(tab, panels);
tab.setAttribute("role", "tab");
tab.setAttribute(
"aria-controls",
`panel-${tab.dataset.target}-block-${index + 1}`
);
const associatedPanel = tabBlock.querySelector(
`[data-panel="${tab.dataset.target}"]`
);
if (associatedPanel !== null) {
associatedPanel.id = `panel-${tab.dataset.target}-block-${
index + 1
}`;
tab.id = `tab-${tab.dataset.target}-block-${index + 1}`;
}
tab.addEventListener("click", () => {
this.toggleTabs(tab, panels);
this.emitTabsToggle(tabs, tabIndex);
});
});
Array.prototype.forEach.call(panels, (panel) => {
const associatedTab = tabBlock.querySelector(
`[data-target="${panel.dataset.panel}"]`
);
panel.setAttribute("role", "tabpanel");
panel.setAttribute("aria-labelledby", `${associatedTab.id}`);
});
});
}
}
toggleTabs = (currentTab, panels) => {
const tabs = currentTab.closest(".tabs-block").querySelectorAll("button");
const target = currentTab.dataset.target;
Array.prototype.forEach.call(tabs, (tab) => {
if (tab.dataset.target !== target) {
tab.classList.remove("is-active");
tab.setAttribute("data-open", "false");
tab.setAttribute("aria-selected", "false");
}
});
Array.prototype.forEach.call(panels, (panel) => {
if (panel.dataset.panel !== target) {
panel.classList.remove("is-active");
} else {
panel.classList.add("is-active");
}
});
/// activate tab..
currentTab.classList.add("is-active");
currentTab.setAttribute("data-open", "true");
currentTab.setAttribute("aria-selected", "true");
};
}
const components = {
Tabs: new Tabs()
};
components.Tabs.init();
// have the pagination more decoupled from tabs!
// it uses tabs component but you can remove it OR apply it to other
// classes like so more easily..
const prevBtnId = ".pagination-prev";
const nextBtnId = ".pagination-next";
const pagination = new Pagination(components.Tabs, prevBtnId, nextBtnId);
pagination.init();
.tabs-block {
border: 1px solid red;
}
.tabs-block .tab-wrapper li {
flex: 1 1 0%;
text-align: center;
}
.tabs-block .tab-wrapper li button {
font-weight: lighter;
font-size: rem(20px);
}
.tabs-block .tab-wrapper li button.is-active {
font-weight: normal;
}
.tabs-block .panel {
display: none;
}
.tabs-block .panel.is-active {
display: block;
}
.is-active {
color: red;
}
<section class="tabs-block">
<ul class="tab-wrapper">
<li><button data-target="1" data-open="true">Tab title 1</button></li>
<li><button data-target="2">Tab title 2</button></li>
<li><button data-target="3">Tab title 3</button></li>
</ul>
<div class="panel-wrapper">
<div data-panel="1" class="panel">
<p>Panel 1 content</p>
</div>
<div data-panel="2" class="panel">
<p>Panel 2 content</p>
</div>
<div data-panel="3" class="panel">
<p>Panel 3 content</p>
</div>
</div>
<button class="buttonPrev pagination-prev">
<< Prev</button>
<button class="buttonNext pagination-next">Next >></button>
</section>

how can i check winners by using jquery [duplicate]

This question already has answers here:
JavaScript TicTacToe if... Winner detection
(7 answers)
Closed 2 years ago.
I am tryin to implement a tic tac to game using jquery, and here is my code:
$(document).ready(function() {
let turn = 1;
$(".smallbox").click(function() {
if (turn == 1) {
$(this).text("X");
$(this).addClass("X");
turn = 2;
} else {
$(this).text("O");
$(this).addClass("O");
turn = 1;
}
$("#tune").text(turn);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box" id="mainbox">
<!-- creat 9 small box -->
<div class="smallbox" id="square1"></div>
<div class="smallbox" id="square2"></div>
<div class="smallbox" id="square3"></div>
<div class="smallbox" id="square4"></div>
<div class="smallbox" id="square5"></div>
<div class="smallbox" id="square6"></div>
<div class="smallbox" id="square7"></div>
<div class="smallbox" id="square8"></div>
<div class="smallbox" id="square9"></div>
</div>
however I have difficulty detecting the winner, due to X and Y. Since my code is providing X information but not Y, how can I improve my code in this regard?
$(document).ready(function() {
let gameArray = [];
let turn = 1;
let gameOver = false;
$("#turn").text(turn === 1 ? 'X' : 'O');
$(".smallbox").click(function() {
let squereIndex = $(this).attr('id').replace('square', '') - 1;
if (turn == 1 && !gameOver && gameArray[squereIndex] === undefined) {
$(this).text("X");
$(this).addClass("X");
turn = 2;
gameArray[squereIndex] = 1;
} else if (!gameOver && gameArray[squereIndex] === undefined) {
$(this).text("O");
$(this).addClass("O");
turn = 1;
gameArray[squereIndex] = -1;
}
checkWinner();
$("#turn").text(turn === 1 ? 'X' : 'O')
});
function checkWinner() {
let result;
//check Rows
for (let i = 0; i <= 6; i += 3) {
result = gameArray[i] + (gameArray[i + 1]) + (gameArray[i + 2]);
if (result === 3) {
$("#winner").text('X win');
gameOver = true;
}
if (result === -3) {
$("#winner").text('O win');
gameOver = true;
}
}
//check Columns
for (let i = 0; i <= 3; i++) {
result = gameArray[i] + (gameArray[i + 3]) + (gameArray[i + 6]);
if (result === 3) {
$("#winner").text('X win');
gameOver = true;
}
if (result === -3) {
$("#winner").text('O win');
gameOver = true;
}
}
//check Diagonal
result = gameArray[0] + (gameArray[4]) + (gameArray[8]);
if (result === 3) {
$("#winner").text('X win');
gameOver = true;
}
if (result === -3) {
$("#winner").text('O win');
gameOver = true;
}
result = gameArray[2] + (gameArray[4]) + (gameArray[6]);
if (result === 3) {
$("#winner").text('X win');
gameOver = true;
}
if (result === -3) {
$("#winner").text('O win');
gameOver = true;
}
}
});
.smallbox {
width: 50px;
border: 1px solid black;
height: 35px;
margin: 2px;
text-align: center;
padding-top: 15px;
}
.row-container {
display: flex;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="box" id="mainbox">
Turn: <span id='turn'></span>
<!-- creat 9 small box -->
<div class='row-container'>
<div class="smallbox" id="square1"></div>
<div class="smallbox" id="square2"></div>
<div class="smallbox" id="square3"></div>
</div>
<div class='row-container'>
<div class="smallbox" id="square4"></div>
<div class="smallbox" id="square5"></div>
<div class="smallbox" id="square6"></div>
</div>
<div class='row-container'>
<div class="smallbox" id="square7"></div>
<div class="smallbox" id="square8"></div>
<div class="smallbox" id="square9"></div>
</div>
<span id='winner'></span>
</div>

Selecting next div with Button and changing the value

I have a 4 div elements each with their own value, for example 0. I have a button with a plus and minus that changes the value in each box. I also have a set next button so you can do the same thing to the next box.
The problem I'm facing is how to select the next div and change the value with the same plus and minus buttons and then selecting the next div and doing the same until you're at the end. It then has to return to the first div. Here is my code:
<div class="code_div">
<div class="code_area">
<p id="number1">00</p>
</div>
<div class="code_area2">
<p id="number2">00</p>
</div>
<div class="code_area3">
<p id="number3">00</p>
</div>
<div class="code_area4">
<p id="number4">00</p>
</div>
var value = 0;
var plus = false;
var minus = false;
$(document).ready(function() {
$('#set_next').click(function() {
});
$('#minus').click(function() {
minus = false;
plus = true;
if (plus == true) {
value -= 5;
}
displayValue()
});
$('#plus').click(function() {
minus = true;
plus = false;
if (minus == true) {
value += 5;
}
displayValue()
});
});
function displayValue() {
document.getElementById("number1").innerHTML = value;
}
Can anyone help me?
Keep it simple. You have a list of divs, so use a list instead. Even if you want to keep your original markup, this should give an idea on how to implement this.
var $items = $('ul li'),
qtItems = $items.length,
activeItem = 0;
$('#setnext').click(function () {
$items.removeClass('active').eq(++activeItem % qtItems).addClass('active');
});
$('#plus, #minus').click(function () {
var currvalue = $items.eq(activeItem % qtItems).text();
this.id === 'plus' ? currvalue++ : currvalue--;
$items.eq(activeItem % qtItems).text(currvalue);
});
ul {
list-style: none;
}
ul li {
display: inline-block;
margin: 0 1em;
padding: 1em;
background-color: green;
opacity: .5;
}
li.active {
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="active">0</li>
<li>0</li>
<li>0</li>
<li>0</li>
</ul>
<button id="setnext">set next</button>
<button id="plus">plus</button>
<button id="minus">minus</button>
But, if you cannot simplify your markup, here is another simple solution using your original html.
As you can see, you don't need all of those classes and ids.
var value = 0;
var plus = false;
var minus = false;
var index=1;
$( document ).ready(function() {
$('#set_next').click(function() {
index++;
//update
$("#number"+index).css("color","blue");
if(index==5){
index=1;
}
});
$('#minus').click(function() {
minus = false;
plus = true;
if (plus == true){
value -= 5;
}
displayValue()
});
$('#plus').click(function() {
minus = true;
plus = false;
if (minus == true){
value += 5;
}
displayValue()
});
});
function displayValue(){
document.getElementById("number"+index).innerHTML = value;
}
Although your code needs a lot of polishing (i can give you a cleaner approach if you want)
https://jsfiddle.net/cbw4zc55/
something along these lines?
html code:
<div class="code_div">
<div class="code_area">
<p id="number1">00</p>
</div>
<div class="code_area2">
<p id="number2">00</p>
</div>
<div class="code_area3">
<p id="number3">00</p>
</div>
<div class="code_area4">
<p id="number4">00</p>
</div>
<button id="set_next">set next</button>
<button id="minus">minus</button>
<button id="plus">plus</button>
javascript:
var current = 1;
var max = 4;
var value = 0;
var plus = false;
var minus = false;
$( document ).ready(function() {
$('#set_next').click(function() {
if( current < max )
{
current+=1;
}
else
{
current = 1;
}
value = parseInt($("#number"+current).text());
});
$('#minus').click(function() {
minus = false;
plus = true;
if (plus == true){
value -= 5;
}
displayValue()
});
$('#plus').click(function() {
minus = true;
plus = false;
if (minus == true){
value += 5;
}
displayValue()
});
});
function displayValue(){
document.getElementById("number"+current).innerHTML = value;
}
EDIT:
Note that you would need to recalculate the current element value each time you change your focus to a new one (aside from that the selected answer is just perfect as well)

KnockOut Drag And Drop Cause Duplication

Here is my first template:
<script type="text/html" id="Testing">
<!-- ko if: $data.CLASSIFICATION_NAME().toLowerCase() == 'general' -->
<!-- ko if: $data.ATTRIBUTE_DISPLAY_TYPE().toLowerCase() == AttributeEnum.NumberRange -->
<li>
<div class="divFilterRow">
<div class="divFilterCol">
<input type="checkbox" data-bind="checked: ISATTRIBUTESELECTED, attr:{'id': ATTRIBUTE_NAME}, click: function(){checkedCallback($data); return true; }" />
</div>
<div class="divFilterCol divFilterCph">
<label data-bind=" text: ATTRIBUTE_NAME, attr:{'for': ATTRIBUTE_NAME,'attributetooltip': ATTRIBUTE_DESCRIPTION}"></label>
<a class="iClose" href="javascript:void(0);" data-bind=" click: $data.removeSelectedAttribute , style: {display: ISATTRIBUTESELECTED() ? 'block' : 'none'}"></a>
</div>
</div>
<div class="iClearBoth" />
<div data-bind=" visible: ISATTRIBUTESELECTED">
<div data-bind=" template: {name: 'sliderTemplate',foreach: filterSliderValues} "></div>
</div>
</li>
<!-- /ko -->
<!-- ko if: $data.ATTRIBUTE_DISPLAY_TYPE().toLowerCase() == AttributeEnum.MultipleChoiceList -->
<li>
<div class="divFilterRow">
<div class="divFilterCol">
<input type="checkbox" data-bind="checked: ISATTRIBUTESELECTED, attr:{'id': ATTRIBUTE_NAME}, click: function(){checkedCallback($data); return true; }" />
</div>
<div class="divFilterCol divFilterCph">
<label data-bind="text: ATTRIBUTE_NAME, attr:{'for': ATTRIBUTE_NAME,'attributetooltip': ATTRIBUTE_DESCRIPTION }"></label>
<a class="iClose" href="javascript:void(0);" data-bind="click: $data.removeSelectedAttribute , style: {display: ISATTRIBUTESELECTED() ? 'block' : 'none'}"></a>
</div>
</div>
<div class="iClearBoth" />
<div data-bind="visible: ISATTRIBUTESELECTED">
<div data-bind=" template: {name: 'sliderTemplate',foreach: filterSliderValues} "></div>
</div>
<div data-bind="visible: ISATTRIBUTESELECTED">
<div data-bind="dialog: {'autoOpen': false, 'title': ATTRIBUTE_NAME,'modal': true,
'resizable': false, width: 950, draggable: false, closeOnEscape: false
#*,buttons: {
'Apply': function () {
$(this).dialog('close');
}
} *#
},
dialogVisible: isDialogOpen"
class="iSmallDialog" >
<div class="HelpBar" style="display: block; margin-bottom: 12px;">
<div class="divHelpContent" data-bind="text: ATTRIBUTE_DESCRIPTION">
</div>
</div>
<div style="padding-top: 5px; padding-bottom: 10px;">
Please select options from the list below:
</div>
<div style="overflow-y: auto; max-height: 200px;" class="ListOptions">
<ul data-bind="sortable: { template: 'TestingTemplate', data: filterListOptions },class:'ui-sortable'"></ul>
</div>
<div class="iDialogSubmit">
<button data-bind="click: $data.onDialogCloseCallback,enable: isOptionsSelected" class="active">TestingApply</button>
<button class="btnInactive" data-dismiss="modal" data-bind="click: $data.onDialogClose" aria-hidden="true">TestingCancel</button>
</div>
</div>
</div>
</li>
<!-- /ko -->
<!-- /ko -->
</script>
Here is my second template:
<script id="TestingTemplate" type="text/html">
<li><label data-bind="text: Value, attr:{'for': Value().replace(/ /g,'_')}"></label></li>
</script>
Here is the way i call it:
<div class="LHSListItem">General</div>
<div class="contentDivWithPadding fixHeightAccordian">
<div class="divAccordianContent" id="divAttributes_General">
<ul data-bind="template: { name : 'Testing', foreach : filterData} "></ul>
</div>
</div>
</li>
Here is my output:
When i drag Active or Out of Study,output becomes as follow:
Here is My Model:
var extendedAttributeMapping = {
//'ignore': ["ISATTRIBUTESELECTED"],
create: function (options) {
var extendedAttributeModel = ko.mapping.fromJS(options.data);
//drop down for SECTION attribute
extendedAttributeModel.selectedFilterStateforSection = ko.observable();
// extendedAttributeModel.sectionCounter = ko.observable("2509");
extendedAttributeModel.removeSelectedAttribute = function (modelObject) {
modelObject.ISATTRIBUTESELECTED(false);
if(modelObject.ATTRIBUTE_DISPLAY_TYPE().toLowerCase() == AttributeEnum.MultipleChoiceList)
{
modelObject.isDialogOpen(false);
extendedAttributeModel.onAttributeUncheckCallback(modelObject);
//modelObject.OptionsCountLabel("");
//modelObject.isOptionsSelected(false);
//modelObject.OptionsSelectedCount(0);
}
if(modelObject.ATTRIBUTE_DISPLAY_TYPE().toLowerCase() == AttributeEnum.NumberRange)
{
extendedAttributeModel.resetSlider(modelObject);
}
sltModel.getsectionCount();
$(document).trigger('OnApplyAttribute');
};
extendedAttributeModel.resetSlider = function(modelObject){
var minCurrentVal = modelObject.filterSliderValues()[0].MINCURRENT();
var maxCurrentVal = modelObject.filterSliderValues()[0].MAXCURRENT();
modelObject.filterSliderValues()[0].min(minCurrentVal);
modelObject.filterSliderValues()[0].max(maxCurrentVal);
};
//jquery UI Dialog custom Helper events
extendedAttributeModel.onDialogCloseCallback = function(modelObject){
//alert("Callback");
//debugger;
modelObject.isDialogOpen(false);
if(modelObject.ATTRIBUTE_CODE().toLowerCase() == "section")
{
extendedAttributeModel.getSectionAttributeOptionsOnApply(modelObject);
}
else
{
extendedAttributeModel.getOptionsOnApply(modelObject);
}
sltModel.getsectionCount();
extendedAttributeModel.setDefaultModified(modelObject);
$(document).trigger('OnApplyAttribute');
};
extendedAttributeModel.onDialogOpen = function(){
extendedAttributeModel.isDialogOpen(true);
//modelObject.isDialogOpen(true);
//modelObject.ISATTRIBUTESELECTED(true);
};
//SECTION ATTRIBUTE IMPLEMENETATION- EXTENDED MODEL
//SECTION CHECKBOXES SELECTION
extendedAttributeModel.getSectionAttributeOptionsOnApply = function(modelObject) {
var totalSelected = 0;
var selectedAttributeID = modelObject.ATTRIBUTE_ID();
ko.utils.arrayForEach(modelObject.filterddlSectionListOptions(), function(outeritem) {
// sltModel.setSectionAttributeOriginalStateName(outeritem);
if(outeritem.sectionList().length > 0)
{
ko.utils.arrayForEach(outeritem.sectionList(),function(item){
if (item.isSectionSelected()) {
totalSelected++;
// outeritem.isSelected(true);
//highlight selected states
}
item.SavedSectionCheckedState(item.isSectionSelected());
});
}
});
extendedAttributeModel.OptionsCountLabel("(" + totalSelected + ")");
extendedAttributeModel.OptionsSelectedCount(totalSelected);
if(totalSelected > 0)
extendedAttributeModel.isOptionsSelected(true);
else
{
extendedAttributeModel.isOptionsSelected(false);
extendedAttributeModel.ISATTRIBUTESELECTED(false);
}
};
//ali method code starts
extendedAttributeModel.isTaskSelected = function(task) {
return task === self.selectedTask();
};
//ali method code ends
extendedAttributeModel.OnSectionAttributeOptionSelect = function(modelObject,parentObject){
//SavedSectionCheckedState
//isSectionModified
//isSectionSelected
//sectionId
//sectionName
//stateCode
modelObject.isSectionModified(true);
var totalSelected=0;
ko.utils.arrayForEach(parentObject.filterddlSectionListOptions(), function(outeritem) {
if(outeritem.sectionList().length > 0)
{
ko.utils.arrayForEach(outeritem.sectionList(),function(item){
if (item.isSectionSelected()) {
totalSelected++;
}
});
}
});
//sections selected per state
var sectionSelectedPerState=0;
ko.utils.arrayForEach(parentObject.filterddlSectionListOptions()[sltModel.SectionAttributeStateIndex()].sectionList(), function(item) {
if (item.isSectionSelected()) {
sectionSelectedPerState++;
}
});
parentObject.filterddlSectionListOptions()[sltModel.SectionAttributeStateIndex()].sectionSelectedCount = (sectionSelectedPerState);
var indexCounter = parentObject.filterddlSectionListOptions()[sltModel.SectionAttributeStateIndex()].Text().indexOf("(");
var stateNameWithCount = 0;
if(indexCounter > -1)
{
stateNameWithCount = parentObject.filterddlSectionListOptions()[sltModel.SectionAttributeStateIndex()].Text().substring(0,indexCounter);
}
else{
stateNameWithCount = parentObject.filterddlSectionListOptions()[sltModel.SectionAttributeStateIndex()].Text();
}
if(sectionSelectedPerState == 0)
parentObject.filterddlSectionListOptions()[sltModel.SectionAttributeStateIndex()].Text($.trim(stateNameWithCount));
else
parentObject.filterddlSectionListOptions()[sltModel.SectionAttributeStateIndex()].Text($.trim($.trim(stateNameWithCount) + " ("+sectionSelectedPerState+")"));
//sections selected per state
if(totalSelected > 0)
{
parentObject.isOptionsSelected(true);
}
else
{parentObject.isOptionsSelected(false);}
};
extendedAttributeModel.getSectionAttributeOptionsSelectedCount = function(modelObject) {
var totalSelected = 0;
var perStateCounter = 0;
var selectedAttributeID = modelObject.ATTRIBUTE_ID();
ko.utils.arrayForEach(modelObject.filterddlSectionListOptions(), function(outeritem) {
if(outeritem.sectionList().length > 0)
{
ko.utils.arrayForEach(outeritem.sectionList(),function(item){
//if user unchecks checked and press cancel
if(item.isSectionModified()) {
item.isSectionSelected(item.SavedSectionCheckedState());
//if(!item.SavedSectionCheckedState())
//sltModel.setSectionAttributeOriginalStateName(outeritem);
}
if (item.isSectionSelected()) {
totalSelected++;
perStateCounter++;
}
});
}
sltModel.setSectionAttributeOriginalStateName(outeritem,perStateCounter);
perStateCounter = 0;
});
//setting the state name for selected sections
extendedAttributeModel.OptionsCountLabel("(" + totalSelected + ")");
extendedAttributeModel.OptionsSelectedCount(totalSelected);
if(totalSelected > 0)
extendedAttributeModel.isOptionsSelected(true);
else
{
extendedAttributeModel.isOptionsSelected(false);
extendedAttributeModel.ISATTRIBUTESELECTED(false);
}
};
//END OF SECTION ATTRIBUTE IMPLEMENETATION- EXTENDED MODEL
extendedAttributeModel.OnOptionSelect = function(modelObject,parentObject){
modelObject.isModified(true);
var totalSelected=0;
ko.utils.arrayForEach(parentObject.filterListOptions(), function(item) {
if(modelObject.childObjects()==null)
{
if (item.isSelected()) {
totalSelected++;
}
}
});
//Get All the child elements for the selected item
//if the selected option is checked then check all the child options
//else vice versa
if(modelObject.childObjects()!=null){
var isChecked = modelObject.isSelected();
ko.utils.arrayForEach(modelObject.childObjects(), function(item) {
//item.isModified(true);
item.isSelected(isChecked);
totalSelected++;
});
}
if(totalSelected > 0)
{
parentObject.isOptionsSelected(true);
}
else
{parentObject.isOptionsSelected(false);}
};
//new event added for the child options
extendedAttributeModel.OnChildOptionSelect = function(modelObject,parentContext, parentContextParentObject, parentObject){
modelObject.isModified(true);
var totalChildSelected=0;
ko.utils.arrayForEach(parentObject.childObjects(), function(item) {
if (item.isSelected())
{
totalChildSelected++;
}
});
if(totalChildSelected == parentObject.childObjects().length)
{
parentObject.isSelected(true);
}
else
{
parentObject.isSelected(false);
}
if(totalChildSelected > 0)
{
parentContextParentObject.isOptionsSelected(true);
}
else
{
parentContextParentObject.isOptionsSelected(false);
}
};
//eof child option event
extendedAttributeModel.setDefaultModified = function(modelObject){
if(modelObject.ATTRIBUTE_CODE().toLowerCase() == "section")
{
ko.utils.arrayForEach(modelObject.filterddlSectionListOptions(), function(outeritem) {
if(outeritem.sectionList().length > 0)
{
ko.utils.arrayForEach(outeritem.sectionList(),function(item){
item.isSectionModified(false);
});
}
});
}
else
{
ko.utils.arrayForEach(modelObject.filterListOptions(),function(elem){
elem.isModified(false);
});
}
};
//instead of using click event , binding applied to observable property itself to show PopUp
// extendedAttributeModel.ISATTRIBUTESELECTED.subscribe(function(value) {
extendedAttributeModel.checkedCallback = function(modelObject,SOURCE){
if(SOURCE == "LABEL")
{
modelObject.ISATTRIBUTESELECTED(true);
}
if(modelObject.ATTRIBUTE_DISPLAY_TYPE().toLowerCase() == AttributeEnum.MultipleChoiceList)
{
extendedAttributeModel.setDefaultModified(modelObject);
if(modelObject.ISATTRIBUTESELECTED())
{
modelObject.isDialogOpen(true);
//if(modelObject.ATTRIBUTE_DISPLAY_TYPE.toLowerCase()=="list")
//{
//}
}
else
{
modelObject.isDialogOpen(false);
extendedAttributeModel.onAttributeUncheckCallback(modelObject);
sltModel.getsectionCount();
$(document).trigger('OnApplyAttribute');
}
}
if(modelObject.ATTRIBUTE_DISPLAY_TYPE().toLowerCase() == AttributeEnum.NumberRange)
{
if(!modelObject.ISATTRIBUTESELECTED())
{
extendedAttributeModel.resetSlider(modelObject);
}
sltModel.getsectionCount();
$(document).trigger('OnApplyAttribute');
}
};
// },extendedAttributeModel);
extendedAttributeModel.onDialogClose = function(modelObject){
//alert("Close");
//debugger;
modelObject.isDialogOpen(false);
if(modelObject.ATTRIBUTE_CODE().toLowerCase() == "section")
{
extendedAttributeModel.getSectionAttributeOptionsSelectedCount(modelObject);
}
else
{
extendedAttributeModel.getOptionsSelectedCount(modelObject);
}
};
//Helper functions for label count selected Options
extendedAttributeModel.OptionsCountLabel = ko.observable();
extendedAttributeModel.OptionsSelectedCount = ko.observable();
extendedAttributeModel.isOptionsSelected = ko.observable();
extendedAttributeModel.getOptionsSelectedCount = function(modelObject) {
debugger;
var totalSelected = 0;
var selectedAttributeID = modelObject.ATTRIBUTE_ID();
ko.utils.arrayForEach(modelObject.filterListOptions(), function(item) {
//Checkbox is checked but cancel button clicked
//if (item.isSelected() && item.isModified()) {
// item.isSelected(item.SavedCheckedState());
//}
//if user unchecks checked and press cancel
if(item.isModified()) {
item.isSelected(item.SavedCheckedState());
}
if (item.isSelected()) {
totalSelected++;
}
});
extendedAttributeModel.OptionsCountLabel("(" + totalSelected + ")");
extendedAttributeModel.OptionsSelectedCount(totalSelected);
if(totalSelected > 0)
extendedAttributeModel.isOptionsSelected(true);
else
{
extendedAttributeModel.isOptionsSelected(false);
extendedAttributeModel.ISATTRIBUTESELECTED(false);
}
};
extendedAttributeModel.getOptionsOnApply = function(modelObject) {
debugger;
var totalSelected = 0;
var selectedAttributeID = modelObject.ATTRIBUTE_ID();
var i=0;
ko.utils.arrayForEach(modelObject.filterListOptions(), function(item) {
if(modelObject.filterListOptions()[i].childObjects()==null)
{
if (item.isSelected()) {
totalSelected++;
}
}
//Get All the child elements for the selected item
//if the selected option is checked then check all the child options
//else vice versa
if(modelObject.filterListOptions()[i].childObjects()!=null){
//var isChecked = modelObject.filterListOptions()[i].isSelected();
//if(isChecked){
ko.utils.arrayForEach(modelObject.filterListOptions()[i].childObjects(), function(item) {
if( item.isSelected())
{
totalSelected++;
}
});
//}
}
//if (item.isSelected()) {
// totalSelected++;
//}
item.SavedCheckedState(item.isSelected());
i++;
});
extendedAttributeModel.OptionsCountLabel("(" + totalSelected + ")");
extendedAttributeModel.OptionsSelectedCount(totalSelected);
if(totalSelected > 0)
extendedAttributeModel.isOptionsSelected(true);
else
{
extendedAttributeModel.isOptionsSelected(false);
extendedAttributeModel.ISATTRIBUTESELECTED(false);
}
};
//extendedAttributeModel.getOnlySelectedCount = function(modelObject) {
// var totalSelected = 0;
// var selectedAttributeID = modelObject.ATTRIBUTE_ID();
// ko.utils.arrayForEach(modelObject.filterListOptions(), function(item) {
// if (item.isSelected()) {
// totalSelected++;
// }
// });
// return totalSelected;
//};
extendedAttributeModel.onAttributeUncheckCallback = function(modelObject) {
if(modelObject.ATTRIBUTE_CODE().toLowerCase() == "section")
{
ko.utils.arrayForEach(modelObject.filterddlSectionListOptions(), function(outeritem) {
sltModel.setSectionAttributeOriginalStateName(outeritem,-1);
if(outeritem.sectionList().length > 0)
{
ko.utils.arrayForEach(outeritem.sectionList(),function(item){
item.isSectionSelected(false);
});
}
});
}
else
{
ko.utils.arrayForEach(extendedAttributeModel.filterListOptions(), function(item) {
item.isSelected(false);
if(item.childObjects()!=null){
ko.utils.arrayForEach(item.childObjects(), function(item) {
item.isSelected(false);
});
}
});
}
extendedAttributeModel.OptionsCountLabel("");
extendedAttributeModel.OptionsSelectedCount(0);
extendedAttributeModel.isOptionsSelected(false);
};
return extendedAttributeModel;
}
};
};
In short,it replicates the drag one option.Kindly tell me what I am missing??
It looks like you're making use of the knockout-sortable library. I've had problems in the past where the templates had whitespace outside of any elements - it's noted on the project's page also:
Note2: When using named templates, you will have the best results across browsers, if you ensure that there is only a single top-level node inside your template with no surrounding text nodes. Inside of the top-level nodes, you can freely use whitespace/text nodes. So, you will want:
<!-- good - no text nodes surrounding template root node -->
<script id="goodTmpl" type="text/html"><li data-bind="text: name">
<span data-bind="text: name"></span>
</li></script>
<!-- bad -->
<script id="badTmpl" type="text/html">
<li>
<span data-bind="text: name"></span>
</li>
</script>

Categories

Resources