HTML Multiselect Limit - html

Is it possible to set limit to multipleselect?
Below is an example code where user can select more than 1 value.
<select multiple="multiple" name="choose">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
<option value="4">Value 4</option>
<option value="5">Value 5</option>
<option value="6">Value 6</option>
</select>
But, how to limit user to select not more than 3 value.
Any idea?

You can use jQuery
$("select").change(function () {
if($("select option:selected").length > 3) {
//your code here
}
});

You would do this via javascript on the client side, and then add a check on the server side as well in case the client has disabled javascript.
Here is some basic client side code to give you an idea:
<html>
<body>
<form onsubmit="validate()">
<select multiple="multiple" id="choose" name="choose">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
<option value="4">Value 4</option>
<option value="5">Value 5</option>
<option value="6">Value 6</option>
</select><br>
<input type="submit">
</form>
<script>
function validate()
{
var selectChoose = document.getElementById('choose');
var maxOptions = 2;
var optionCount = 0;
for (var i = 0; i < selectChoose.length; i++) {
if (selectChoose[i].selected) {
optionCount++;
if (optionCount > maxOptions) {
alert("validation failed, not submitting")
return false;
}
}
}
return true;
}
</script>
</body>
</html>

Script that will disallow more than 3 elements to be selected (as opposed to just validating it at submit time).
http://jsfiddle.net/v33sszgp/
var verified = [];
document.querySelector('select').onchange = function(e) {
if (this.querySelectorAll('option:checked').length <= 3) {
verified = Array.apply(null, this.querySelectorAll('option:checked'));
} else {
Array.apply(null, this.querySelectorAll('option')).forEach(function(e) {
e.selected = verified.indexOf(e) > -1;
});
}
}
Note there's some additional complexity related to preventing the item from actually being selected on the select and that it rather validates a user's actions and reverts it if it's invalid.

RedFilter has the right idea with validating by javascript. Haven't tested, but you could do something like:
var options = document.all.tags("option");
var selectedCounter = 0;
for (var i=0; i < options.length; i++) {
if (options[i].selected) {
selectedCounter++;
}
checkCounter();
}
function checkCounter() {
//disable all options here
}

Related

Matching two ID attributes from cloned dependent dropdown list

