logic error in javascript code

dot

I am trying to write some logic that will check for the existence of a specific record in two tables. If the row exists in either table, I want to return TRUE.

For table A, when the record is added to the table, the id field looks like "123". For table B, the same record would have the id of "a123". However, the value i have to search for the record is "row_123".

This is what my code looks like right now :

var checkForDuplicates = function(row_id) {

   return !!($('#existing_members').find('#' + row_id.replace('row_','')).length || $('#selected_users').find('#' + row_id.replace('row_','a').length) );

};

I want the function to return true if the record exists in either table.
However, this statement returns true in cases when it should be false.

What I've tried so Far I've been playing around in the console to make sure that my logic is correct:

!!(1 || 0)  //returns true
!!(0 || 0)  //returns false
!!(0 || 1)  //returns true

I'm also currently reviewing the replace statements to make sure the find() is being supplied the right strings.

But a second pair of eyes to confirm that my logic is correct would be appreciated.

Thanks

EDIT 1

The solution, using Max's suggestion would be:

  var checkForDuplicates = function(row_id) {
             var parts = row_id.split('_');
             var tableB = '#a'+ parts[1];
             var tableA = '#' + parts[1];
             return !!($('#existing_members').find(tableA).length || $('#selected_users').find(tableB).length);
 }

However, as Ankit points out, I just had a typo in my original code. So this would be my final answer / solution:

var checkForDuplicates(row_id) {
       return !!( $('#existing_members').find('#' + row_id.replace('row_', '')).length || $('#selected_users').find('#' + row_id.replace('row_','a')).length);
}
bugwheels94

Your code has a typo at the end of return statement

...'a').length));  //it returns object which always evaluates to true

it should be

...'a')).length);   

DEMO

	var checkforduplicates = function(row_id){
     //row_id looks like "row_123"
	 return !!($('#tableA').find('#' + row_id.replace('row_','')).length || $('#tableB').find('#' + row_id.replace('row_','a')).length );
	
}
alert(checkforduplicates("row_123"));
<table id=tableA><tr><td id="123">123 ID</td></tr></table>
	<table id=tableA><tr><td id="a13">a13 ID</td></tr></table>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related