Manipulate two selects on page load with jQuery



Let’s say the following is our first select −

<select name="all_name" id="all_present_name">    <option value="John">John</option>    <option value="David">David</option>    <option value="Bob">Bob</option>    <option value="Mike">Mike</option>    <option value="Sam">Sam</option>    <option value="Carol">Carol</option> </select>

Following is our second select −

<select name="common_name" id="remaining_name">    <option value="David">David</option>    <option value="Mike">Mike</option>    <option value="Carol">Carol</option> </select>

We need to remove the options in the first select, which are similar to options in the second select. For this, use val(). Following is the complete code −

Example

 Live Demo

<!DOCTYPE html> <html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Document</title> </head> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <body>    <select name="all_name" id="all_present_name">       <option value="John">John</option>       <option value="David">David</option>       <option value="Bob">Bob</option>       <option value="Mike">Mike</option>       <option value="Sam">Sam</option>       <option value="Carol">Carol</option>    </select>    <select name="common_name" id="remaining_name">       <option value="David">David</option>       <option value="Mike">Mike</option>       <option value="Carol">Carol</option>    </select> </body> <script>    $('#remaining_name > option').each(function (i, el) {       var value = $(el).val();       $('#all_present_name > option[value="' + value + '"]').remove();    }); </script> </html>

Output

The output is as follows −

Updated on: 2020-10-01T13:20:39+05:30

482 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements