JQuery: do something if select element exists

Hey, I looked back at Qaru and tried several other attempts at this, and I just couldn't get it to work.

I have a select element like this:

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

This is displayed only after the completion of the specified AJAX request, therefore this selection element is NOT loaded by the DOM source page, it is loaded as a separate AJAX request after loading the main page.

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 that this should work after the page has loaded. I can press the select button to launch the JS function, if necessary.

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

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

So, if the select element exists, change the color of the tab to green, otherwise change it to red.

+3
4

jQuery.ajax() . > 0 $('.element1').length > 0, Ruby, 0 "" falsy JavaScript.

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

if- ajax-,

$.ajax({
  url: "test.html",
  context: document.body,
  success: function(){
   if ($(".element1").length > 0 || $(".element2").length > 0 {
  ...stuff...
}
  }
});
+1

You can try using something like:

 if ($('select#slct_firstCat').length) {
    // ... stufff....
  }
+1
source

You have to change colors when your events happen, i.e. when your ajax call succeeds, fires, or when you fire another event. In any case, you can use this code, this is not the best way to do this, but is suitable for your needs:

$(document).ready(function(){
  setInterval(function(){
      if($("#slct_firstCat").size() > 0)
          $("#divColour").css("backgroundColor", "green");
      else
          $("#divColour").css("backgroundColor", "red");
  }, 100);
});
0
source

All Articles