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>
Related
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>
I have the code for a dynamic dropdown (taken from this website), see below. However, I don't know how to make it generate text after you make the selections. I would like it after I choose my two options for it to have a filler sentence underneath that I can change later ("This is dummy text"). I need the text for each combination to be different text.
Also, if you know how to make my the two selections side-by-side instead of one on top of the other, that would be great, but not needed!
I am trying to create a website and have very minimal experience with HTML, and have been using a lot of code found online. I am knowledgable enough to edit code properly, just not create it. Any help would be amazing! Thank you.
<html>
<head>
<!- This is a comment->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript" type="text/javascript">
function dynamicdropdown(listindex)
{
switch (listindex)
{
case "manual" :
document.getElementById("status").options[0]=new Option("Select status","");
document.getElementById("status").options[1]=new Option("OPEN","open");
document.getElementById("status").options[2]=new Option("DELIVERED","delivered");
break;
case "online" :
document.getElementById("status").options[0]=new Option("Select status","");
document.getElementById("status").options[1]=new Option("OPEN","open");
document.getElementById("status").options[2]=new Option("DELIVERED","delivered");
document.getElementById("status").options[3]=new Option("SHIPPED","shipped");
break;
}
return true;
}
</script>
</head>
<title>Dynamic Drop Down List</title>
<body>
<div class="category_div" id="category_div">Chapter:
<select id="source" name="source" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
<option value="">Select source</option>
<option value="manual">MANUAL</option>
<option value="online">ONLINE</option>
</select>
</div>
<div class="sub_category_div" id="sub_category_div">Lesson:
<script type="text/javascript" language="JavaScript">
document.write('<select name="status" id="status"><option value="">Select status</option></select>')
</script>
<noscript>
<select id="status" name="status">
<option value="open">OPEN</option>
<option value="delivered">DELIVERED</option>
</select>
</noscript>
</div>
</body>
Please checkout this code.
I haven't written the entire code, it would be too long.
Here if you would like to set custom text for each selection please edit the display() function (see the commented line in the javascript).
function dynamicList() {
var chapter = document.getElementById("chapter");
var lesson = document.getElementById("lesson");
switch (chapter.value) {
case "online":
lesson.length = 0;
var option = document.createElement("option");
option.value = "";
option.text = "Select status";
lesson.add(option);
var option = document.createElement("option");
option.value = "open";
option.text = "Open";
lesson.add(option);
option = document.createElement("option");
option.value = "delevered";
option.text = "Delevered";
lesson.add(option);
break;
case "manual":
lesson.length = 0;
var option = document.createElement("option");
option.value = "";
option.text = "Select status";
lesson.add(option);
var option = document.createElement("option");
option.value = "open";
option.text = "Open";
lesson.add(option);
option = document.createElement("option");
option.value = "delevered";
option.text = "Delevered";
lesson.add(option);
option = document.createElement("option");
option.value = "shipped";
option.text = "Shipped";
lesson.add(option);
break;
default:
display();
}
}
function display() {
var chapter = document.getElementById("chapter");
var lesson = document.getElementById("lesson");
var result = document.getElementById("result");
if (chapter.value != "" && lesson.value != "") {
result.innerHTML = "<span class='text'>You have selected " + chapter.value + " and " + lesson.value + "</span>";
} else {
result.innerHTML = "<span class='text'>Please select the both options</span>";
}
//for using custom combination of values use if statement and use the values as condition like this
// if(chapter.value=="online" && lesson.value=="open")
// {
// write the code here (when chapter value=online and lesson value=open)
// }
}
#result
{
margin-top: 15px;
float: left;
color:#0078d7;
}
.categories
{
float: left;
}
<!DOCTYPE html>
<html>
<head>
<title>sample</title>
</head>
<title>Dynamic Drop Down List</title>
<body>
<div class="categories">
Chapter:
<select id="chapter" onchange="dynamicList()" style="margin-right:25px">
<option value="">Select source</option>
<option value="online">Online</option>
<option value="manual">Manual</option>
</select>
lesson:
<select id="lesson" onchange="display()">
<option value="">Select status</option>
</select>
<br>
<div id="result"></div>
</div>
</body>
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>
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
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
}