简体   繁体   中英

Delete option in select box once added to multiple select on button click

I have two select boxes: client and software/hardware , and a multiple select selectpname where the selected product from software/hardware is placed. software/hardware would be populated by data from the db according to the selected client. I want to avoid having the same product added to selectpname so I tried removing the selected option but I can't seem to make it work. These are the codes that I've tried:

$("#selectBox option[value='#selectBox option:selected']").remove(); //trial 1
$("#selectpname option[value='foo']").remove();                      //trial 2
$("#selectpname option:selected").remove();                          //trial 3
$("#selectpname option:selected").each(function () {                 //trial 4
        $(this).remove();
    }
});

I added the above to the add button:

var num = 1;
function addonprodlist(str, num, location, toFocusDom)
{
    if(str != "")
    {
        if (num == 1) { $("#"+location).append('<option value="' + str + '">' + str + '</option>'); }
        $("#"+toFocusDom).val("");
        $("#"+toFocusDom).focus();
        if (location=='txtsofthard'){
            //code here             
        }
    }               
};

JQUERY: (disables/enables the select box)

//change in #txtclient will trigger this
$(document).on('change','#txtclient', function() {
    var client = $(this).val();
    if(client != "") {
      $.ajax({
        type: "POST",
        url: "components/comp_include/mainclass.php",
        data: "client=" + client + "&form=chained",
        success:function(response) {
          if(response != '') {
            $("#selectpname").removeAttr('disabled','disabled').html(response);
            //alert(response);
          } 
          else {
            $("#selectpname").attr('disabled','disabled').html("<option value=''>SELECT PRODUCT</option>");
          }
        }
      });
    } 
    else {
      $("#selectpname").attr('disabled','disabled').html("<option value=''>SELECT PRODUCT</option>");
    }

    //other code here       
});

PHP: (populates the dropdown menu)

case 'chained':
    if (isset($_POST['client'])) {              
        $qry = //query here
        $res = mysql_query($qry);

        if(mysql_num_rows($res) > 0) {
            $items = [];

            //get all items from database and explode the concat values.
            while($row = mysql_fetch_array($res)) {
                $items = array_merge($items, explode('|', $row[2]));
            }

            //get only the distinct items.
            $items = array_unique($items);

            //remove the emtpy items.
            $items = array_filter($items);

            //initialize the list.
            $list = '<option value="">SELECT PRODUCT</option>';

            //create the list of unique items.
            foreach ($items as $item) {
                $list .= '<option value="'.$item.'">'.$item.'</option>';
            }

            echo $list;
        }
        else if ($_POST['client'] == "SELECT CLIENT") {
            //do nothing / menu would be disabled
        }
        else {
            echo '<option value="">NO RECORD FOUND!</option>';
        }
    } 
break;

HTML:

<select list="pnamelist" name="selectpname" id="selectpname" style="width:345px; height: 30px; overflow: scroll;" disabled="disabled">
    <option>SELECT PRODUCT</option>
</select>
<div class="btn btn-primary btn-small" onclick="addonprodlist($('#selectpname').val(), 1, 'txtsofthard', 'selectpname');" ><center>Add</center></div>

<br>
<select multiple="multiple" id="txtsofthard" name="txtsofthard" onclick='deleteThisSelectedvalue(this.id);' ></select>

How can I go about this?

I can not point out the exact error in your code.

But you should try not to rely on the "selected" option of an element through your code. Like here:

$("#selectpname option:selected").remove(); 

A better solution would be to get all needed information from the selected item after the click on the button and then use this information in your code. Because the selected item could change between your click on the button and the point where your code reaches the delete command.

Also try not to use onClick in your html code, the better solution would be to register a event to the element.

So here is a small working example with an registered onClick event to the button that reads all data from the selected product in your list and passes this data to the functions who do all needed functionality:

 // adds an pruduct to the 'txtsofthard' select box function addProduct(selectedProductValue, selectedProductName) { $("#txtsofthard").append('<option value="' + selectedProductValue + '">' + selectedProductName + '</option>'); } // removes a product from the 'selectpname' select box function removeProdFromSource(selectedProductValue) { $("#selectpname option[value='"+selectedProductValue+"']").remove(); } // registers a onClick event to the button $('#btnAddProduct').on("click", function() { //get the selected item from the 'selectpname' select box var selectedProductValue = $('#selectpname').val(); //check if a valid product was selected if( selectedProductValue === "SELECT PRODUCT" ) { //do nothing if no product was selected but the button was clicked return; } // get the displayed name of the selected product var selectedProductName = $("#selectpname option[value='"+selectedProductValue+"']").text(); // add the selected product to the 'txtsofthard' select box addProduct(selectedProductValue, selectedProductName); // remove the selected prudct from the 'selectpname' select box removeProdFromSource(selectedProductValue); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="selectpname"> <option>SELECT PRODUCT</option> <option value="product1">Product 1</option> <option value="product2">Product 2</option> <option value="product3">Product 3</option> <option value="product4">Product 4</option> </select> <button id="btnAddProduct">Add</button> <br> <select multiple="multiple" id="txtsofthard" name="txtsofthard"></select> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM