jquery - Remove / disable selected option[selected from first dropdown] from second dropdown on clicking add button php

930

index.php

<?php
//index.php

$connect = new PDO("mysql:host=localhost;dbname=test", "root", "");
function fill_unit_select_box($connect)
{ 
 $output = '';
 $query = "SELECT * FROM tbl_unit ORDER BY unit_name ASC";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
 $output .= '<option value="'.$row["unit_name"].'">'.$row["unit_name"].'</option>';
 }
 return $output;
}

?>
<!DOCTYPE html>
<html>
 <head>
 <title>Add Remove Select Box Fields Dynamically using jQuery Ajax in PHP</title>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
 <br />
 <div >
  <h3 align="center">Add Remove Select Box Fields Dynamically using jQuery Ajax in PHP</h3>
  <br />
  <h4 align="center">Enter Item Details</h4>
  <br />
  <form method="post" id="insert_form">
  <div >
   <span id="error"></span>
   <table id="item_table">
   <tr>
    <th>Enter Item Name</th>
    <th>Enter Quantity</th>
    <th>Select Unit</th>
    <th><button type="button" name="add" ><span ></span></button></th>
   </tr>
   </table>
   <div align="center">
   <input type="submit" name="submit" value="Insert" />
   </div>
  </div>
  </form>
 </div>
 </body>
</html>

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

 $(document).on('click', '.add', function(){
 var html = '';
 html += '<tr>';
 html += '<td><input type="text" name="item_name[]" /></td>';
 html += '<td><input type="text" name="item_quantity[]" /></td>';
 html += '<td><select name="item_unit[]" ><option value="">Select Unit</option><?php echo fill_unit_select_box($connect); ?></select></td>';
 html += '<td><button type="button" name="remove" ><span ></span></button></td></tr>';
 $('#item_table').append(html);
 });

 $(document).on('click', '.remove', function(){
 $(this).closest('tr').remove();
 });

 $('#insert_form').on('submit', function(event){
 event.preventDefault();
 var error = '';
 $('.item_name').each(function(){
  var count = 1;
  if($(this).val() == '')
  {
  error += "<p>Enter Item Name at "+count+" Row</p>";
  return false;
  }
  count = count + 1;
 });

 $('.item_quantity').each(function(){
  var count = 1;
  if($(this).val() == '')
  {
  error += "<p>Enter Item Quantity at "+count+" Row</p>";
  return false;
  }
  count = count + 1;
 });

 $('.item_unit').each(function(){
  var count = 1;
  if($(this).val() == '')
  {
  error += "<p>Select Unit at "+count+" Row</p>";
  return false;
  }
  count = count + 1;
 });
 var form_data = $(this).serialize();
 if(error == '')
 {
  $.ajax({
  url:"insert.php",
  method:"POST",
  data:form_data,
  success:function(data)
  {
   if(data == 'ok')
   {
   $('#item_table').find("tr:gt(0)").remove();
   $('#error').html('<div >Item Details Saved</div>');
   }
  }
  });
 }
 else
 {
  $('#error').html('<div >'+error+'</div>');
 }
 });

});
</script>

insert.php

<?php
//insert.php;

if(isset($_POST["item_name"]))
{
 $connect = new PDO("mysql:host=localhost;dbname=test", "root", "");
 $order_id = uniqid();
 for($count = 0; $count < count($_POST["item_name"]); $count++)
 {  
  $query = "INSERT INTO tbl_order_items 
  (order_id, item_name, item_quantity, item_unit) 
  VALUES (:order_id, :item_name, :item_quantity, :item_unit)
  ";
  $statement = $connect->prepare($query);
  $statement->execute(
   array(
    ':order_id'   => $order_id,
    ':item_name'  => $_POST["item_name"][$count], 
    ':item_quantity' => $_POST["item_quantity"][$count], 
    ':item_unit'  => $_POST["item_unit"][$count]
   )
  );
 }
 $result = $statement->fetchAll();
 if(isset($result))
 {
  echo 'ok';
 }
}
?>

This picture shows the output of the code

What I need is:

I don't want to showbags option selected in the first row inside theSelect Unit dropdown of the second row.

That is, I want the user to select only one option from theSelect Unit dropdown. The selection of the same option from theSelect unit dropdown must be restricted.

449

Answer

Solution:

Have a look at jquery fiddle link: https://jsfiddle.net/fyxog73t/3/

HTML Code:

<div >
 <div >1st Row</div>
 <div >
  <select id="select_1">
   <option value="">Choose</option>
   <option value="a">A</option>
   <option value="b">B</option>
   <option value="c">C</option>
   <option value="d">D</option>
   <option value="e">E</option>
  </select>
 </div>
</div>
<div >
 <div >2st Row</div>
 <div >
  <select id="select_2">
   <option value="">Choose</option>
   <option value="a">A</option>
   <option value="b">B</option>
   <option value="c">C</option>
   <option value="d">D</option>
   <option value="e">E</option>
  </select>
 </div>
</div>
<div >
 <div >3st Row</div>
 <div >
  <select id="select_3">
   <option value="">Choose</option>
   <option value="a">A</option>
   <option value="b">B</option>
   <option value="c">C</option>
   <option value="d">D</option>
   <option value="e">E</option>
  </select>
 </div>
</div>

JS Code:

$(document).on('change', '[id^="select_"]', function(){
    var dropdown_value = $(this).val();
    var dropdown_id = $(this).attr('id');
  // code to update options from other dropdowns excluding currently selected dropdown
    if(dropdown_value != "") {
    $('[id^="select_"]:not([id="'+dropdown_id+'"])').find("option[value='"+dropdown_value+"']").attr('disabled', true);
    }

  // code to check, if any disabled option is present with it's value not present in other dropdown as selected option. If so then removing disabled option for that dropdown
    $('[id^="select_"]:not([id="'+dropdown_id+'"])').find("option[value!='"+dropdown_value+"']:disabled").each(function(){
        dropdown_value = $(this).val();
        dropdown_id = $(this).parent().attr('id');

    if($('[id^="select_"]:not([id="'+dropdown_id+'"])').find("option[value='"+dropdown_value+"']:selected").length == 0) {
            $(this).removeAttr('disabled');
        }
    });
});

Had used below steps to achieve the required output:

1) On change method written for each dropdown.
2) In that on change method, disabling other dropdown's option whose value is same as selected option from current dropdown.
3) Then checked, is their any disabled option in other dropdown's(excluding currently selected dropdown). Checking whether that disabled value is present as selected value in other dropdown's or not. If not selected then remove it's disabled attribute.

People are also looking for solutions to the problem: php - A data breach on a site exposed your password message sent by chrome on my login form

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.