Including a for loop in an if statement - javascript

I'm building an application in which I want to display some errors when a user enters invalid values in an input box. A correct value is appended as 'entry' to a div if no errors were found. In total there are 3 cases when to display errors:
The input value is empty
The input value is a number
The input value already exists
These errors are displayed with if else statements.
1.and 2. were easy, but the problem case (3.) only validates against the first element of class .cat_entry.
if(cat_input == '') { // generate errors
errorDisplay(error_input_empty);
} else if(!isNaN(cat_input)) {
errorDisplay(error_input_number);
} else if($('.cat_entry') == cat_input) { // THIS IS THE PROBLEMATIC LINE
// .cat_entry is the class of the entries that have been appended
errorDisplay(error_duplicate);
} else {
// stuff
};
So I believe I need a for loop/ .each() (no problem so far), but how do I include this as a condition in an if statement? Something like.. if( for(i=0;i<$('.cat_entry').length;i++) { ... }; ... How to return true (or something similar) when one of the entries matches the input value, then pass the return value to the if statement?
EDIT: here is a jsFiddle with the relevant code. I updated it with $.inArray() method. I'd like to try and use this instead of a for / .each() loop.

You can try this:
var a=$('.cat_entry'),o={};
for(i=0;i<a.length;i++) {
var s=a[i].val();
if(s in o){
errorDisplay(error_duplicate);
return;
}
o[s]=true;
}
or
var o={};
$('.cat_entry').each(function(){
var s=$(this).val();
if(s in o){
errorDisplay(error_duplicate);
return;
}
o[s]=true;
}

You can actually use the jQuery inArray function for this, such as:
else if($.inArray(cat_input, $('.cat_entry') != -1)
}

The solution was to add this to the function:
var isDuplicate = false;
$('.cat_entry').each(function() {
if(!$(this).text().indexOf(cat_input)) {
isDuplicate = true;
}
// And in the if else loop:
else if(isDuplicate == true)
//and just before the function ends
isDuplicate = false;
Thanks to all for the help you offered.

Related

How does the matching JS code using indexOf work?

I've managed to copy some JS over into my doc, and I've got it working. But I don't entirely understand how its doing it.
It's a search function to match with data in a table and hide any rows that don't match.
But I don't understand the active line of code that actually searches and matches. Would someone explain it?
$('#searchBar').keyup(function() {
searchFunction($(this).val());
});
function searchFunction(value) {
$('#results tr').each(function() {
var found = 'false';
$(this).each(function() {
if ($(this).text().toLowerCase().indexOf(value.toLowerCase()) >= 0) {
found = 'true';
}
});
if (found === 'true') {
$(this).show();
} else {
$(this).hide();
}
})
};
It's this line I can't get my head around:
if ($(this).text().toLowerCase().indexOf(value.toLowerCase()) >= 0) {
found = 'true';
}
I understand how it changes the variable to true, but I don't understand how it matches the data in the Table row with the Value fed in.
It converts the value you sent to the function to lowercase, and then looks at the data in the row. It converts that to lowercase too, and sees if there is a match using indexof, which is covered here: How to use IndexOf in JQuery
Basically, the indexOf() method returns the position of the first occurrence of a specified value in a string. It returns -1 if the value to search does not occur.
Consider searching for "test"
var str = "Hello this is a test";
var n = str.indexOf("test");
The result of n will be: 16, ergo, as in your script, larger than 0... and "found"
What it does is
For each rows in my table "result"
If one of all these values, that I look in lowercase, is equal to what I typed in the "searchBar" in lower case, more than one time, then I found it, and so found = "true"
From search bar key press event will be triggered and value of search bar will passed to search function
$("#searchBar").keyup(function() {
searchFunction($(this).val());
});
function searchFunction(value) {
//value will contain the value of search bar
$("#results tr").each(function() {
//assuming value is not there in tr
var found = "false";
//now searching for each tr for value
$(this).each(function() {
//converting to lower case and comparing each value with searchbar value
if (
$(this)
.text()
.toLowerCase()
.indexOf(value.toLowerCase()) >= 0
) {
found = "true";
}
});
//actual showing/hiding row
if (found === "true") {
$(this).show();
} else {
$(this).hide();
}
});
}
if need more info about index of
https://www.w3schools.com/jsref/jsref_indexof.asp
#MattCouthon let me know if you need anything else

Avoid jquery function for all the content

I have a table with 20 rows. In each row there is an element
<p class="exp-date">'.$cust->Expiration_Date.'</p>
This element is going to be repeated and return different values but in a lot of rows return 0001-01-01.
I want to hide this content so I wrote this in javascript
var exp = $(".exp-date").val();
var exphide = '0001-01-01';
if(exp = exphide) {
$(".exp-date").html('');
}
and also have tried this
$('.exp-date').each(function() {
if(exp = exphide) {
$(".exp-date").html('');
}
});
But in both cases apply the jquery on the first row and modify everything not only where the statement is declared.
Someone any idea?
Thanks in advance
You're using assignment in if statement. The condition exp = exphide will always evaluate to true and the code inside the if statement will execute for all the elements.
Change
if(exp = exphide) {
to
if(exp == exphide) {
or
if(exp === exphide) {
Also, use text() instead of html() to get the date, and use trim() on it to remove extra spaces before comparing.
Use this/$(this) inside the each to get the innerText of the current element.
$('.exp-date').each(function () {
if ($(this).text().trim() == exphide) {
// ^^^^^^^^^^^^^^^^^^^^^^^^
$(this).html('');
// ^^^^
}
});
Use == and "this", else it will point to all classes. Code shown below
var exphide = '0001-01-01';
$('.exp-date').each(function() {
if(this.innerHTML == exphide) { //this.innerHTML
$(this).html(''); //this.html..else will point to all classes
}
});
First you should correct the syntax in the if condition and then try the below code. When you are using "each" for looping you should pass index and value to the callback function as shown below. Then you can achieve the desired result.
var exphide = '0001-01-01';
$('.exp-date').each(function(index, value) {
var exp = $(value).text();
if(exp == exphide) {
$(value).html('');
}
});
I suggest not to remove the content from table cell instead you can hide. Hope this helps.

HTML 5 toggling the contenteditable attribute with javascript

enter code hereI am trying to make something editable online with a function like this
function toggle_editable (div, cssclass) {
var classToEdit = document.getElementsByClassName(cssclass)
for (i = 0;classToEdit.length; i++) {
if (classToEdit[i].contentEditable == false) {
classToEdit[i].contentEditable = true ;
}
if (classToEdit[i].contentEditable == true) {
classToEdit[i].contentEditable = false ;
}
}
}
classToEdit is a collection of HTML elements with the same class name or whatever document.getElementsByClassName(cssclass) returns
when going through the debugger it jumps over the line
classToEdit[i].contentEditable == true
as well as over the line
classToEdit[i].contentEditable == true
and does not execute the code in the braces following the if statements
this works however - meaning it sets the contenteditable property without hesitation
classToEdit.contenteditable = true;
as well as this
classToEdit.contenteditable = false;
(well obviously)
also this seemed to have no effect
classToEdit.contenteditable = !classToEdit.contenteditable
ideas anyone?
ps why is the loop
You've created an infinite loop here:
for (i = 0;classToEdit.length; i++) {
Should be:
for (var i = 0; i < classToEdit.length; i++) {
But, if you say classToEdit.contenteditable = true "works", you've to define "not working/is working" since the snippet doesn't definitely do what you expect it to do, if classToEdit is a HTMLCollection.
It looks like you'd want to toggle contentEditable values, you can do it like this:
for (var i = 0; i < classToEdit.length; i++) {
if (classToEdit[i].contentEditable == false) {
classToEdit[i].contentEditable = true ;
} else { // Notice else here, no need for another check
classToEdit[i].contentEditable = false;
}
}
Or simply without ifs in the loop:
classToEdit[i].contentEditable = !classToEdit[i].contentEditable;
Your current code will switch the value back to it's original in a case the value was false.
HTMLElement.contentEditable returns a string and not a boolean.
Hence, what you want to identify the state of your editable field is:
// Incorrect
classToEdit[i].contentEditable == true
// Coorect
classToEdit[i].contentEditable === 'true'
What's even better if you want to know the state of your fields is to use HTMLElement.isContentEditable
which returns a boolean:
classToEdit[i].contentEditable = !element.isContentEditable
Another way to refactor the above:
function toggleContentEdit() {
var editableFields = document.getElementsByClassName('editable');
[].forEach.call(editableFields, function(field){
var isEditable = field.isContentEditable;
field.setAttribute('contenteditable', !isEditable);
});
};
JSFiddle: http://jsfiddle.net/6qz3aotv/

Display error if element in array have 0 value

i have an array in javascript using map function. it collect data from a loop drop down. i just want to ask how to check if array have 0 then display error message. "One of the data not selected"
the array code :
var self_assess_check = $("select[name='self_assess[]'] option:selected").map(function() {
return $(this).text();
}).get();
alert(self_assess_check);
if i alert the array alert(self_assess_check); it produce : 1,0,2,-,-,5,0
how can i make if condition to check if whole array have 0 value then show error message
what i made:
if ((self_assess_check) == "0"){
alert("One of the data not selected");
return false;
}else{
var r=confirm("Make sure all answer is correct. Once Submit it cannot be changed");
if (r==true){
}else{
return false;
}
}
i think my if condition not correct since it will go to else and skip if.tq
Use $.inArray()
if ($.inArray('0', self_assess_check) != -1) {
alert("One of the data not selected");
return false;
} else {
var r = confirm("Make sure all answer is correct. Once Submit it cannot be changed");
if (r == true) {
} else {
return false;
}
}
Note: Array.indexOf() is not used since IE8 might have to be supported.
You can check Array as below code.
function isUndefined(targetO){
return (targetO == 'undefined' || targetO == undefined);
} if(!isUndefined(self_assess_check){ if(self_assess_check.length!=0){alert("Array contain values"); }}
This will work.

breaking main loop - jstree

I am using jstree library to display a tree.
In the code below, I am looping through the selected nodes in the tree and based on some conditions, I am assigning a variable 'allow_edit' a boolean value.
I would like to break the main loop if 'allow_edit = false'.
I tried using label and breaking the loop but this does not seem to work. I am getting undefined label.
loop1:
$j.each($j("#demo2").jstree("get_selected"), function(index, element) {
var selected_node_depth = parseInt($j(element).attr('node_depth'));
var allow_edit = false;
var array_first_filter = $j.grep(array_first, function(v) { return v[1] != "not detected";})
var array_second_filter = $j.grep(array_first_filter, function(v) { return v[3] > selected_node_depth;})
if (array_second_filter.length === 0 || array_second_filter.length == null)
{
allow_edit = true;
}
else{
alert("Confliction exists in your selected terms.");
allow_edit = false;
//break loop1; /** not working, getting undefined label **/
}
}
Any suggestions on how to break the main loop if 'allow_edit = false'? Thanks a lot
If the function you pass to .each() returns false, the iteration will stop.
else {
allow_edit = false; // pointless since you're about to return ...
return false;
}
Also, as a programming style note, any construction of the form:
if (something) {
flag = true;
}
else {
flag = false;
}
can be better written as simply:
flag = something;
In JavaScript, to force flag to be boolean (true or false), you can do this:
flag = !!(something);
The two ! (logical "not") operators force the expression ("something") to be evaluated as a boolean by the same rules as are used when that expression is the test clause of an if statement.

Categories