Search code examples
javascriptjquerydhtml

jQuery enable/disable show/hide button w/ SELECT options. Get remaining option values


I have a select list which is being populated using the values from a text field. I also have two buttons: an add button which adds the entered value to the select list and a remove button which removes the entered value from the select list. I would like to do the following using jQuery:

  1. If the value entered into the text field is NOT AVAILABLE in the select list, show the add button and hide the remove button.
  2. If the value entered into the text field is AVAILABLE in the select list, hide the add button and show the remove button.
  3. If the select list is EMPTY show the add button and hide the remove button.

Here is some code I've come up with:

// Remove selected options
$('#removeButton').click(function() {
   //$.map($('#addedchargeamtid :selected'), function(e) {
   $.map($('#addedchargeamtid option'), function(e) {
      var exp = $(e).text();
      // Would like to have all the Option values in CVS format 0.00,1.99, etc...
      // If removed this should also remove the value in the array
   })

   $('#removeButton').hide();
      return !$('#addedchargeamtid :selected').remove();
   });

   // Add charge amount
   $('#addedchargeamtid option:selected').focus(function() {
      $('#removeButton').show();
   });

It shows the remove button when I add the first value, but if I remove the value the button doesn't show back up.

UPDATE:

Okay I have edited it to this.

$('#removeButton').click(function() {
   $('#addedchargeamtid :selected').remove();

   $.map($('#addedchargeamtid option'), function(e) {
      var exp = $(e).text();
      alert(exp); // Need this in CSV format but I think it displays the correct values
   })

   //if($("#addedchargeamtid option").length > 0) {  <-- Didn't work                
   if($("#addedchargeamtid").length > 0) {
      $('#removeButton').show();
   } else {
      $('#removeButton').hide();
   }
});

still not hiding the button when no value in the SELECT. Tried it with the option as well.


Solution

  • I believe you can check to see if the option length is >0 saying that it has values and if not then it doesn't exist meaning it doesn't have values like so:

    if($("#addedchargeamtid option").length > 0 ) //if addedchargeamtid is the id of select tag
    {
       $('#removeButton').show();
    }
    else
    {
      $('#removeButton').hide();
    }