views:

43

answers:

3

I'm using 1 js for 2 different pages. 1 page doesn't have a div which the other does. So when I submit the values, I get a $( js error

for

$('.description'+save_id+'').html(description_val).show(); //update category description

I suspect that I get the error because there is nothing to show(). Is there a short code I can use to detect if the div.description exists otherwise don't do the function?

+2  A: 

jQuery will not error if it has nothing to perform on. The show() would not be a problem. To answer your question, though, you can check the length property on the jQuery object returned from $.

icktoofay
In other words: `if ($('.description'+save_id).length === 0) { ... }`
strager
How would I check the length? But, `.description'+save_id+` in the js is for a div `.description14 or .description12.. etc` which doesn't exist on the page. While show() isn't the issue, do you think it's the div?
Cyber Junkie
@Cyber Junkie, What problem are you experiencing? You're being unclear. `.show()` and `.html()` work even if no element is selected by `$(...)`; they just do nothing.
strager
Sorry. I have a div `.description` in my html and the javascript picks up its value, puts it in an text input and on submit it returns the divs html using show(). On a different page I don't have the .description div or input so I get the `$(` errors, I think because there's no `.description` in the HTML. So how can I disable this line.. `$('.description'+save_id+'').html(description_val).show();` if there is no .description div and input. I have different pages which use some functions from the js file and others that don't. So I don't want to create separate js for each page.
Cyber Junkie
A: 

From what you posted I'd check to make sure the variables you're using are all defined at this stage. To check for existence you can do this:

if ($('.description' + save_id).size() > 0) {
  // code here that operates on the div.
}

This is essentially just a syntactic alternative to checking the length property.

g.d.d.c
A: 

If the description_val variable is undefined, then the code will fail.

Try using an if() statement to only run the code if description_val is not undefined.

if(description_val) {
    $('.description'+save_id+'').html(description_val).show();
}

Or if for some reason the value of description_val may be a value that would equate to false, then do this:

if(description_val !== undefined) {
    $('.description'+save_id+'').html(description_val).show();
}
patrick dw
Thanks patrick that works!
Cyber Junkie
@Cyber - You're welcome. :o)
patrick dw