0

I have found a huge amount of problem-related to my problem. Actually, I have the solution about "without holding Ctrl button to select the option."

For better reference: Selecting multiple from an html select element without using ctrl key

I got the best solution in the following question. But the problem is that I need a function having both 1. without holding the Ctrl button 2. limited the selection option less than 3

Here the code for HTML select element without using ctrl key

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);
    }
}
select{
  width: 200px;
  height: 200px;
}
<select multiple>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
</select>

Here the code for limited the option with holding ctrl button:

$("select").on('change', function(e) {
    if (Object.keys($(this).val()).length > 3) {
        $('option[value="' + $(this).val().toString().split(',')[3] + '"]').prop('selected', false);
    }
});
select{
  width: 200px;
  height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<select multiple>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
</select>

But I can't make the two scripts together. I have tried but there only work only "without holding ctrl" script.

Note: I have found other script in jquery to activate "without holding ctrl" in multi-select option. But they didn't send data correctly. The above pure JS is perfect for me :)

Thanks

Reza Mousavi
  • 4,420
  • 5
  • 31
  • 48

1 Answers1

-1

Your first script allows for multiple selections to be made by clicking without and with CTRL. You don't need to combine anything.

Peter
  • 624
  • 1
  • 8
  • 24
  • But with that script I need to limit the option less than 3. Actually I am trying to build a form where user can select multiple option without holding ctrl but they can select less than 3 option from individual 10 options – MD RIZAUR RAHMAN Oct 01 '18 at 20:29