I am required to stop the execution of the JavaScript function as soon as any of the table cells contains a zero. I tried my best, but nothing seems to work. I can not understand why is it not working.
function ZeroCheck(IDTable) {
var myData = [];
$('#' + IDTable).find("tr:gt(0)").each(function(i, row) {
var oRow = [];
$(row).find("td").each(function(j, cell) {
if ($(cell).text() == '0') {
alert('Please correct input. There should not be a 0 in any cell');
return false;
}
oRow.push(parseFloat($(cell).text()));
});
myData.push(oRow);
});
};
Please try with this:
function ZeroCheck(IDTable) {
let isZeroDetectted = false;
let myData = [];
$('#' + IDTable).find("tr:gt(0)").each(function(i, row) {
let oRow = [];
$(row).find("td").each(function(j, cell) {
if ($(cell).text() == '0') {
alert('Please correct input. There should not be a 0 in any cell');
isZeroDetectted = true;
return false;
}
oRow.push(parseFloat($(cell).text()));
});
if(isZeroDetectted){
return false;
}
myData.push(oRow);
});};
Corrected and Used version of mplungjan suggested piece of code. I find this code better than my one in my question. It is self-explanatory, fairly easy and gives more control over rows and columns.
function calculateAHP(IDTable){
var myData = [];
var rows = document.getElementById(IDTable).rows;
for (var i = 1; i<rows.length;i++) {
var oRow = [];
for ( var j=1; j<rows[i].cells.length; j++) {
var val = rows[i].cells[j].innerText;
if (parseFloat(val) == 0) {
alert('Please correct input. There should not be a 0 in any cell');
return false;
}
oRow.push(parseFloat(val));
}
myData.push(oRow);
}
};
Related
I have a script that is searching for duplicated text strings in an array and changing the colors.
function checkDuplicates() {
var values = new Array();
var $input = $('input[type=\'text\']');
var error = 0;
$input.each(function() {
$(this).removeClass('double-error');
var that = this;
if (that.value!='') {
values[that.value] = 0;
$('input[type=\'text\']').each(function() {
if (this.value == that.value) {
values[that.value]++;
}
});
} //endif
});
$input.each(function(key) {
if (values[this.value]>1) {
error++;
$(this).addClass('double-error');
}
});
return (error <= 0); //returns false or true
}
<style type="text/css">
.double-error {
color:red;
border:1px solid red;
}
</style>
This is working fine.
However, I need to count duplicated strings and add keep track of whether they are the first occurence of that word, the second occurence of that word, etc.
For example:
Given john, john, peter, doe, peter, john, the result would be john-1, john-2, peter-1, doe, peter-2, john-3.
This is what I currently have:
function eliminateDuplicates() {
var values = new Array();
var $input = $('input[type=\'text\']');
var error = 0;
$input.each(function() {
$(this).removeClass('double-error');
var that = this;
if (that.value!='') {
values[that.value] = 0;
$('input[type=\'text\']').each(function() {
if (this.value == that.value) {
values[that.value]++;
}
});
}
});
$input.each(function(key) {
if (values[this.value]>1) {
error++;
myArray = values[this.value];
for (var i = 0; i < myArray; i++) {
$(this).parent()
.find('input[type=\'text\']')
.val(this.value + '-' + i);
}
}
});
return error <= 0; //return error > 0 ? false : true;
}
But I got this result:
john-0-1-2, john-0-1-2, peter-0-1, doe, peter-0-1, john-0-1-2
What's wrong?
I make some modification:
function eliminateDuplicates() {
var values = new Array();
var $input = $('input[type=\'text\']');
var error = 0;
$input.each(function() {
$(this).removeClass('double-error');
var that = this;
if (that.value!='') {
values[that.value] = 0;
$('input[type=\'text\']').each(function() {
if (this.value == that.value) {
values[that.value]++;
}
});
}
});
$input.each(function(key) {
if (values[this.value]>1) {
var name=this.value;
var names = values[this.value];
values[this.value]++;
for (var i = 0; i < names; i++){
$(this).parent().find('input[type=\'text\']').val(name + '-' + i);
}
}
});
checkDoubles();
return error <= 0; //return error > 0 ? false : true;
}
now I getting counts in sequence but not from 1.
for example if I have 4 duplicated names (Peter) i getting:
Peter-3, Peter-4, Peter-5, Peter-6.
but I need
Peter-1, Peter-2, Peter-3, Peter-4.
what wrong?
I think you're looking for something like this:
function eliminateDuplicates() {
var repeats = {};
var error = false;
//cache inputs
var $inputs = $("input[type='text']");
//loop through inputs and update repeats
for (i = 0; i < $inputs.length; ++i) {
//cache current element
var cur = $inputs[i];
//remove class
$(cur).removeClass("double-error");
//get text of this element
var text = $(cur).val();
//no text -- continue
if (text === "") {
continue;
}
//first time we've came across this value -- intialize it's counter to 1
if ((text in repeats) === false) {
repeats[text] = 1;
}
//repeat offender. Increment its counter.
else {
repeats[text] = repeats[text] + 1;
}
//update the the value for this one
$(cur).val(text + "-" + repeats[text]);
}
return error; // always returns false since I'm not sure
// when it's supposed to return true.
}
PS: I didn't understand when error was supposed to be true, so it's always false. Nevertheless, this should be enough to get you going.
PPS: Plunker here.
I have a function which gets values from elements:
function getTransactionValues() {
var o = {};
o.reservations = [];
$('#custom-headers option:selected').each(function (i, selected) {
o.reservations[i] = $(selected).val();
});
o.amount = $('input[name=amount-price]').val();
o.currency_value = $('input[name=currency-value]').val();
o.currency_name = $('.currency_appendto option:selected').html();
o.actual_amount = $('input[name=actual-amount]').val();
o.actual_remaining = $('input[name=actual-remaining]').val();
o.funds_arrival_date = $('input[name=funds-arrival]').val();
o.paid_to = $('.paidto option:selected').html();
o.checkbox = $('.multi-transaction:checked').map(function () {
return this.value
}).get();
return o;
}
Now i want to check whether amount, actual_amount and funds_arrival_date are filled. if they are i will release the disabled class from a button. i've tried
var check_review = function () {
var a = getTransactionValues();
var options = [a.amount, a.actual_amount, a.funds_arrival_date];
for(i = 0; i < options.length; i++) {
if(options[i].length > 0) {
$('a[name=review_button]').removeClass('disabled');
}
else{
//this array is empty
alert('There is a problem!');
}
}
}
$('.test').click(function() {
check_review();
});
But it doesn't seems to be working..
Remove disabled attribute using JQuery?
Can you please look at above link, I think we should use $('.inputDisabled').prop("disabled", false);
Even if a single array element will be non empty then your code will remove the class disabled from the a. To make sure that all the elements of array are non empty and then only you want to remove the class then the way is:
for(i = 0; i < options.length; i++) {
if(options[i].length > 0) {
$('a[name=review_button]').removeClass('disabled');
}
else{
$('a[name=review_button]').addClass('disabled');
}
}
Or the other way is
var check = true;
for(i = 0; i < options.length; i++) {
if(options[i].length == 0) {
check = false;
}
}
if(check ) $('a[name=review_button]').removeClass('disabled');
Try using Array.prototype.every()
if (options.every(Boolean)) {
$("a[name=review_button]").removeClass("disabled");
} else {
// do other stuff
}
When the user clicks on one of the blocks in the table ( see screenshot ) I want to find all neighbouring blocks with the same color. I am trying to do this recursively, but if I try it with more than three blocks it sometimes goes crazy and calls itself over and over until the program crashes.
As far as I can see, the objects are added to the array, but somehow my tests fails and the same object is added over and over and over.
Any insight on what the problem might be and how to solve it would be much appriciated!
Here's a screenshot
This is the function that is called when the user clicks on a block:
var $matchArray;
$('.block').click(function () {
$matchArray = [$(this)];
var $colorClass;
if ($(this).hasClass('red')) {
$colorClass = 'red';
} else if ($(this).hasClass('green')) {
$colorClass = 'green';
} else if ($(this).hasClass('blue')) {
$colorClass = 'blue';
} else {
$colorClass = 'error';
}
findAllSameColorNeighbours($(this), $colorClass);
});
And this is the recursive method:
findAllSameColorNeighbours = function ($this, $colorClass) {
$this.css('border-style', 'solid');
//LEFT
var $leftBlock = isLeftBlockSameColor($this, $colorClass);
if ($leftBlock != null) {
if (!(arrayContains($matchArray, $leftBlock))) {
$matchArray.push($leftBlock);
findAllSameColorNeighbours($leftBlock, $colorClass);
}
}
//ABOVE
//same as for LEFT
//RIGHT
//same as for LEFT
//BELOW
//same as for LEFT
}
This is how I find the neighboring cells, as far as I can see these work just fine. I have one for each direction:
isLeftBlockSameColor = function ($block, $color) {
var $this = $block;
var $tr = $this.parent().parent();
var col = $tr.children().index($this.parent().prev());
var $leftBlock = $this.parent().siblings().eq(col).children();
var $blockClassMatch = $leftBlock.hasClass($color);
if ($blockClassMatch) {
return $leftBlock;
}
else {
return null;
}
};
Here are some help methods to find out if the object is already in the array or not. I use the index of the row and cell to create a sort of latitude and longditude thing.
arrayContains = function ($array, $object) {
for (i = 0; i < Array.length; i++) {
if (compareIndex($array[i], $object)) {
say('true');
return true;
}
};
return false;
};
compareIndex = function ($obj1, $obj2) {
if ((getRowIndex($obj1)) === (getRowIndex($obj2)) {
if ((getCellIndex($obj1)) === (getCellIndex($obj2)) {
return true;
} else {
return false;
}
} else {
return false;
}
};
getCellIndex = function ($this) {
var $tr = $this.parent().parent();
var index = $tr.children().index($this.parent());
return index;
};
getRowIndex = function ($this) {
var $tr = $this.parent().parent();
var index = $tr.index();
return index;
};
There is a bug in the arrayContains function. The loop will iterates only once, because Array.length is equals to 1(As I tested with chrome browser, but I don't know why). You should use $array.length instead.
arrayContains = function ($array, $object) {
//for (i = 0; i < Array.length; i++) {
for (i = 0; i < $array.length; i++) {
if (compareIndex($array[i], $object)) {
say('true');
return true;
}
};
return false;
};
Can this code be chained and the for loop abstracted away? Using map and filter?
function listViewFilter(){ // test
var DateFiltered = containerdata.filter(function (obj){ // remove dates of 010
return !/010/.test(obj.EventDate);
});
var NameFiltered = [];
for (var i = 0; i < DateFiltered.length; i++){ // remove EventNames.Name if empty string
if (DateFiltered[i].EventNames[0].Name == "") continue;
else NameFiltered.push(DateFiltered[i]);
}
Filtered = NameFiltered;
}
Sure, your for loop does nothing but another filter:
function listViewFilter() {
var DateFiltered = containerdata.filter(function(obj) { // remove dates of 010
return !/010/.test(obj.EventDate);
});
var NameFiltered = DateFiltered.filter(function(obj, i) { // remove EventNames.Name if empty string
return obj.EventNames[0].Name != "";
});
Filtered = NameFiltered;
}
or in short
function listViewFilter() {
Filtered = containerdata.filter(function(obj) {
return !/010/.test(obj.EventDate) && obj.EventNames[0].Name != "";
});
}
function checkSelect(field_id)
{
var oParent = document.getElementById(field_id);
alert(oParent);
var aElements = oParent.getElementsByTagName('input');
alert(aElements);
var c_value = "";
for (var i = 0; i < aElements.length; i++)
{
if (aElements[i].type == 'checkbox')
{
if(aElements[i].checked )
{
c_value=aElements[i].checked.value;
alert(c_value);
}
}
}
//alert(c_value);
}
The code i have searched from here. Please let me know what I'm doing wrong. I want to get the values of checkboxes by it's fieldname or fieldid passed through function. Javascript is not getting the value "fieldid" as the name of checkbox causes an error. If I give the hardcoded value then it works like function given below.
function checkSelect()
{
var bool=false;
var field=document.countryManagementForm.country_ids;
var length=1;
if(field.length==null)
{
//alert("yes");
}
else
{
///alert("No");
length=field.length;
}
for (i = 0; i < length; i++)
{
if(field[i].checked == true)
{
bool=true;
}
}
if(!bool)
{
alert("Please select atleast one country");
return false;
}
else
{
return true;
}
}
I would recommend using a javascript framework for this. It's a breeze to do what you want to do:
For ID:
$('#id').val();
For names:
$('[name="name"]').val();
Jquery and the Docs
change
c_value=aElements[i].checked.value;
to
c_value=aElements[i].value;
and try it again
Looks like country_ids is the name of your checkbox inputs. If so, you can replace this line
var aElements = oParent.getElementsByTagName('input');
by
var aElements = document.getElementsByName(field_id);
and ignore the lines above it. Call your function as checkSelect('country_ids')