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

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>

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.

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 to 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

Subscribe to our mailing list

* indicates required
Subscribe to plus2net
Your Rating


Google+

Post Comment This is for short comments only. Use the forum for more discussions.




Subscribe to our mailing list

* indicates required
Subscribe to plus2net



Most Popular JQuery Scripts

1

Two dependant list boxes

2

Calendar with Date Selection

3

Data change by Slider

4

Show & Hide element
HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us
©2000-2017 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer