Select multiple options without ctrl click | How to avoid the need for ctrl-click in a multi-select box using Javascript or jQyery?

Select multiple options without ctrl click | How to avoid the need for ctrl-click in a multi-select box using JavaScript or jQuery?

In this post we are learning about how to select multiple options without ctrl Key.

Select multiple options without ctrl click


Select multiple options without ctrl click Using jQuery

Html Code

<select>
  <option>Aman</option>
  <option>Raman</option>
  <option>Radhka</option>
</select>

jQuery Code 

jQuery('option').mousedown(function(e) {
    e.preventDefault();
    jQuery(this).toggleClass('selected');
  
    jQuery(this).prop('selected', !jQuery(this).prop('selected'));
    return false;
});


Select multiple options without ctrl click Using JavaScript

HTML Code:

<h4>From</h4>

<div>
    <select name="sites-list" size="7" multiple>
        <option value="site-1">SITE-One</option>
        <option value="site-2" selected>SITE-Two</option>
        <option value="site-3">SITE-Three</option>
        <option value="site-4">SITE-four</option>
        <option value="site-5">SITE-Five</option>
        <option value="site-6" selected>SITE-Six</option>
        <option value="site-7">SITE-Seven</option>
        <option value="site-8">SITE-Eight</option>
        <option value="site-9">SITE-Nine</option>
</div> 


JavaScript code :

window.onmousedown = function (e) {

    var el = e.target;

    if (el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple')) {

        e.preventDefault();

        // toggle selection

        if (el.hasAttribute('selected')) el.removeAttribute('selected');

        else el.setAttribute('selected', '');

        // hack to correct buggy behavior

        var select = el.parentNode.cloneNode(true);

        el.parentNode.parentNode.replaceChild(select, el.parentNode);

    }

}

Previous
Next Post »

Please do not entering spam link in the comment box ConversionConversion EmoticonEmoticon