Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: do something if select element exists

Hey, I looked around on Stack Overflow and tried a few other people's attempts at this, and I just couldn't get this to work.

I have a select element like this:

<select id="slct_firstCat" name="slct_firstCat" size="15">
</select>

This only shows once a specfic AJAX request has completed, so this select element is NOT loaded with the original page's DOM, it is loaded as a seperate AJAX request after the main page has loaded.

I basically want to do this...

if (/* select element exists */) {
  // Then change the colour of a div to green
} else {
  // Change the colour to red
}

But remember, this has to work after the page has loaded. I can click the select to run the JS function if needed.

I tried this code below, but couldn't get it to work:

if ($(".element1").length > 0 || $(".element2").length > 0 {
  // code
}

So basically, if the select element exists, then change the tab colour to green, else change it to red.


1 Answers

You have to put your code in jQuery.ajax()'s success callback. And the > 0 part isn't needed in $('.element1').length > 0, since—unlike in Ruby—, 0 and "" are also falsy in JavaScript.

jQuery.ajax({
    url: 'example.php',
    success: function () {    
        if ($('#slct_firstCat').length) {
            $('#myDiv').css('color', 'green');
        } else {
            $('#myDiv').css('color', 'red');
        }
});

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!