Here is the code that I am executing:
filterIssues: function(objectKey, text){
var view = this;
var keys = objectKey.split(".");
var attributeKey = keys[0];
var attributeName;
if (keys.length > 1){
attributeName = keys[1];
}
view.issues.each(function(issue){
var value = issue.get(attributeKey);
console.log(text);
if (value === undefined || value === null){
issue.trigger("hide");
return;
}
if (attributeName !== undefined){
value = value[attributeName];
}
if(value !== undefined){
var matchedText = value.substring(0, text.length - 1);
if ( matchedText === text){
issue.trigger("show");
console.log(value);
return;
}
}
issue.trigger("hide");
});
}
The matchedText == text always returns false.
This is what I get when I play around with the console:
> matchedText
"sande"
> text
"sande"
> typeof(text)
"string"
> typeof(matchedText)
"string"
> matchedText === text
false
> matchedText == text
false
I do realize that and === will always check if both the objects are the same and I have read
JavaScript equal operations anomalies and Javascript string equality.
Is there something wrong in the code that I am overlooking?
I think you are misusing the subString() method. If you use subString(), use the length without -1.
Well I eventually found out what was the problem. Thanks for your responses and I believe you might not have come across the answer for the lack of information.
The problem lied in the text value that I was passing to the function. The text contained a "" at the end and that's why comparison just did not work.
Related
I'm populating a table with data - using fixed-data-table, which is a React.js component. However, that isn't so important at this stage.
The table has a search box where the issue stems from.
First, here's the interesting part of the code.
for (var index = 0; index < size; index++) {
if (!filterBy || filterBy == undefined) {
filteredIndexes.push(index);
}
else {
var backendInfo = this._dataList[index];
var userListMap = hostInfo.userList;
var userListArr = Object.values(userListMap);
function checkUsers(){
for (var key in userListArr) {
if (userListArr.hasOwnProperty(key) && userListArr[key].text.toLowerCase().indexOf(filterBy) !== -1) {
return true;
}
}
return false;
}
if (backendInfo.firstName.indexOf(filterBy) !== -1 || backendInfo.lastName.toLowerCase().indexOf(filterBy) !== -1 || backendInfo.countryOrigin.toLowerCase().indexOf(filterBy) !== -1
|| backendInfo.userListMap.indexOf(filterBy) !== -1) {
filteredIndexes.push(index);
}
}
}
This is rendered and the last part is throwing errors if you input something in the table, and a column returns null in the given cell.
The thing is, I can make the code work if I change the last part to ..
try {
if (backendInfo.firstName.indexOf(filterBy) !== -1 || backendInfo.lastName.toLowerCase().indexOf(filterBy) !== -1 || backendInfo.countryOrigin.toLowerCase().indexOf(filterBy) !== -1
|| backendInfo.userListMap.indexOf(filterBy) !== -1) {
filteredIndexes.push(index);
}
}
catch(err) {
console.log('Exception')
}
With the try/catch, it works 100% as intended and handles the indexOf returning null... But this can't be the way to properly handle it - I'm assuming this sort of exception handling is, well, supposed to be for rare exceptions, and shouldn't really be used on the front-end as much as the backend.
How do I handle the error in the title without using try/catch?
You are using indexOf, so make sure the values will not be undefined or null, You can solve it by putting the check on each values like this:
let {firstName, lastName, countryOrigin, userListMap} = backendInfo;
if ((firstName && firstName.indexOf(filterBy) !== -1)
|| (lastName && lastName.toLowerCase().indexOf(filterBy) !== -1)
|| (countryOrigin && countryOrigin.toLowerCase().indexOf(filterBy) !== -1)
|| (userListMap && userListMap.indexOf(filterBy) !== -1)) {
filteredIndexes.push(index);
}
or other way of solving this is, the default values you defined of these variables firstName, lastName, countryOrigin, userListMap, if they are array then it should be [], and if string then it should be ''.
I want to check null and empty id in JavaScript function,but if syntax isn't work ?
var id = "<%=Request["Id"]%>";
if (id !== "")
if (id !== null)
{var id = "<%=new Guid(Request["ID"].ToString())%>";
window.location = "/Controller/Action.aspx?Id=" + id; }
With javascript,
If you are trying to test for not-null (any value that is not explicitly NULL) this should work for you:
if( myVar !== null ) {
// your code
}
If you are only interested to test for not-empty (null value, zero number, empty string etc..) then try:
if( !myVar ) {
// your code
}
If you want to test for if a variable is defined at all (which I believe is what you are trying to achieve) then you can do it like:
if( typeof myVar !== 'undefined' ) {
// your code
}
Please let me know if it works for you.
Read into binary logic:
var id = "<%=Request["Id"]%>";
if (id !== "" && id != null) {
var id = "<%=new Guid(Request["ID"].ToString())%>";
window.location = "/Controller/Action.aspx?Id=" + id;
}
Then again, var id = "<%=Request["Id"]%>"; will never be null, only empty string, so perhaps you can drop that check altogether.
I want to build a IF condition which is built dynamically based on the parameters it gets. More over, this is expected to be built as a plugin.
For instance, there are 3 parameters for student object, called age,name, phone_numbers. Also, there is a option object for selection parameters.
In the condition,
if(student.age >option.age & student.name == option.name & student.phonenumbers == option.phonenumbers ){
// do stuff
}
If any parameter is missing, it should not be included in the condition. For example, assume, in case option.name is undefined, then the if condition should be prepared as following,
if(student.age >option.age & student.phonenumbers == option.phonenumbers ){
// do stuff
}
Moreover, why this kind of thing is required is, here an array of (500 objects) students objects are iterated. The above condition can be splitted into seperat conditions, but then the iteration will be multipled by the number of conditions !!!. So I m looking for a way to add all conditions into one.
However, my approach is, create the expression as a string and then execute it with eval(..),but as far as I know that using eval can lead vulnerabilities.
Any one let me know a way to implement a dynamic conditions.
Note that the JavaScript and operator is &&.
For your example, this should work:
if((!student.age || student.age>option.age) &&
(!student.name || student.name==option.name) &&
(!student.phonenumbers || student.phonenumbers==option.phonenumbers)
) {
}
How about
function testStudent(student,option) {
var res = [];
var test = true;
if (student.age) res.push(student.age > option.age);
if (student.name) res.push(student.name == option.name);
if (student.phonenumbers) res.push(student.phonenumbers == option.phonenumbers);
for (var i=0;i<res.length;i++) {
test = test && res[i];
}
if (res.length > 0 && test) {
//do stuff
}
}
generic:
function testObjects(obj1,obj2) {
for (var o in obj1) { // assuming obj2 is a superset of obj1
if (o === "age" && obj1.age <= obj2.age) return false;
if (obj1.hasOwnProperty(o) && obj1[o] != obj2[o]) return false;
}
return true;
}
var ok = testObjects(student,option);
You can have your conditions in functions and those functions in an Array. so then you can do a loop in the Array and call every function (condition).
var aConds = [];
function firstCond(params) {return (params<0)};
function secondCond(params) {return(params!='hi')};
aConds.push(firstCond);
...
for(var i=0;i<aConds.length;i++)
{
if(!aConds[i](params)) console.log("a condition has not been meet");
}
Would it work to allow undefined in each condition?
if((student.age == undefined || student.age > option.age) && (student.name == undefined || student.name == option.name) ...
Short questioion, I'm trying to understand this tutorial:
http://superdit.com/2011/02/09/jquery-memory-game/
Being new to Javascript I can't seem to find what the statement '== ""' means... I understand "==", but not the empty double quotes.
val == "" is a non-strict comparison to emtpy string. It will evaluate to true if val is empty, 0, false or [] (empty array):
var val = "";
console.log( val == "" ); // true
val = 0;
console.log( val == "" ); // true
val = false;
console.log( val == "" ); // true
val = [];
console.log( val == "" ); // true
You can use === to use strict comparison, fex:
val = 0;
console.log( val === "" ); // false
The ' == "" ' is a check for an empty string. It will be true when the string is empty, and false whenever there are some characters inside it.
A quick scan of the code (ctrl-F is your friend) quickly teaches you that the only time such a statement occurs in the code is here: if (imgopened == ""), another search taught me that imgopened is an evil (global) variable that is initialized to "" at the very top of the script, and every time some action/function is done with whatever value it was assigned.
I suspect it's a sort of card game, where two identical imgs need to be clicked, in which case this var will reference the image currently turned. If it's empty, then all imgs are facing down, and this var is empty: "".In other words:
if (imgopened == "")//=== if no card is turned
{
//do X, most likely: turn card
}
else
{
//do Y
}
This could've been written as
if (!imgopened)
//or
if (imgopened == false)//falsy, but somewhat confusing
//or
if (imgopened == 0)//!confusing, don't use
//or, my personal favorite
if (imgopened === '')
As the title says, I am looking for a way of comparing the Text content of an HTML Element with another HTML Elements's Text content and only if they are identical, alert a message. Any thoughts? Greatly appreciate it!
(Posted with code): For example, I can't equalize the remItem's content with headElms[u]'s content.
else if (obj.type == 'checkbox' && obj.checked == false) {
var subPal = document.getElementById('submissionPanel');
var remItem = obj.parentNode.parentNode.childNodes[1].textContent;
alert("You have disselected "+remItem);
for (var j=0; j < checkSum.length; j++) {
if (remItem == checkSum[j]) {
alert("System found a match: "+checkSum[j]+" and deleted it!");
checkSum.splice(j,1);
} else {
//alert("There were no matches in the search!");
}
}
alert("Next are...");
alert("This is the checkSum: "+checkSum);
alert("Worked!!!");
var headElms = subPal.getElementsByTagName('h3');
alert("We found "+headElms.length+" elements!");
for (var u=0; u < headElms.length; u++){
alert("YES!!");
if (remItem == headElms[u].textContent) {
alert("System found a matching element "+headElms[u].textContent+" and deleted it!");
}
else {
alert("NO!!");
alert("This didn't work!");
}
}
}
var a = document.getElementById('a');
var b = document.getElementById('b');
var tc_a = a ? a.textContent || a.innerText : NaN;
var tc_b = b ? b.textContent || b.innerText : NaN;
if( tc_a === tc_b )
alert( 'equal' );
Using NaN to ensure a false result if one or both elements don't exist.
If you don't like the verbosity of it, or you need to do this more than once, create a function that hides away most of the work.
function equalText(id1, id2) {
var a = document.getElementById(id1);
var b = document.getElementById(id2);
return (a ? a.textContent || a.innerText : NaN) ===
(b ? b.textContent || b.innerText : NaN);
}
Then invoke it...
if( equalText('a','b') )
alert( 'equal' );
To address your updated question, there isn't enough info to be certain of the result, but here are some potential problems...
obj.parentNode.parentNode.childNodes[1] ...may give different element in different browsers
"System found a matching element ... and deleted it!" ...if you're deleting elements, you need to account for it in your u index because when you remove it from the DOM, it will be removed from the NodeList you're iterating. So you'd need to decrement u when removing an element, or just iterate in reverse.
.textContent isn't supported in older versions of IE
Whitespace will be taken into consideration in the comparison. So if there are different leading and trailing spaces, it won't be considered a match.
If you're a jQuery user....
var a = $('#element1').text(),
b = $('#element2').text();
if (a === b) {
alert('equal!');
}
The triple equals is preferred.
To compare two specific elements the following should work:
<div id="e1">Element 1</div>
<div id="e2">Element 2</div>
$(document).ready(function(){
var $e1 = $('#e1'),
$e2 = $('#e2'),
e1text = $e1.text(),
e2text = $e2.text();
if(e1text == e2text) {
alert("The same!!!");
}
});
I will highly recommend using jQuery for this kind of comparison. jQuery is a javascript library that allows you to draw values from between HTML elements.
var x = $('tag1').text();
var y = $('tag2').text();
continue js here
if(x===y){
//do something
}
for a quick intro to jQuery...
First, download the file from jQuery.com and save it into a js file in your js folder.
Then link to the file. I do it this way:
Of course, I assume that you're not doing inline js scripting...it is always recommended too.
A simple getText function is:
var getText = (function() {
var div = document.createElement('div');
if (typeof div.textContent == 'string') {
return function(el) {
return el.textContent;
}
} else if (typeof div.innerText == 'string') {
return function(el) {
return el.innerText;
}
}
}());
To compare the content of two elements:
if (getText(a) == getText(b)) {
// the content is the same
}