jQuery & dropdown listbox

Listbox is part of the webform where user can select one or options from a given list. By using jQuery we will try to manage dropdown select box.

We will show some examples here.

Reading selected value or text

For the listbox with id=student
var sel = $("#student").val();
Getting Selected Item (option) text part
var sel = $('#student option:selected').text()

Triggering on change event and reading selected value

<script>
   $(document).ready(function() {
$("#student").change(function(){ // change function of listbox
var sel = $("#student").val(); // reading listbox selection
$("#t1").attr('value',sel); // keeping in a text box
   });
});
</script>
If you have more than one dropdown selection boxes and want to trigger event on selection of any one, then change this line only.
$("#student1,#student2,#student3").change(function(){ 
......
});
student1, student2, student3 are three different list box with different ids

From a group of listbox we can collect id of the selected listbox and the selected value. Here all listbox have common class=my_class.
$(".my_class").change(function(){	// change function of listbox
var var_value = $(this).val();              // reading listbox selection value
var var_id = sel + $(this).attr('id');      // reading id of selected  listbox
});

Submitting form with onChange event of listbox

<form method=GET action=page_name.php>
<select id=dept name=dept class='form-control' onchange='this.form.submit()'>
<option value=''>Select Dept</option>
....
</select></form>
DEMO of on change event and reading selected value
  • Video Tutorial on JQuery Listbox


We can set the default selected value of the listbox by using val(). User can change the option as per requirement. Once such default value is selected we can trigger change option of the list box .
<script>
   $(document).ready(function() {
$("#student").change(function(){ // change function of listbox
var sel = $("#student").val(); // reading listbox selection
$("#t1").attr('value',sel); // keeping in a text box
$("#student2").val(sel); // Change the selection of list box 
   });
});
</script>
DEMO of setting to one selected option

Resetting the select box

We can reset the selection box to first options
$("#student").prop('selectedIndex',0);
DEMO of resetting to first selection option

HTML part of Selection box

Student <select id=student>
<option value='Alex'>Alex</option>
<option value='Raju'>Raju</option>
<option value='Raman'>Raman</option>
</select> <br><br>
<input type=text name=t1 id=t1>

Adding bootstrap design and managing width of listbox

<select name=cat_id id=cat_id class='form-control'>
....
</select>
To adjust width we can change style='width:auto' to match the width to widest option. width='fit' to adjust the width as per current selected option. data-width='100px' to keep the width equal to 100px. data-width='75%' to occupy width to 75% of available width.
<select id=student class='form-control'>
..
</select>


style='width:auto'
<select id=student class='form-control' style='width:auto;'>
..
</select>
style='width:100px;'
<select id=student class='form-control' style='width:100px'>
..
</select>
style='width:75%;'
<select id=student class='form-control' style='width:75%'>
..
</select>

Listbox options by taking data from MySQL table

$sql='select * from student ';
echo "<select id=name name=name class='form-control'>";
foreach ($dbo->query($sql) as $row) {
echo "<option value=$row[id]>$row[name]</option>";
}
echo "</select>";

read more of display or records using PHP PDO

if($stmt = $connection->query("SELECT * from student")){

echo "<select id=name name=name class='form-control'>";
while ($row = $stmt->fetch_assoc()) {
echo "<option value=$row[id]>$row[name]</option>";
}
echo "</select>";
}else{
echo $connection->error;
}
read more of display or records using PHP MySQLi

Enable or disable dropdown listbox

We can disable by changing attr
$('#student1').attr('disabled', true);
We can enable by again changing attr to false
$('#student1').prop('disabled',false);
For a group of listbox
$('#student1,#student2').prop('disabled',false);
Here is a demo script where we have used click event of a set of radio buttons to manage dropdown list box status. The first radio button will disable the first dropdown list box, second one will disable both the listboxes and the third one will enable the both.
DEMO of enable or disable list box with Click event of radio button
  • JQuery Listbox Add Remove options


Adding options to existing list box.

list box id is student and it is already having some options. To add more options we have to use this line .
$("#student").append("<option value=" + to_add +">"+to_add+"</option>");
In the above line to_add is the variable which stores the new option to be added.

We will try to use one text box and user can enter text and add the same as option to our list box.
<script>
   $(document).ready(function() {
     $("#b1").click(function(){
    var to_add = $("#t1").val();
$("#student").append("<option value=" + to_add +">"+to_add+"</option>");
$("#t1").val('');
   });
});
</script>
Add text and submit to enter as option<br><br>
Student <select id=student>
<option value='Alex'>Alex</option>
<option value='Raju'>Raju</option>
</select> <br><br>
<input type=text name=t1 id=t1>
<input type=button name=b1 id=b1 value=Add>
We used click event to the Add button and then stored ( in a variable to_add ) the text entered by user by using val() function. Then we are adding the text as option and text to our student dropdown list.
Adding options to listbox

Removing option from listbox.

User can select one option and then by click of a button the option can be removed from the listbox.

We will first identity the user selection of option and store the value in a variable.
var to_remove = $("#student").val();
Then we will use remove() function to remove the option.
$("#student option[value= '"+ to_remove + "' ]").remove();
Here is the complete code.
<script>
   $(document).ready(function() {
     $("#b1").click(function(){
    var to_remove = $("#student").val();
$("#student option[value= '"+ to_remove + "' ]").remove();
   });
});
</script>
Select One option to remove / add.<br><br>
Student <select id=student>
<option value='Alex'>Alex</option>
<option value='Raju'>Raju</option>
<option value='Rone'>Rone</option>
<option value='Peter'>Peter</option>
</select> 
<input type=button name=b1 id=b1 value=Remove>
Removing options from listbox

Removing all the options

We will modify the above code a little and use the empty() function to remove all the options. Here is the code.
<script>
   $(document).ready(function() {
 $("#b1").click(function(){
	$("#student").empty();
  });
});
</script>
Select One option to remove / add.<br><br>
Student <select id=student>
<option value='Alex'>Alex</option>
<option value='Raju'>Raju</option>
<option value='Rone'>Rone</option>
<option value='Peter'>Peter</option>

</select> 
<input type=button name=b1 id=b1 value='Remove All'>
Removing all the options of a listbox

Multiple selection listbox.

We can add attribute multiple to dropdown listbox so users can select more than one option from the listbox. We will learn how to handle multiple selection using jQuery. For multiple selection user has to click and hold Ctrl key or Shift key.

We will use change function to collect all the selected options from the lsitbox. To store the selected elements we will use one Array variable . By using each function we will loop through all the selected elements and add them to array.
$("#student").change(function(){
//var str = ($("#student").val() || []).join(', ');
var str=new Array();
$("#student option:selected").each(function() {
str.push($(this).val());
});
Finally we will display the elements of the array inside div layer display by using join function.
$("#display1").html(str.join(","));
This how we will display the selected options.

Selecting all the options

We can add one button to select all the available options inside the multiple dropdown box. We will add the following line of code to the click event of the button ( id = b2 )
$("#b2").click(function(){
$('#student option').prop('selected', true);
});
Here we have used prop() function to select all the elements of the listbox.

Submitting a form with multiple selection dropdown listbox.

After submitting a form we will get an array with the selections of the listbox. Here we will change the name of the listbox to student[]. Our new listbox will be like this.
<script>
$(document).ready(function() {
$("#student").change(function(){
//var str = ($("#student").val() || []).join(', '); 
var str=new Array();
$("#student option:selected").each(function() {
  str.push($(this).val());
});

$("#display1").html(str.join(","));
});
////////
$("#b2").click(function(){
$('#student option').prop('selected', true);
});
///////
     });
</script>
Select Multiple options by pressing Ctrl key<br><br>
Selected options will be displayed. <br><br>
<form method=post action=listbox5ck.php>
 <select id=student size=4 multiple name=student[]>
<option value='Alex'>Alex</option>
<option value='Raju'>Raju</option>
<option value='Rone'>Rone</option>
<option value='Peter'>Peter</option>
<option value='Ramu'>Ramu</option>
<option value='John'>John</option>

</select><input type=button name=b2 id=b2 value='Select All'><br> 
<br><br><input type=submit name=b1 id=b1 value='Submit'>
<div id=display1></div>
Now in PHP file we will collect the array and display all the elements.
<?Php
echo "Your selections are here <br><br>";
$str=$_POST['student'];
while (list ($key, $val) = each ($str)) { 
echo "$key -> $val <br>"; 
}
?>

Developing SQL from the array

if( is_array($student) ){
$sql_student='(';
while (list ($key, $val) = each ($student)) {
//echo "$val <br>";
if(strlen($val)>0){
$sql_student = $sql_student."'".$val."'".",";
}
}
$sql_student=substr($sql_student,0,(strLen($sql_student)-1));
$sql_student=$sql_student.")";
$sql_student= " AND my_student_table.student IN $sql_student ";
}
else{$sql_student='';}
Submitting Multiple selection box in a form

Projects using Listbox with jQuery

Using the above concepts we will try to learn some uses by developing projects.


Download Zip file for Listbox Demos
Managing Button Radio button

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    15-09-2020

    This is an amazing tutorial! Thank you very much, it was very beneficial to me.






    Most Popular JQuery Scripts

    1

    Two dependant list boxes

    2

    Calendar with Date Selection

    3

    Data change by Slider

    4

    Show & Hide element


    JQuery Video Tutorials




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer