Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Select / Unselect" multiple select fields

Tags:

jquery

I have a multiple select fields defined in a table column,

<table border=1>
    <tr>
        <td>THIS IS THE PLACE TO SELECT THE PROJECTS</td>
    </tr>
    <tr>
    <td id="select_project">
      <select class="projects" id="projects" multiple="multiple" name="projects[]" size="10">
       <option value="1">Project 1</option> 
       <option value="2" selected="selected">project 2</option> 
       <option value="3">Project 3</option>
     </select>
   CLICK HERE SHOULD "UNSELECT"
</td>
</tr>
</table>

I would like to have the feature that when user click on the space of the column besides the selection field, all selected options should back to unselected status, I have used the following jquery to implement,

$("#select_project").bind('click', function(){
    $('#projects option').attr('selected', false);
    return false;
});

It works but it also affect the selection field, that's when user select a option, it immediately change back to unselected status automatically, how to get rid of this?

like image 437
Mellon Avatar asked Jan 26 '11 10:01

Mellon


3 Answers

Well yeah, you binded event to the whole table cell, where select box and text are, so it affects both of them. Fixed code:

<table border=1>
    <tr>
        <td>THIS IS THE PLACE TO SELECT THE PROJECTS</td>
    </tr>
    <tr>
    <td id="select_project">
      <select class="projects" id="projects" multiple="multiple" name="projects[]" size="10">
       <option value="1">Project 1</option> 
       <option value="2" selected="selected">project 2</option> 
       <option value="3">Project 3</option>
     </select>
   <a href="#" id="unselect">CLICK HERE SHOULD "UNSELECT"</a>
</td>
</tr>
</table>

$("#unselect").bind('click', function(){
    $('#projects option:selected').removeAttr("selected");;
    return false;
});
like image 120
usoban Avatar answered Oct 13 '22 13:10

usoban


Yes of course it will clear the selected value immediately after the user has selected something from the drop down list.

You've placed the <select> inside the area that is affected by the .click() function. So whenever the user clicks on the drop down list to choose something, your function is run - and the selection is cleared.

You have to change the UI so that the place to click to clear the selection is somewhere else.

like image 26
JK. Avatar answered Oct 13 '22 13:10

JK.


In Drupal 7 you need to have write following in order to make unselect two other selectboxes names edit-tid-3 and edit-tid-4 when you click on first select box ( edit-tid-2)

jQuery("#edit-tid-2").bind('click', function(){
                jQuery('#edit-tid-3 option:selected').removeAttr("selected");
                        jQuery('#edit-tid-4 option:selected').removeAttr("selected");
                        return false;
    });
like image 1
drupalchamp Avatar answered Oct 13 '22 14:10

drupalchamp