简体   繁体   中英

Delete a drop down item after selecting another drop down value (Jquery)

I want to delete an item (ItemX) from a drop down menu (Drop Down 2) when ItemX is selected in Drop Down 1 using Jquery.

I am working in a way;

<?php
session_start ();

?>

<!doctype html>
<html lang="en">
 <head>
 <title>Document</title>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

</head>

<body>

<form action = 'testselectprocess.php' method='POST'>

<div>
<select id="cat"></select> <select id="items" disabled></select>
</div>

<script>
$(document).ready(function(){

var c = '<option>Select</option>';
var cat1 = ["Honey", "Tree", "Chocolate"];
for (i=0; i < cat1.length; i++){
 c += '<option>' + cat1[i] + '</options>';
}
$('#cat')
 .html(c)
 .change(function(){
  var indx = this.selectedIndex - 1;
  if (indx < 0) {
   $('#items').empty().attr('disabled','disabled');
   return;
  }
  var item = '<option>Select an item</option>';
  for (i=0; i < cat1.length; i++){
    item += '<option>' + cat1[i] + '</options>';
  }
  $('#items').html(item).removeAttr('disabled');
 });

});

</script>


</form>

 </body>
</html>

There are two drop downs in the above code. In which both have three values Honey , Tree , Chocolate . I need that if a user select Honey from first drop down then Honey should be invisible or delete from second drop down.

You don't do any check and not added the selected value you just copy all items from the first select to the second one.

So the solution is to validate and not copy the the selected item, like this:

<?php

session_start ();

?>

<!doctype html>
<html lang="en">
 <head>
 <title>Document</title>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

</head>

<body>

<form action = 'testselectprocess.php' method='POST'>

<div>
<select id="cat"></select> <select id="items" disabled></select>
</div>

<script>
$(document).ready(function(){

var c = '<option>Select</option>';
var cat1 = ["Honey", "Tree", "Chocolate"];
for (i=0; i < cat1.length; i++){
 c += '<option>' + cat1[i] + '</options>';
}
$('#cat')
 .html(c)
 .change(function(){
  var indx = this.selectedIndex - 1;
  if (indx < 0) {
   $('#items').empty().attr('disabled','disabled');
   return;
  }
  var item = '<option>Select an item</option>';
  for (i=0; i < cat1.length; i++){
    item += indx !== i ? '<option>' + cat1[i] + '</options>' : '';
  }
  $('#items').html(item).removeAttr('disabled');
 });

});

</script>


</form>

 </body>
</html>

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