JQuery and Bootstrap based toaster - javascript

In my HTML page i have table in which each row, there is a check box.
My requirement is if more then one row is selected i.e. if the array length is 2, a toaster message has to be shown.
I got a use case there and it is,
if i select 2 rows(array length is 2), message is showing .
Then select 3rd row(array length is 3) and again deselect 3rd row(array length is 2 again).
Now also it shows the message. Here i don't want that toast.
My approach is :
$scope.toggleOne = function () {
if ($scope.selectedUsers.length === 2) {
showMessage();
}
for (var j = 0; j < $scope.users.length; j++) {
if (!$filter('filter')($scope.selectedUsers, $scope.users[j].id, true).length) {
$scope.selectAllCheckboxOfUsers = false;
return;
}
}
$scope.selectAllCheckboxOfUsers = true;
}

If you want to display the message just when going from 1 selected to 2 selected, you can check for that:
var previousSelectedNum = 0;
$scope.toggleOne = function () {
if ($scope.selectedUsers.length === 2 && previousSelectedNum === 1) {
showMessage();
}
// ...
previousSelectedNum = $scope.selectedUsers.length;
}

You can use a flag such as,
var isMessageShown = false;
Then in your function use as,
$scope.toggleOne = function () {
if($scope.selectedUsers.length === 1){
isMessageShown = false;
}
if ($scope.selectedUsers.length === 2 && !isMessageShown) {
isMessageShown = true;
showMessage();
}
for (var j = 0; j < $scope.users.length; j++) {
if (!$filter('filter')($scope.selectedUsers, $scope.users[j].id, true).length) {
$scope.selectAllCheckboxOfUsers = false;
return;
}
}
$scope.selectAllCheckboxOfUsers = true;
}

Related

JS object changed to true, still treated like false

When setting value of object to true it looks and seems it changed it but I still cant use it(as it stayed false).
validateNextMove() {
Card.setArrayNextMoveValid(this.cardRepository.findAll(), false);
let client = this.clientRepository.findByTurn(true);
let provjera = 0;
if (client instanceof UNOClient) {
let cards = client.getCards();
for (let i = 0; i < cards.length; i++) {
if (this.cardCanBePlaced(cards[i])) {
provjera++;
cards[i].setNextMoveValid(true);
console.log(cards[i].getNextMoveValid());
console.log(provjera);
}
}
if (provjera == 0) {
for (let i = 0; i < cards.length; i++) {
cards[i].setNextMoveValid(true);
console.log(cards[i].getNextMoveValid());
console.log(provjera);
}
}
How do I fix this ?
this is my method for checking if card can be place:
cardCanBePlaced(card){
let current = this.discardDeck.slice(-1)[0];
if(typeof current === 'undefined'){
return true;
}
//Check if card is allowed
if(
card.getColor() === current.getColor()
){
return true;
}
return false;
}
if in above mtehod i add global variable to count if there is any available it still doesnt make it work, something like this(counter++ if there is available card of that color)
if(card.getColor()!= current.getColor() && counter==0){
return true;
}

Execute the else statement if none of the items are found

I have this for loop, and I would like to execute the else in the for loop only if none of the if conditions are met. The for loop runs until every item in the database has been checked. If none of the items in the database matches the user input then I want to run the else.
Right now, it runs the else right after the first try which means if the item matches is in the last row, it will just throw it in the error page since it stops the evaluation at the first iteration.
for(var i=0; i< rows.length; i++) {
if (rows[i].hashtag == userEnteredHashtag) {
// Display the choose Box page
res.render('chooseBox', {});
}
else {
// Display the invalid hashtag page
res.render('invalidHashtag', {});
}
}
Just move the else portion outside of the loop and execute it based on a flag
var wasFound = false;
for (var i = 0; i < rows.length; i++) {
if (rows[i].hashtag == userEnteredHashtag) {
// ...
wasFound = true; // set the flag here
}
}
if (!wasFound) {
res.render('invalidHashtag', {});
}
So add a check outside.
var hasMatch = false;
for (var i = 0; i < rows.length; i++) {
if (rows[i].hashtag == userEnteredHashtag) {
// Display the choose Box page
res.render('chooseBox', {});
hasMatch = true;
}
}
if (!hasMatch) {
// Display the invalid hashtag page
res.render('invalidHashtag', {});
}
Create a variable to track whether your condition has been met:
var isValid = true;
for(var i=0; i< rows.length; i++) {
if (rows[i].hashtag != userEnteredHashtag) {
isValid = false
}
}
isValid ? res.render('chooseBox') : res.render('invalidHashtag')
Another way to do it is to use filter and forEach.
var rows = [{hashtag: '#a'}, {hashtag: 'b'}, {hashtag: 'c'}];
var userEnteredHashTag = '#a';
var matchingRows = rows.filter(row => row.hashtag === userEnteredHashTag);
if (matchingRows.length) {
matchingRows.forEach(row => console.log(row));
} else {
console.log('invalid');
}

Multiple click listeners - java script

I am working on a project that imports some javascript rules from a file myjs.js, which is called (on all the web page of the project) in the header.
This files manages the behavior of checkboxes, and in fact toggling the checks of every checkbox pairs. The problem is that in some case, this behavior is wrong but I can't change anything in this js file because it is too complex.
So, on some page, I decided to listen to the click event on some checkbox to correct the behavior : the problem is that there is a conflict of script and I can't trigger my script (put on this very page). How can I force it to make my java script listened first ?
In fact the checkbox are constructed by myjs.js, applying to the html sequece
<div class="left">
<input type="radio" name="isPubOk" id="pubOk" checked="checked" />
<label for="pubOk"><?php echo _("Oui"); ?></label>
</div>
<div class="left">
<input type ="radio" name="isPubNok" id="pubNok" checked="" />
<label for="pubNok"><?php echo _("Non"); ?></label>
</div>
Here's a sample of the js file :
function initCustomForms() {
getElements();
separateElements();
replaceRadios();
replaceCheckboxes();
replaceSelects();
// hide drop when scrolling or resizing window
if (window.addEventListener) {
window.addEventListener("scroll", hideActiveSelectDrop, false);
window.addEventListener("resize", hideActiveSelectDrop, false);
}
else if (window.attachEvent) {
window.attachEvent("onscroll", hideActiveSelectDrop);
window.attachEvent("onresize", hideActiveSelectDrop);
}
}
function refreshCustomForms() {
// remove prevously created elements
if(window.inputs) {
for(var i = 0; i < checkboxes.length; i++) {
if(checkboxes[i].checked) {checkboxes[i]._ca.className = "checkboxAreaChecked";}
else {checkboxes[i]._ca.className = "checkboxArea";}
}
for(var i = 0; i < radios.length; i++) {
if(radios[i].checked) {radios[i]._ra.className = "radioAreaChecked";}
else {radios[i]._ra.className = "radioArea";}
}
for(var i = 0; i < selects.length; i++) {
var newText = document.createElement('div');
if (selects[i].options[selects[i].selectedIndex].title.indexOf('image') != -1) {
newText.innerHTML = '<img src="'+selects[i].options[selects[i].selectedIndex].title+'" alt="" />';
newText.innerHTML += '<span>'+selects[i].options[selects[i].selectedIndex].text+'</span>';
} else {
newText.innerHTML = selects[i].options[selects[i].selectedIndex].text;
}
document.getElementById("mySelectText"+i).innerHTML = newText.innerHTML;
}
}
}
// getting all the required elements
function getElements() {
// remove prevously created elements
if(window.inputs) {
for(var i = 0; i < inputs.length; i++) {
inputs[i].className = inputs[i].className.replace('outtaHere','');
if(inputs[i]._ca) inputs[i]._ca.parentNode.removeChild(inputs[i]._ca);
else if(inputs[i]._ra) inputs[i]._ra.parentNode.removeChild(inputs[i]._ra);
}
for(i = 0; i < selects.length; i++) {
selects[i].replaced = null;
selects[i].className = selects[i].className.replace('outtaHere','');
selects[i]._optionsDiv._parent.parentNode.removeChild(selects[i]._optionsDiv._parent);
selects[i]._optionsDiv.parentNode.removeChild(selects[i]._optionsDiv);
}
}
// reset state
inputs = new Array();
selects = new Array();
labels = new Array();
radios = new Array();
radioLabels = new Array();
checkboxes = new Array();
checkboxLabels = new Array();
for (var nf = 0; nf < document.getElementsByTagName("form").length; nf++) {
if(document.forms[nf].className.indexOf("default") < 0) {
for(var nfi = 0; nfi < document.forms[nf].getElementsByTagName("input").length; nfi++) {inputs.push(document.forms[nf].getElementsByTagName("input")[nfi]);
}
for(var nfl = 0; nfl < document.forms[nf].getElementsByTagName("label").length; nfl++) {labels.push(document.forms[nf].getElementsByTagName("label")[nfl]);}
for(var nfs = 0; nfs < document.forms[nf].getElementsByTagName("select").length; nfs++) {selects.push(document.forms[nf].getElementsByTagName("select")[nfs]);}
}
}
}
// separating all the elements in their respective arrays
function separateElements() {
var r = 0; var c = 0; var t = 0; var rl = 0; var cl = 0; var tl = 0; var b = 0;
for (var q = 0; q < inputs.length; q++) {
if(inputs[q].type == "radio") {
radios[r] = inputs[q]; ++r;
for(var w = 0; w < labels.length; w++) {
if((inputs[q].id) && labels[w].htmlFor == inputs[q].id)
{
radioLabels[rl] = labels[w];
++rl;
}
}
}
if(inputs[q].type == "checkbox") {
checkboxes[c] = inputs[q]; ++c;
for(var w = 0; w < labels.length; w++) {
if((inputs[q].id) && (labels[w].htmlFor == inputs[q].id))
{
checkboxLabels[cl] = labels[w];
++cl;
}
}
}
}
}
//replacing radio buttons
function replaceRadios() {
for (var q = 0; q < radios.length; q++) {
radios[q].className += " outtaHere";
var radioArea = document.createElement("div");
if(radios[q].checked) {
radioArea.className = "radioAreaChecked";
}
else
{
radioArea.className = "radioArea";
}
radioArea.id = "myRadio" + q;
radios[q].parentNode.insertBefore(radioArea, radios[q]);
radios[q]._ra = radioArea;
radioArea.onclick = new Function('rechangeRadios('+q+')');
if (radioLabels[q]) {
if(radios[q].checked) {
radioLabels[q].className += "radioAreaCheckedLabel";
}
radioLabels[q].onclick = new Function('rechangeRadios('+q+')');
}
}
return true;
}
//checking radios
function checkRadios(who) {
var what = radios[who]._ra;
for(var q = 0; q < radios.length; q++) {
if((radios[q]._ra.className == "radioAreaChecked") && (radios[q]._ra.nextSibling.name == radios[who].name))
{
radios[q]._ra.className = "radioArea";
}
}
what.className = "radioAreaChecked";
}
//changing radios
function changeRadios(who) {
if(radios[who].checked) {
for(var q = 0; q < radios.length; q++) {
if(radios[q].name == radios[who].name) {
radios[q].checked = false;
}
radios[who].checked = true;
checkRadios(who);
}
}
}
//rechanging radios
function rechangeRadios(who) {
if(!radios[who].checked) {
for(var q = 0; q < radios.length; q++) {
if(radios[q].name == radios[who].name) {
radios[q].checked = false;
}
if(radioLabels[q]) {
radioLabels[q].className = radioLabels[q].className.replace("radioAreaCheckedLabel","");
}
}
radios[who].checked = true;
if(radioLabels[who] && radioLabels[who].className.indexOf("radioAreaCheckedLabel") < 0) {
radioLabels[who].className += " radioAreaCheckedLabel";
}
checkRadios(who);
if(window.$ && window.$.fn) {
$(radios[who]).trigger('change');
}
}
}
//replacing checkboxes
function replaceCheckboxes() {
if (replaceCheckBoxes == 0)
return;
for (var q = 0; q < checkboxes.length; q++) {
// checkboxes[q].className += " outtaHere";
var checkboxArea = document.createElement("div");
if(checkboxes[q].checked) {
checkboxArea.className = "checkboxAreaChecked";
if(checkboxLabels[q]) {
checkboxLabels[q].className += " checkboxAreaCheckedLabel"
}
}
else {
checkboxArea.className = "checkboxArea";
}
checkboxArea.id = "myCheckbox" + q;
checkboxes[q].parentNode.insertBefore(checkboxArea, checkboxes[q]);
checkboxes[q]._ca = checkboxArea;
checkboxArea.onclick = new Function('rechangeCheckboxes('+q+')');
if (checkboxLabels[q]) {
checkboxLabels[q].onclick = new Function('changeCheckboxes('+q+')');
}
checkboxes[q].onkeydown = checkEvent;
}
return true;
}
//checking checkboxes
function checkCheckboxes(who, action) {
var what = checkboxes[who]._ca;
if(action == true) {
what.className = "checkboxAreaChecked";
what.checked = true;
}
if(action == false) {
what.className = "checkboxArea";
what.checked = false;
}
if(checkboxLabels[who]) {
if(checkboxes[who].checked) {
if(checkboxLabels[who].className.indexOf("checkboxAreaCheckedLabel") < 0) {
checkboxLabels[who].className += " checkboxAreaCheckedLabel";
}
} else {
checkboxLabels[who].className = checkboxLabels[who].className.replace("checkboxAreaCheckedLabel", "");
}
}
}
//changing checkboxes
function changeCheckboxes(who) {
setTimeout(function(){
if(checkboxes[who].checked) {
checkCheckboxes(who, true);
} else {
checkCheckboxes(who, false);
}
},10);
}
Please see the jquery stopImmediatePropagation() function here: http://docs.jquery.com/Types/Event#event.stopImmediatePropagation.28.29
I believe this will achieve what you are looking to do.
Edit: With more detail I may be able to provide a better answer.
Edit 2: It appears that there is no guarantee'd order of execution in Javascript, so inline code may not run before dynamically added code. In addition this particular function may only work if the other handlers are added using jQuery.
Edit 3:
A quick and dirty fix would be to add
<script type="text/javascript">var executeHandlers = false;</script>
to the top of the one html file.
Then edit the javascript file such that the event handlers have
if (executeHandlers !== false) { ... do the logic you normally would here ... }
as the body
This would add one line to the html file that needs to be treated differently, and should not impact the execution on the other pages.
Please note that this is a quick and dirty fix, and there are better ways to do this. Working with the constraints of an existing .js file, and only one file that needs to be treated differently, this seems to be the fastest / easiest way to the desired outcome, not necessarily the best.

Set Selected Indices in Multi Select Using Javascript

Im not sure why this isnt working and would love some help with it! And yes i have looked at this
Im trying to set multiple options in a select element as selected using an array holding the values i want selected and interating through both the array and the options in the select element. Please find code below:
// value is the array.
for (var j = 0; j < value.length; j++) {
for (var i = 0; i < el.length; i++) {
if (el[i].text == value[j]) {
el[i].selected = true;
alert("option should be selected");
}
}
}
After completing these loops nothing is selected, even though the alert() fires.
Any ideas are welcome!
Thanks
CM
PS (not sure whats happened to the code formatting).
EDIT: Full function
if (CheckVariableIsArray(value) == true) {
if (value.length > 1) { // Multiple selections are made, not just a sinle one.
var checkBoxEl = document.getElementById(cbxElement);
checkBoxEl.checked = "checked";
checkBoxEl.onchange(); // Call function to change element to a multi select
document.getElementById(element).onchange(); // Repopulates elements with a new option list.
for (var j = 0; j < value.length; j++) {
for (var i = 0; i < el.length; i++) {
if (el[i].text === value[j]) {
el[i].selected = true;
i = el.length + 1;
}
}
}
//document.getElementById(element).onchange();
}
}
else {
for (var i = 0; i < el.length; i++) {
if (el[i].innerHTML == value) {
el.selectedIndex = i;
document.getElementById(element).onchange();
}
}
}
Works for me. Are you setting el and value correctly? And are you sure you want to look at each option's innerHTML instead of it's value attribute?
See the jsFiddle.
HTML:
<select id="pick_me" multiple="multiple">
<option>Hello</option>
<option>Hello</option>
<option>Foo</option>
<option>Bar</option>
</select>
JS:
var value = ['Foo', 'Bar'],
el = document.getElementById("pick_me");
// value is the array.
for (var j = 0; j < value.length; j++) {
for (var i = 0; i < el.length; i++) {
if (el[i].innerHTML == value[j]) {
el[i].selected = true;
//alert("option should be selected");
}
}
}
Well, first of all, you must set the html select control multiple property, something like this "<select multiple="multiple">...</select>", and then you can use the javascript function SetMultiSelect (defined as below) to set the select html control:
function SetMultiSelect(multiSltCtrl, values)
{
//here, the 1th param multiSltCtrl is a html select control or its jquery object, and the 2th param values is an array
var $sltObj = $(multiSltCtrl) || multiSltCtrl;
var opts = $sltObj[0].options; //
for (var i = 0; i < opts.length; i++)
{
opts[i].selected = false;//don't miss this sentence
for (var j = 0; j < values.length; j++)
{
if (opts[i].value == values[j])
{
opts[i].selected = true;
break;
}
}
}
$sltObj.multiselect("refresh");//don't forget to refresh!
}
$(document).ready(function(){
SetMultiSelect($sltCourse,[0,1,2,3]);
});
Ran into this question and wasn't satisfied with the answers.
Here's a generic, non-jQuery version. It utilises Array.indexOf where possible, but falls back to a foreach loop if it isn't available.
Pass a node into the function, alongside an array of values. Will throw an exception if an invalid element is passed into it. This uses === to check against the value. For the most part, make sure you're comparing the option's value to an array of strings.
E.g. selectValues( document.getElementById( 'my_select_field' ), [ '1', '2', '3'] );
var selectValues = (function() {
var inArray = ( function() {
var returnFn;
if( typeof Array.prototype.indexOf === "function" ) {
returnFn = function(option, values) {
return values.indexOf( option.value ) !== -1;
};
} else {
returnFn = function(option, values) {
var i;
for( i = 0; i < values.length; i += 1 ) {
if( values[ i ] === option.value ) {
return true;
}
}
return false;
}
}
return returnFn;
}() );
return function selectValues(elem, values) {
var
i,
option;
if( typeof elem !== "object" || typeof elem.nodeType === "undefined" )
throw 'selectValues() expects a DOM Node as it\'s first parameter, ' + ( typeof elem ) + ' given.';
if( typeof elem.options === "undefined" )
throw 'selectValues() expects a <select> node with options as it\'s first parameter.';
for( i = 0; i < elem.options.length; i += 1 ) {
option = elem.options[ i ];
option.selected = inArray( option, values );
}
}
}());

How to validate just one checkbox?

I'm working on a piece of code from an open source library called gvalidator. The following checkbox validate function only works when I have two or more checkboxes. For some reason the if(elements[i]checked) line is not returning true when elements only has 1 object in the array.
Anyone have a guess as to why this is happening? Thanks!
this.validate = function() {
// Check if the form has a value set for this checkbox
// by cycling through all of the checkboxes
var elements = document.forms[0].elements[this.field.name];
if(undefined == elements.length){
x = elements;
elements = new Array(x);
}
for (i = 0; i < elements.length; i++) {
if (elements[i].checked) {
document.write(elements[i].name);
this.setState(ONEGEEK.forms.FIELD_STATUS_OK);
return true;
} else {
if (this.modified !== true || !this.isRequired) {
this.setState(ONEGEEK.forms.FIELD_STATUS_INFO);
} else {
this.setState(ONEGEEK.forms.FIELD_STATUS_EMPTY);
}
}
}
return false;
};
Jan was right... almost. The following is required in the function validate as the the form.elements function won't always return an array - it returns an element in the case there is only 1 match:
// Check if the form has a value set for this checkbox
// by cycling through all of the checkboxes
var elements = document.forms[0].elements[this.field.name];
if (elements.length === undefined) {
elements = [ elements ];
}
It is also required in the setup function before it adds the validation events in the first place:
this.setup = function() {
...
// Add events to ALL of the items
var elements = document.forms[0].elements[this.field.name];
if (elements.length === undefined) {
elements = [ elements ];
}
for (i = 0; i < elements.length; i++) {
_du.addEvent(elements[i], 'click', this.applyFieldValidation(this));
_du.addEvent(elements[i], 'click', this.applyContextInformation(this));
_du.addEvent(elements[i], 'change', this.applyFieldModification(this));
}
}
I have updated the source code at code http://code.google.com/p/gvalidator/, the latest binary is available for download here: http://code.google.com/p/gvalidator/downloads/list.
There are some serious and some minor flaws in your code. This is how it should look like. Test this code and tell me if it still does not work and provide any error messages in the error console.
this.validate = function () {
// Check if the form has a value set for this checkbox
// by cycling through all of the checkboxes
var elements = document.forms[0].elements[this.field.name];
if (elements.length === undefined) {
elements = [ elements ];
}
for (var i = 0, ii = elements.length; i < ii; ++i) {
if (elements[i].checked) {
document.write(elements[i].name);
this.setState(ONEGEEK.forms.FIELD_STATUS_OK);
return true;
} else {
if (this.modified !== true || !this.isRequired) {
this.setState(ONEGEEK.forms.FIELD_STATUS_INFO);
} else {
this.setState(ONEGEEK.forms.FIELD_STATUS_EMPTY);
}
}
}
return false;
};

Categories

Resources