In this code I have 2 dependent dropdown lists and a button to duplicate/clone the form. The color selection changes based on what is selected in item. When I duplicate the dropdown list the function didn't work. I tried changing the id of the duplicated dropdown list but still can't manage to match the id of 2 dropdown list. Is there any solution? Thanks.
var count = 1;
var duplicate_div = document.getElementById('duplicate_1');
function addRecord() {
var clone = duplicate_div.cloneNode(true);
clone.id = "duplicate_" + ++count;
duplicate_div.parentNode.append(clone);
var cloneNode = document.getElementById(clone.id).children[0];
$(clone).find("*[id]").each(function() {
$(this).val('');
var tID = $(this).attr("id");
var idArray = tID.split("_");
var idArrayLength = idArray.length;
var newId = tID.replace(idArray[idArrayLength - 1], count);
$(this).attr('id', newId);
});
}
$(document).ready(function() {
$("#item_" + count).change(function() {
var val = $(this).val();
if (val == "shirt") {
$("#color_" + count).html("<option>Black</option> <option>Gray</option>");
} else if (val == "pants") {
$("#color_" + count).html("<option>Blue</option> <option>Brown</option>");
} else if (val == "shoe") {
$("#color_" + count).html("<option>White</option> <option>Red</option>");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="select-form">
<div class="duplicate" id="duplicate_1">
<br>
<label>item</label>
<select id="item_1">
<option value="template" disabled selected></option>
<option value="shirt">Shirt</option>
<option value="pants">Pants</option>
<option value="shoe">Shoe</option>
</select>
<label>color</label>
<select id="color_1">
<option disabled selected>Select item first</option>
</select>
</div>
</form>
<br><br>
<button type="button" id="add-button" onclick="addRecord()">add</button>
Since you've imported jQuery into the project, I suggest you fully use it.
It's recommended to use jQuery's .on method instead of onclick attribute.
The change event will not work on the dynamically created elements.
You should instead use "event delegation".
Last but not least, you can remove the ids if they serve as selectors. You can use jQuery to easily transverse the DOM
Try this
$(document).ready(function() {
var $cloned = $('.duplicate').first().clone(true);
var $container = $('.select-form');
$('#add-button').click(function() {
$container.append($cloned.clone());
})
$('.select-form').on('change', '.item', function() {
var val = $(this).val();
var $color = $(this).closest('.duplicate').find('.color');
if (val == "shirt") {
$color.html("<option>Black</option> <option>Gray</option>");
} else if (val == "pants") {
$color.html("<option>Blue</option> <option>Brown</option>");
} else if (val == "shoe") {
$color.html("<option>White</option> <option>Red</option>");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="select-form">
<div class="duplicate">
<br>
<label>item</label>
<select class="item">
<option value="template" disabled selected></option>
<option value="shirt">Shirt</option>
<option value="pants">Pants</option>
<option value="shoe">Shoe</option>
</select>
<label>color</label>
<select class="color">
<option disabled selected>Select item first</option>
</select>
</div>
</form>
<br><br>
<button type="button" id="add-button">add</button>

Jquery check if multiple drop down list has any selected option

I am trying to display in console a message when a user removes all options from a multiple drop down list. My current code creates a JSON object when there are options selected and encodes the items into a URI string component.
How can I display a message when the user removes all selected options?
<div class="form-group row">
<label class="col-sm-3 col-form-label">Customer</label>
<div class="col-sm-9">
<select id="Customers" class="js-select2-custom custom-select" name="CustomerID" multiple size="1" style="opacity: 0;" asp-for="CustomerID" onchange="getSelects()"
data-hs-select2-options='{
"minimumResultsForSearch": "Infinity"
}'>
#{
var selectedCustomer = Model.CustomerList.Where(x => Model.SelectedCustomers.Any(c => c.CustomerID == x.CustomerID));
var Customers = Model.CustomerList.Where(x => !Model.SelectedCustomers.Any(c => c.CustomerID == x.CustomerID));
}
#foreach (var item in selectedCustomer)
{
<option value="#item.CustomerID" selected>#item.CustomerName</option>
}
#foreach (var item in Customers)
{
<option value="#item.CustomerID">#item.CustomerName</option>
}
</select>
</div>
</div>
function getSelects() {
$('#selectedText').val('');
var items = $("#Customers > option:selected").map(function () {
var opt = {};
$('#Customers > option:selected').each(function() {
if ($(this).not(':selected')) {
alert('Yes')
}
});
return opt;
}).get();
$('#selectedText').val(encodeURIComponent(JSON.stringify(items)));
console.log($('#selectedText').val());
}
How about something like this? Press and hold the "Ctrl" key to select/deselect multiple:
$('#cars').change(function(){
// get selected values:
var values = $(this).val();
console.log('selected values: ', values);
// send alert if none are selected:
if (!values.length) alert('No values selected!');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="cars">Choose a car:</label>
<select name="cars" id="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>

jQuery if in array but exclude some string

I have six option values from database table similar to this: #blog and #hariciURL and #portfolio blah blah blah similar like this.
I have another table have that values, I check if same values in the array that option value will be disabled but except #hariciURL option value never disable.
How can I exclude #hariciURL not disabled from this option menu?
please check codes you can understand what I mean.
sorry, my bad English.
$().ready(function() {
$('#degeriAL option').each(function() { // option menüsündeki tüm değerleri al
//console.log(BolumleriAl);
var BolumleriAl = $(this).val(); // tüm valuelerini bir değişkene ata
var seolink = ("#services", "#hariciURL");
//var seolink = "<?php echo $BolumVarmiSorgula->seolink;?>"; // this original code come from database.
console.log(seolink);
var bolumisimleri = $('#degeriAL option[name]');
var exclude = "#hariciURL"; //this will be never disabled
if ($.inArray(seolink, BolumleriAl) && BolumleriAl !== exclude) { // iki dizi içinde eşleşen varmı diye bak
$('#degeriAL option[value="' + seolink + '"]').prop("disabled", true).addClass("secimMenusuDisabled").addClass(".secimMenusuDisabled" + "(bölüm mevcut)").nextAll(); //option menüdeki dizi içinde olan tüm değerlerini veritabanından gelenlerle karşılaştır ve eşleşenleri option menü içinden disabled yap
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="degeriAL" name="bolumLink" class="form-control form-control-sm" required="">
<option value="" required="">Bölüm Seçiniz...</option>
<option value="#featured-services"> Diğer Hizmetler </option>
<option value="#about"> Hakkımızda </option>
<option value="#services"> Hizmetler </option>
<option value="#call-to-action"> Tıklama Eylemi </option>
<option value="#blog"> Blog </option>
<option value="#skills"> Yatay İstatistik Çizelgesi </option>
<option value="#facts"> Rakamsal İstatistik </option>
<option value="#portfolio"> Ürünler </option>
<option value="#clients"> Referansların Logoları </option>
<option value="#testimonials"> Müşteri Görüşleri </option>
<option value="#team"> Bizim Takım & Çalışanlar </option>
<option value="#contact"> İletişim / Form / Harita </option>
<option value="#hariciURL"> Harici Link </option>
</select>
$('#degeriAL option').each(function() {
var BolumleriAl = $(this).val();
var seolink = "<?php echo $BolumVarmiSorgula->seolink;?>";
var bolumisimleri = $('#degeriAL option[name]');
var Exclude = "#hariciURL"; //this will be never disabled
if (jQuery.inArray(seolink, BolumleriAl)) {
$('#degeriAL option[value="' + seolink + '"]').prop("disabled", true).addClass("secimMenusuDisabled").addClass(".secimMenusuDisabled" + "(that already exist, you can not add more than one)").nextAll();
}
});
What you most likely want is
since the seolinks seems to be a string, you need to split it so that it becomes an array.
check that the BolumleriAl is not the same as the Exclude
if they are different then check if it is found in the seolinks array and if so then disable it
you are already iterating over the option elements so no need to use a selector to find the element to disable. Just use this.
$('#degeriAL option').each(function() {
var BolumleriAl = $(this).val();
var seolink = "<?php echo $BolumVarmiSorgula->seolink;?>".split(' ');
var Exclude = "#hariciURL"; //this will be never disabled
if (BolumleriAl !== Exclude && $.inArray(BolumleriAl, seolink) > -1) {
$(this).prop("disabled", true)
.addClass("secimMenusuDisabled")
//.addClass(".secimMenusuDisabled" + "(that already exist, you can not add more than one)");
}
});
According to what I understoud from your question, I think your if condition was inverted.
Also, you should use the value given by $.each function
var seolink = "<?php echo $BolumVarmiSorgula->seolink;?>";
var Exclude = "#hariciURL"; //this will be never disabled
$('#degeriAL option').each(function(i,v) {
Exclude = v != Exclude && $.inArray(seolink, v) ? $('#degeriAL option[value="' + seolink + '"]').prop("disabled", true).addClass("secimMenusuDisabled").text('that already exist, you can not add more than one') : "#hariciURL";
});
You are looping through the options, so you can just check if the option value, BolumleriAl, is not the excluded one.
Also, You can move the variables seolink and Exclude out of the loop, as these do change not every time.
var seolink = "https://example.com";
var Exclude = "#hariciURL"; //this will be never disabled
var Bölümler = ['test3', 'test7'];
$('#degereriAL').children('option').each(function() {
var currentValue = $(this).val();
if (currentValue == Exclude || $.inArray(currentValue, Bölümler) > -1) {
// The value is excluded (#hariciURL)
// OR the value is in the Bölümler array
} else {
$(this)
.prop("disabled", true)
.addClass("secimMenusuDisabled");
}
});
select {
min-width: 10em;
}
select option[disabled] {
color: #eee;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="degereriAL" size="8">
<option value="https://example.com">Test</option>
<option value="#hariciURL">Test 2</option>
<option value="test3">Test 3</option>
<option value="test4">Test 4</option>
<option value="test5">Test 5</option>
<option value="test6">Test 6</option>
<option value="test7">Test 7</option>
<option value="test8">Test 8</option>
</select>

Get value from dropdownlist and create another dropdown list

I have created a dropdownlist and it looks like this
<select id="mySelect">
<option value="one">Do one</option>
<option value="two">Do two</option>
</select>
Firstly I would like NOT to have a submit button. The second thing I was searching is that when I select the first choice to appear another dropdown list and when i choose the second to appear a text input for the user to type something. Thank you and sorry for the English!
If you do not want to import any jQuery you can still do it with pure JavaScript.
Here is a demo
Just include the below script in your file as,
function myFun(){
var val = document.getElementById("mySelect");
var input = document.getElementById("myIn");
var sel = document.getElementById("myOtherSelect");
var sub = document.getElementById("mySubmit");
if(val.value == "one"){
sel.style.display = "block";
input.style.display = "none";
sub.style.display = "none";
}else if(val.value == "two"){
input.style.display = "block";
sub.style.display = "block";
sel.style.display = "none";
}else{
input.style.display = "none";
sub.style.display = "block";
sel.style.display = "none";
}
}
Now add the onchange event on your select as,
<select id="mySelect" onchange="myFun()">
<option value="emp" selected>Choose something</option>
<option value="one">Do one</option>
<option value="two">Do two</option>
</select>
<select id="myOtherSelect">
<option value="three">Do three</option>
<option value="four">Do four</option>
</select>
<input type="text" id="myIn">
<input type="submit" id="mySubmit">
Use jQuery to do something simple like:
$('#mySelect').on('change', function() {
$('#input').html('<input name="myname" value="'+this.value +'">');
})
JSFiddle

HTML Selection script between two droplists

I have two droplist in html built using tag.
<select name="List1" id="List1" onclick="GetVal()">
<option value="1" selected="selected">Mercurio</option>
<option value="2">Venus</option>
<option value="3">Tierra</option>
<option value="4">Marte</option>
</select>
<select name="List2" id="List2">
<option value="1" selected="selected">Hg</option>
<option value="2">Ve</option>
<option value="3">Ti</option>
<option value="4">Ma</option>
</select>
I have written a script such as the selection of an element from List2 relies on the selection of the corresponding element of List1.
<script language="javascript" type="text/javascript">
// <!CDATA[
function GetVal() {
var LSelect1 = document.getElementById('List1');
var LSelect2 = document.getElementById('List2');
switch (LSelect1.selectedIndex)
{
case 1:
LSelect2.selectedIndex = 1;
break;
case 2:
LSelect2.selectedIndex = 2;
break;
case 3:
LSelect2.selectedIndex = 3;
break;
default:
LSelect2.selectedIndex = 4;
}
}
// ]]>
</script>
However, the function works wrongly for the first element of the List1. Why?
selectedIndex is 0-based. A simpler way to do things might be like this:
<script language="javascript" type="text/javascript">
// <!CDATA[
function GetVal() {
var LSelect1 = document.getElementById('List1');
var LSelect2 = document.getElementById('List2');
LSelect2.selectedIndex = LSelect1.selectedIndex;
}
// ]]>
</script>