This question already has answers here:
How can you programmatically tell an HTML SELECT to drop down (for example, due to mouseover)?
(16 answers)
Closed 3 years ago.
Is it possible to use JavaScript to open an HTML select to show its option list?
Unfortunately there's a simple answer to this question, and it's "No"
I had this problem...and found a workable solution.
I didn't want the select box to show until the user clicked on some plain HTML. So I overlayed the select element with opacity=.01. Upon clicking, I changed it back to opacity=100. This allowed me to hide the select, and when the user clicked the text the select appeared with the options showing.
I use this... but it requires the user to click on the select box...
Here are the 2 javascript functions
function expand(obj)
{
obj.size = 5;
}
function unexpand(obj)
{
obj.size = 1;
}
then i create the select box
<select id="test" multiple="multiple" name="foo" onFocus="expand(this)" onBlur="unexpand(this)">
<option >option1</option>
<option >option2</option>
<option >option3</option>
<option >option4</option>
<option >option5</option>
</select>
I know this code is a little late, but i hope it helps someone who had the same problem as me.
ps/fyi
i have not tested the code above (i create my select box dynamically), and the code i did write was only tested in FireFox.
This works on Google Chrome
dropDown = function (elementId) {
var dropdown = document.getElementById(elementId);
try {
showDropdown(dropdown);
} catch(e) {
}
return false;
};
showDropdown = function (element) {
var event;
event = document.createEvent('MouseEvents');
event.initMouseEvent('mousedown', true, true, window);
element.dispatchEvent(event);
};
After trying to solve this issue for some time, I managed to come with a working solution that is also valid:
var event = new MouseEvent('mousedown');
element.dispatchEvent(event);
I've tried to implement this in Jquery as well, using trigger and mousedown or only mousedown but with no success.
This is very late, but I thought it could be useful to someone should they reference this question. I beleive the below JS will do what is asked.
<script>
$(document).ready(function()
{
document.getElementById('select').size=3;
});
</script>
I'm fairly certain the answer is: No. You can select options with JavaScript but not open the select. You'd have to use a custom solution.
The solution I present is safe, simple and compatible with Internet Explorer, FireFox and Chrome.
This approach is new and complete. I not found nothing equal to that solution on the internet. Is simple, cross-browser (Internet Explorer, Chrome and Firefox), preserves the layout, use the select itself and is easy to use.
Note: JQuery is required.
HTML CODE
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CustonSelect</title>
<script type="text/javascript" src="./jquery-1.3.2.js"></script>
<script type="text/javascript" src="./CustomSelect.js"></script>
</head>
<div id="testDiv"></div>
<body>
<table>
<tr>
<td>
<select id="Select0" >
<option value="0000">0000</option>
<option value="0001">0001</option>
<option value="0002">0002</option>
<option value="0003">0003</option>
<option value="0004">0004</option>
<option value="0005">0005</option>
<option value="0006">0006</option>
<option value="0007">0007</option>
<option value="0008">0008</option>
<option value="0009">0009</option>
<option value="0010">0010</option>
<option value="0011">0011</option>
<option value="0012">0012</option>
<option value="0013">0013</option>
<option value="0014">0014</option>
<option value="0015">0015</option>
<option value="0016">0016</option>
<option value="0017">0017</option>
<option value="0018">0018</option>
<option value="0019">0019</option>
<option value="0020">0020</option>
<option value="0021">0021</option>
<option value="0022">0022</option>
<option value="0023">0023</option>
<option value="0024">0024</option>
<option value="0025">0025</option>
<option value="0026">0026</option>
<option value="0027">0027</option>
<option value="0028">0028</option>
<option value="0029">0029</option>
<option value="0030">0030</option>
<option value="0031">0031</option>
<option value="0032">0032</option>
<option value="0033">0033</option>
<option value="0034">0034</option>
<option value="0035">0035</option>
<option value="0036">0036</option>
<option value="0037">0037</option>
<option value="0038">0038</option>
<option value="0039">0039</option>
<option value="0040">0040</option>
</select>
</td>
</tr>
<tr>
<td>
<select id="Select1" >
<option value="0000">0000</option>
<option value="0001">0001</option>
<option value="0002">0002</option>
<option value="0003">0003</option>
<option value="0004">0004</option>
<option value="0005">0005</option>
<option value="0006">0006</option>
<option value="0007">0007</option>
<option value="0008">0008</option>
<option value="0009">0009</option>
<option value="0010">0010</option>
<option value="0011">0011</option>
<option value="0012">0012</option>
<option value="0013">0013</option>
<option value="0014">0014</option>
<option value="0015">0015</option>
<option value="0016">0016</option>
<option value="0017">0017</option>
<option value="0018">0018</option>
<option value="0019">0019</option>
<option value="0020">0020</option>
<option value="0021">0021</option>
<option value="0022">0022</option>
<option value="0023">0023</option>
<option value="0024">0024</option>
<option value="0025">0025</option>
<option value="0026">0026</option>
<option value="0027">0027</option>
<option value="0028">0028</option>
<option value="0029">0029</option>
<option value="0030">0030</option>
<option value="0031">0031</option>
<option value="0032">0032</option>
<option value="0033">0033</option>
<option value="0034">0034</option>
<option value="0035">0035</option>
<option value="0036">0036</option>
<option value="0037">0037</option>
<option value="0038">0038</option>
<option value="0039">0039</option>
<option value="0040">0040</option>
</select>
</td>
</tr>
<tr>
<td>
<select id="Select2" >
<option value="0000">0000</option>
<option value="0001">0001</option>
<option value="0002">0002</option>
<option value="0003">0003</option>
<option value="0004">0004</option>
<option value="0005">0005</option>
<option value="0006">0006</option>
<option value="0007">0007</option>
<option value="0008">0008</option>
<option value="0009">0009</option>
<option value="0010">0010</option>
<option value="0011">0011</option>
<option value="0012">0012</option>
<option value="0013">0013</option>
<option value="0014">0014</option>
<option value="0015">0015</option>
<option value="0016">0016</option>
<option value="0017">0017</option>
<option value="0018">0018</option>
<option value="0019">0019</option>
<option value="0020">0020</option>
<option value="0021">0021</option>
<option value="0022">0022</option>
<option value="0023">0023</option>
<option value="0024">0024</option>
<option value="0025">0025</option>
<option value="0026">0026</option>
<option value="0027">0027</option>
<option value="0028">0028</option>
<option value="0029">0029</option>
<option value="0030">0030</option>
<option value="0031">0031</option>
<option value="0032">0032</option>
<option value="0033">0033</option>
<option value="0034">0034</option>
<option value="0035">0035</option>
<option value="0036">0036</option>
<option value="0037">0037</option>
<option value="0038">0038</option>
<option value="0039">0039</option>
<option value="0040">0040</option>
</select>
</td>
</tr>
<tr>
<td>
<select id="Select3" >
<option value="0000">0000</option>
<option value="0001">0001</option>
<option value="0002">0002</option>
<option value="0003">0003</option>
<option value="0004">0004</option>
<option value="0005">0005</option>
<option value="0006">0006</option>
<option value="0007">0007</option>
<option value="0008">0008</option>
<option value="0009">0009</option>
<option value="0010">0010</option>
<option value="0011">0011</option>
<option value="0012">0012</option>
<option value="0013">0013</option>
<option value="0014">0014</option>
<option value="0015">0015</option>
<option value="0016">0016</option>
<option value="0017">0017</option>
<option value="0018">0018</option>
<option value="0019">0019</option>
<option value="0020">0020</option>
<option value="0021">0021</option>
<option value="0022">0022</option>
<option value="0023">0023</option>
<option value="0024">0024</option>
<option value="0025">0025</option>
<option value="0026">0026</option>
<option value="0027">0027</option>
<option value="0028">0028</option>
<option value="0029">0029</option>
<option value="0030">0030</option>
<option value="0031">0031</option>
<option value="0032">0032</option>
<option value="0033">0033</option>
<option value="0034">0034</option>
<option value="0035">0035</option>
<option value="0036">0036</option>
<option value="0037">0037</option>
<option value="0038">0038</option>
<option value="0039">0039</option>
<option value="0040">0040</option>
</select>
</td>
</tr>
<tr>
<td>
<select id="Select4" >
<option value="0000">0000</option>
<option value="0001">0001</option>
<option value="0002">0002</option>
<option value="0003">0003</option>
<option value="0004">0004</option>
<option value="0005">0005</option>
<option value="0006">0006</option>
<option value="0007">0007</option>
<option value="0008">0008</option>
<option value="0009">0009</option>
<option value="0010">0010</option>
<option value="0011">0011</option>
<option value="0012">0012</option>
<option value="0013">0013</option>
<option value="0014">0014</option>
<option value="0015">0015</option>
<option value="0016">0016</option>
<option value="0017">0017</option>
<option value="0018">0018</option>
<option value="0019">0019</option>
<option value="0020">0020</option>
<option value="0021">0021</option>
<option value="0022">0022</option>
<option value="0023">0023</option>
<option value="0024">0024</option>
<option value="0025">0025</option>
<option value="0026">0026</option>
<option value="0027">0027</option>
<option value="0028">0028</option>
<option value="0029">0029</option>
<option value="0030">0030</option>
<option value="0031">0031</option>
<option value="0032">0032</option>
<option value="0033">0033</option>
<option value="0034">0034</option>
<option value="0035">0035</option>
<option value="0036">0036</option>
<option value="0037">0037</option>
<option value="0038">0038</option>
<option value="0039">0039</option>
<option value="0040">0040</option>
</select>
</td>
</tr>
</table>
<input type="button" id="Button0" value="MoveLayout!"/>
</body>
</html>
JAVASCRIPT CODE
var customSelectFields = new Array();
// Note: The list of selects to be modified! By Questor
customSelectFields[0] = "Select0";
customSelectFields[1] = "Select1";
customSelectFields[2] = "Select2";
customSelectFields[3] = "Select3";
customSelectFields[4] = "Select4";
$(document).ready(function()
{
//Note: To debug! By Questor
$("#Button0").click(function(event){ AddTestDiv(); });
StartUpCustomSelect(null);
});
//Note: To test! By Questor
function AddTestDiv()
{
$("#testDiv").append("<div style=\"width:100px;height:100px;\"></div>");
}
//Note: Startup selects customization scheme! By Questor
function StartUpCustomSelect(what)
{
for (i = 0; i < customSelectFields.length; i++)
{
$("#" + customSelectFields[i] + "").click(function(event){ UpCustomSelect(this); });
$("#" + customSelectFields[i] + "").wrap("<div id=\"selectDiv_" + customSelectFields[i] + "\" onmouseover=\"BlockCustomSelectAgain();\" status=\"CLOSED\"></div>").parent().after("<div id=\"coverSelectDiv_" + customSelectFields[i] + "\" onclick=\"UpOrDownCustomSelect(this);\" onmouseover=\"BlockCustomSelectAgain();\"></div>");
//Note: Avoid breaking the layout when the CSS is modified from "position" to "absolute" on the select! By Questor
$("#" + customSelectFields[i] + "").parent().css({'width': $("#" + customSelectFields[i] + "")[0].offsetWidth + 'px', 'height': $("#" + customSelectFields[i] + "")[0].offsetHeight + 'px'});
BlockCustomSelect($("#" + customSelectFields[i] + ""));
}
}
//Note: Repositions the div that covers the select using the "onmouseover" event so
//Note: if element on the screen move the div always stand over it (recalculate! By Questor
function BlockCustomSelectAgain(what)
{
for (i = 0; i < customSelectFields.length; i++)
{
if($("#" + customSelectFields[i] + "").parent().attr("status") == "CLOSED")
{
BlockCustomSelect($("#" + customSelectFields[i] + ""));
}
}
}
//Note: Does not allow the select to be clicked or clickable! By Questor
function BlockCustomSelect(what)
{
var coverSelectDiv = $(what).parent().next();
//Note: Ensures the integrity of the div style! By Questor
$(coverSelectDiv).removeAttr('style');
//Note: To resolve compatibility issues! By Questor
var backgroundValue = "";
var filerValue = "";
if(navigator.appName == "Microsoft Internet Explorer")
{
backgroundValue = 'url(fakeimage)';
filerValue = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=\'scale\', src=\'fakeimage\' )';
}
//Note: To debug! By Questor
//'border': '5px #000 solid',
$(coverSelectDiv).css({
'position': 'absolute',
'top': $(what).offset().top + 'px',
'left': $(what).offset().left + 'px',
'width': $(what)[0].offsetWidth + 'px',
'height': $(what)[0].offsetHeight + 'px',
'background': backgroundValue,
'-moz-background-size':'cover',
'-webkit-background-size':'cover',
'background-size':'cover',
'filer': filerValue
});
}
//Note: Allow the select to be clicked or clickable! By Questor
function ReleaseCustomSelect(what)
{
var coverSelectDiv = $(what).parent().next();
$(coverSelectDiv).removeAttr('style');
$(coverSelectDiv).css({'display': 'none'});
}
//Note: Open the select! By Questor
function DownCustomSelect(what)
{
//Note: Avoid breaking the layout. Avoid that select events be overwritten by the others! By Questor
$(what).css({
'position': 'absolute',
'z-index': '100'
});
//Note: Open dropdown! By Questor
$(what).attr("size","10");
ReleaseCustomSelect(what);
//Note: Avoids the side-effect of the select loses focus.! By Questor
$(what).focus();
//Note: Allows you to select elements using the enter key when the select is on focus! By Questor
$(what).keyup(function(e){
if(e.keyCode == 13)
{
UpCustomSelect(what);
}
});
//Note: Closes the select when loses focus! By Questor
$(what).blur(function(e){
UpCustomSelect(what);
});
$(what).parent().attr("status", "OPENED");
}
//Note: Close the select! By Questor
function UpCustomSelect(what)
{
$(what).css("position","static");
//Note: Close dropdown! By Questor
$(what).attr("size","1");
BlockCustomSelect(what);
$(what).parent().attr("status", "CLOSED");
}
//Note: Closes or opens the select depending on the current status! By Questor
function UpOrDownCustomSelect(what)
{
var customizedSelect = $($(what).prev().children()[0]);
if($(what).prev().attr("status") == "CLOSED")
{
DownCustomSelect(customizedSelect);
}
else if($(what).prev().attr("status") == "OPENED")
{
UpCustomSelect(customizedSelect);
}
}
<select id="myDropDown">
<option>html5</option>
<option>javascript</option>
<option>jquery</option>
<option>css</option>
<option>sencha</option>
</select>
By jQuery:
var myDropDown=$("#myDropDown");
var length = $('#myDropDown> option').length;
//open dropdown
myDropDown.attr('size',length);
//close dropdown
myDropDown.attr('size',0);
By javascript:
var myDropDown=document.getElementById("myDropDown");
var length = myDropDown.options.length;
//open dropdown
myDropDown.size = length;
//close dropdown
myDropDown.size = 0;
Copied from:
Open close select
//use jquery
$select.trigger('mousedown')
Related
I am using PHP to show years between 1940 and the current year and using a foreach loop to render each option inside a select element. Everything works as planned until I add an id to the select element that a block of jquery looks at for changes.
Essentially I am trying to console.log (for now) the value of whatever option gets selected but something about my jQuery/PHP is stopping the select from displaying the selected option. The console.log works as expected but the selected option doesn't update in the element. It always goes back to displaying the default option aka 2018 since it's the current year.
If I change the PHP foreach select/option to a static dropdown of plain HTML it works fine. Likewise, if I disconnect the jQuery but keep the PHP dynamically generated option list it works fine. Something about the combo of my PHP+jQuery is preventing the select from updating and I cannot figure what.
Here is my HTML/PHP code:
<select name="birthyear" id="birthyear">
<?php
// $years is setting the range from current year to 1940
$years = range(date('Y'), 1940);
foreach ($years as $year) {
echo "<option id='$year' value='$year'>".$year."</option>";
}
?>
</select>
Here is my jQuery:
$('#birthyear').on('change', function() {
var date = new Date();
var year = date.getFullYear();
var yearsOld = year - $(this).val();
console.log(yearsOld + " years old.");
if (yearsOld >= 18) {
console.log("age >= 18")
} else {
console.log("You aren't old enough!");
}
});
Am I missing something here?
Your code works fine... All I did was execute the PHP to get the HTML and then plugged it into JSFiddle.
I'd assume your problem is that you didn't properly include jQuery.
<select name="birthyear" id="birthyear">
<option id='2018' value='2018'>2018</option>
<option id='2017' value='2017'>2017</option>
<option id='2016' value='2016'>2016</option>
<option id='2015' value='2015'>2015</option>
<option id='2014' value='2014'>2014</option>
<option id='2013' value='2013'>2013</option>
<option id='2012' value='2012'>2012</option>
<option id='2011' value='2011'>2011</option>
<option id='2010' value='2010'>2010</option>
<option id='2009' value='2009'>2009</option>
<option id='2008' value='2008'>2008</option>
<option id='2007' value='2007'>2007</option>
<option id='2006' value='2006'>2006</option>
<option id='2005' value='2005'>2005</option>
<option id='2004' value='2004'>2004</option>
<option id='2003' value='2003'>2003</option>
<option id='2002' value='2002'>2002</option>
<option id='2001' value='2001'>2001</option>
<option id='2000' value='2000'>2000</option>
<option id='1999' value='1999'>1999</option>
<option id='1998' value='1998'>1998</option>
<option id='1997' value='1997'>1997</option>
<option id='1996' value='1996'>1996</option>
<option id='1995' value='1995'>1995</option>
<option id='1994' value='1994'>1994</option>
<option id='1993' value='1993'>1993</option>
<option id='1992' value='1992'>1992</option>
<option id='1991' value='1991'>1991</option>
<option id='1990' value='1990'>1990</option>
<option id='1989' value='1989'>1989</option>
<option id='1988' value='1988'>1988</option>
<option id='1987' value='1987'>1987</option>
<option id='1986' value='1986'>1986</option>
<option id='1985' value='1985'>1985</option>
<option id='1984' value='1984'>1984</option>
<option id='1983' value='1983'>1983</option>
<option id='1982' value='1982'>1982</option>
<option id='1981' value='1981'>1981</option>
<option id='1980' value='1980'>1980</option>
<option id='1979' value='1979'>1979</option>
<option id='1978' value='1978'>1978</option>
<option id='1977' value='1977'>1977</option>
<option id='1976' value='1976'>1976</option>
<option id='1975' value='1975'>1975</option>
<option id='1974' value='1974'>1974</option>
<option id='1973' value='1973'>1973</option>
<option id='1972' value='1972'>1972</option>
<option id='1971' value='1971'>1971</option>
<option id='1970' value='1970'>1970</option>
<option id='1969' value='1969'>1969</option>
<option id='1968' value='1968'>1968</option>
<option id='1967' value='1967'>1967</option>
<option id='1966' value='1966'>1966</option>
<option id='1965' value='1965'>1965</option>
<option id='1964' value='1964'>1964</option>
<option id='1963' value='1963'>1963</option>
<option id='1962' value='1962'>1962</option>
<option id='1961' value='1961'>1961</option>
<option id='1960' value='1960'>1960</option>
<option id='1959' value='1959'>1959</option>
<option id='1958' value='1958'>1958</option>
<option id='1957' value='1957'>1957</option>
<option id='1956' value='1956'>1956</option>
<option id='1955' value='1955'>1955</option>
<option id='1954' value='1954'>1954</option>
<option id='1953' value='1953'>1953</option>
<option id='1952' value='1952'>1952</option>
<option id='1951' value='1951'>1951</option>
<option id='1950' value='1950'>1950</option>
<option id='1949' value='1949'>1949</option>
<option id='1948' value='1948'>1948</option>
<option id='1947' value='1947'>1947</option>
<option id='1946' value='1946'>1946</option>
<option id='1945' value='1945'>1945</option>
<option id='1944' value='1944'>1944</option>
<option id='1943' value='1943'>1943</option>
<option id='1942' value='1942'>1942</option>
<option id='1941' value='1941'>1941</option>
<option id='1940' value='1940'>1940</option>
</select>
https://jsfiddle.net/gpfh150g/
I have a dropdown with names of Surah from Quran, How can i pass value of dropdown to function
$.getJSON("http://api.globalquran.com/surah/2/quran-simple?key=api_key&jsoncallback=?", {
...
})
In the above URL 2 should change based one the value of drop-down
jsBin
$.ajaxSetup({
cache: true,
jsonpCallback: 'quranData'
}); // define ajax setup
$.getJSON("http://api.globalquran.com/surah/2/quran-simple?key=api_key&jsoncallback=?", {
format: "jsonp"
}, function(data) {
$.each(data.quran, function(i, by) {
$.each(by, function(verseNo, line) {
// $("<p>").html('('+ line.surah+':'+line.ayah+') '+line.verse).appendTo("#demo-1");
$("<span>").html(line.verse + ' (' + line.surah + ':' + line.ayah + ') ').appendTo("#demo-1");
});
});
});
#demo-1 {
color: black;
font-size: 28px;
direction: rtl;
max-width: 50%;
padding: 30px;
margin: 0 auto;
text-align: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="customSurah" id="surah" name="surah">
<option value="1">Al-Faatiha</option>
<option value="2">Al-Baqara</option>
<option value="3">Aal-i-Imraan</option>
<option value="4">An-Nisaa</option>
<option value="5">Al-Maaida</option>
<option value="6">Al-An'aam</option>
<option value="7">Al-A'raaf</option>
<option value="8">Al-Anfaal</option>
<option value="9">At-Tawba</option>
<option value="10">Yunus</option>
<option value="11">Hud</option>
<option value="12">Yusuf</option>
<option value="13">Ar-Ra'd</option>
<option value="14">Ibrahim</option>
<option value="15">Al-Hijr</option>
<option value="16">An-Nahl</option>
<option value="17">Al-Israa</option>
<option value="18">Al-Kahf</option>
<option value="19">Maryam</option>
<option value="20">Taa-Haa</option>
<option value="21">Al-Anbiyaa</option>
<option value="22">Al-Hajj</option>
<option value="23">Al-Muminoon</option>
<option value="24">An-Noor</option>
<option value="25">Al-Furqaan</option>
<option value="26">Ash-Shu'araa</option>
<option value="27">An-Naml</option>
<option value="28">Al-Qasas</option>
<option value="29">Al-Ankaboot</option>
<option value="30">Ar-Room</option>
<option value="31">Luqman</option>
<option value="32">As-Sajda</option>
<option value="33">Al-Ahzaab</option>
<option value="34">Saba</option>
<option value="35">Faatir</option>
<option value="36">Yaseen</option>
<option value="37">As-Saaffaat</option>
<option value="38">Saad</option>
<option value="39">Az-Zumar</option>
<option value="40">Al-Ghaafir</option>
<option value="41">Fussilat</option>
<option value="42">Ash-Shura</option>
<option value="43">Az-Zukhruf</option>
<option value="44">Ad-Dukhaan</option>
<option value="45">Al-Jaathiya</option>
<option value="46">Al-Ahqaf</option>
<option value="47">Muhammad</option>
<option value="48">Al-Fath</option>
<option value="49">Al-Hujuraat</option>
<option value="50">Qaaf</option>
<option value="51">Adh-Dhaariyat</option>
<option value="52">At-Tur</option>
<option value="53">An-Najm</option>
<option value="54">Al-Qamar</option>
<option value="55">Ar-Rahmaan</option>
<option value="56">Al-Waaqia</option>
<option value="57">Al-Hadid</option>
<option value="58">Al-Mujaadila</option>
<option value="59">Al-Hashr</option>
<option value="60">Al-Mumtahana</option>
<option value="61">As-Saff</option>
<option value="62">Al-Jumu'a</option>
<option value="63">Al-Munaafiqoon</option>
<option value="64">At-Taghaabun</option>
<option value="65">At-Talaaq</option>
<option value="66">At-Tahrim</option>
<option value="67">Al-Mulk</option>
<option value="68">Al-Qalam</option>
<option value="69">Al-Haaqqa</option>
<option value="70">Al-Ma'aarij</option>
<option value="71">Nooh</option>
<option value="72">Al-Jinn</option>
<option value="73">Al-Muzzammil</option>
<option value="74">Al-Muddaththir</option>
<option value="75">Al-Qiyaama</option>
<option value="76">Al-Insaan</option>
<option value="77">Al-Mursalaat</option>
<option value="78">An-Naba</option>
<option value="79">An-Naazi'aat</option>
<option value="80">Abasa</option>
<option value="81">At-Takwir</option>
<option value="82">Al-Infitaar</option>
<option value="83">Al-Mutaffifin</option>
<option value="84">Al-Inshiqaaq</option>
<option value="85">Al-Burooj</option>
<option value="86">At-Taariq</option>
<option value="87">Al-A'laa</option>
<option value="88">Al-Ghaashiya</option>
<option value="89">Al-Fajr</option>
<option value="90">Al-Balad</option>
<option value="91">Ash-Shams</option>
<option value="92">Al-Lail</option>
<option value="93">Ad-Dhuhaa</option>
<option value="94">Ash-Sharh</option>
<option value="95">At-Tin</option>
<option value="96">Al-Alaq</option>
<option value="97">Al-Qadr</option>
<option value="98">Al-Bayyina</option>
<option value="99">Az-Zalzala</option>
<option value="100">Al-Aadiyaat</option>
<option value="101">Al-Qaari'a</option>
<option value="102">At-Takaathur</option>
<option value="103">Al-Asr</option>
<option value="104">Al-Humaza</option>
<option value="105">Al-Fil</option>
<option value="106">Quraish</option>
<option value="107">Al-Maa'un</option>
<option value="108">Al-Kawthar</option>
<option value="109">Al-Kaafiroon</option>
<option value="110">An-Nasr</option>
<option value="111">Al-Masad</option>
<option value="112">Al-Ikhlaas</option>
<option value="113">Al-Falaq</option>
<option value="114">An-Naas</option>
</select>
<div id="demo-1">
</div>
You will have to create a change function and put all fetching code in it.
JSFiddle
Get selected value:
$("#surah").on("change", function() {
$.getJSON("https://api.globalquran.com/surah/" + $(this).val() + "/quran-simple?key=api_key&jsoncallback=?", {
Change content when you change it:
<select class="customSurah" id="surah" name="surah" onchange="DataByParam($('#surah option:selected').text())">
Do a function fo get the data:
function DataByParam(id){
$.ajaxSetup({ cache: true, jsonpCallback: 'quranData' }); // define ajax setup
$.getJSON("http://api.globalquran.com/" + id + "/2/quran-simple?key=api_key&jsoncallback=?", {
format : "jsonp"
}, function(data)
{
$.each(data.quran, function(i, by)
{
$.each(by, function (verseNo, line) {
// $("<p>").html('('+ line.surah+':'+line.ayah+') '+line.verse).appendTo("#demo-1");
$("<span>").html(line.verse + ' (' +line.surah + ':' + line.ayah + ') ').appendTo("#demo-1");
});
});
});
}
pastebin:
http://jsbin.com/fogoduzore/1/edit?html,output
$.getJSON("http://api.globalquran.com/" +
$("#surah option:selected").text() +
"/2/quran-simple?key=api_key&jsoncallback=?", {
format : "jsonp"
},
or anything from Get selected text from a drop-down list (select box) using jQuery
You need to concatenate the value of dropdwon in url. Try this
"http://api.globalquran.com/surah/"+$("#surah").val()+"/quran-simple"
I have two drop down list "optionone" and "optiontwo" and I want to change the default selected value from "option value=3>3" to option value=3 selected>3 when 2 is selected from my first dropdown list ("optionone")
<script>
function myFunction() {
var mylist = document.getElementById("optionone");
var myvalue = mylist.options[mylist.selectedIndex].value
if (myvalue == 2) {
//do stuff
document.getElementById("optiontwo")
//Change <option value=3>3 to <option value=3 selected>3
}
}
</script>
My drop down list
<select name="optionone" onchange="myFunction()">
<option value=1>1
<option value=2>2
<option value=3>3
<option value=4>4
<option value=5>5
<option value=6>6
</select>
<select name="optiontwo">
<option value=1>1
<option value=2>2
<option value=3>3
<option value=4>4
<option value=5>5
<option value=6>6
</select>
Which I want to change to the following when 2 is select from my first drop down list (optionone)
<select name="optiontwo">
<option value=1>1
<option value=2>2
<option value=3 selected>3
<option value=4>4
<option value=5>5
<option value=6>6
</select>
I'm a bit stuck
You have a invalid markup, <option> must be closed
There is no id attribute for second select input
You can set the value attribute instead of finding the option value using index.
value should be wrapped in quote
Instead of playing with selected attribute, setting the value will make option selected.
Instead of inline-event-binding, use addEventListener
/*
function myFunction(elem) {
document.getElementById("optiontwo").value = elem.value;
}
*/
document.getElementById('optionone').addEventListener('change', function() {
document.getElementById("optiontwo").value = this.value;
});
<select name="optionone" id="optionone" onchange="myFunction(this)">
<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>
</select>
<select name="optiontwo" id='optiontwo'>
<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>
</select>
Thanks to the above I adapted Rayon's script to update as I wanted, as follows
<script>
document.getElementById('optionone').addEventListener('change', function() {
if (this.value == 2){
document.getElementById("optiontwo").value = 3;
}
});
</script>
remove onChange="" from html
And update you code or markup like this ..
<select name="optionone" id="optionone">
<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>
</select>
<select name="optiontwo" id='optiontwo'>
<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>
</select>
and then add this javascript code
document.getElementById('optionone').addEventListener('change',
function() {
if(this.value == 2){
document.getElementById("optiontwo").value = 3;
}
});
and your problem will solve
Here is my HTMl select menu:
<select name="shipping_city" id="shipping-city-select" title="">
<option value="">Изберете град</option>
<option city_en="Aytos" value="1">гр. Айтос</option>
<option city_en="Burgas" value="2">гр. Бургас</option>
<option city_en="Asenovgrad" value="3">гр. Асеновград</option>
<option city_en="Blagoevgrad" value="4">гр. Благоевград</option>
<option city_en="Botevgrad" value="5">гр. Ботевград</option>
<option city_en="Byala Rusensko" value="6">гр. Бяла, Русенско</option>
<option city_en="Varna" value="7">гр. Варна</option>
<option city_en="Veliko Tyrnovo" value="8">гр. Велико Търново</option>
<option city_en="Vidin" value="9">гр. Видин</option>
<option city_en="Vratsa" value="10">гр. Враца</option>
<option city_en="Gabrovo" value="11">гр. Габрово</option>
<option city_en="Gorna Oryahovitsa" value="12">гр. Горна Оряховица</option>
<option city_en="Devnya" value="13">гр. Девня</option>
<option city_en="Dryanovo" value="14">гр. Дряново</option>
<option city_en="Dobrich" value="15">гр. Добрич</option>
<option city_en="Dupnitsa" value="16">гр. Дупница</option>
<option city_en="Ihtiman" value="17">гр. Ихтиман</option>
<option city_en="Kazanlyk" value="18">гр. Казанлък</option>
<option city_en="Karlovo" value="19">гр. Карлово</option>
<option city_en="Karnobat" value="20">гр. Карнобат</option>
<option city_en="Kostenets" value="21">гр. Костенец</option>
<option city_en="Kyustendil" value="22">гр. Кюстендил</option>
<option city_en="Kyrdzhali" value="23">гр. Кърджали</option>
<option city_en="Lovech" value="24">гр. Ловеч</option>
<option city_en="Lom" value="25">гр. Лом</option>
<option city_en="Montana" value="26">гр. Монтана</option>
<option city_en="Nova Zagora" value="27">гр. Нова Загора</option>
<option city_en="Pazardzhik" value="29">гр. Пазарджик</option>
<option city_en="Pernik" value="30">гр. Перник</option>
<option city_en="Petrich" value="31">гр. Петрич</option>
<option city_en="Pleven" value="32">гр. Плевен</option>
<option city_en="Plovdiv" value="33">гр. Пловдив</option>
<option city_en="Razgrad" value="34">гр. Разград</option>
<option city_en="Ruse" value="35">гр. Русе</option>
<option city_en="Sandanski" value="36">гр. Сандански</option>
<option city_en="Sevlievo" value="38">гр. Севлиево</option>
<option city_en="Sliven" value="39">гр. Сливен</option>
<option city_en="Sopot" value="40">гр. Сопот</option>
<option city_en="Sofiya" value="41">гр. София</option>
<option city_en="Stara Zagora" value="42">гр. Стара Загора</option>
<option city_en="Troyan" value="43">гр. Троян</option>
<option city_en="Tyrgovishte" value="44">гр. Търговище</option>
<option city_en="Haskovo" value="45">гр. Хасково</option>
<option city_en="Chirpan" value="46">гр. Чирпан</option>
<option city_en="Shumen" value="47">гр. Шумен</option>
<option city_en="Yambol" value="48">гр. Ямбол</option>
<option city_en="Beloslav" value="50">гр. Белослав</option>
<option city_en="Breznik" value="52">гр. Брезник</option>
<option city_en="Velingrad" value="53">гр. Велинград</option>
<option city_en="Elin Pelin" value="55">гр. Елин Пелин</option>
<option city_en="Etropole" value="56">гр. Етрополе</option>
<option city_en="Kalofer" value="59">гр. Калофер</option>
<option city_en="Kozloduy" value="60">гр. Козлодуй</option>
<option city_en="Lyaskovets" value="61">гр. Лясковец</option>
<option city_en="Marten" value="62">гр. Мартен</option>
<option city_en="Mezdra" value="63">гр. Мездра</option>
<option city_en="Panagyurishte" value="64">гр. Панагюрище</option>
<option city_en="Peshtera" value="65">гр. Пещера</option>
<option city_en="Pomorie" value="67">гр. Поморие</option>
<option city_en="Pravets" value="68">гр. Правец</option>
<option city_en="Provadiya" value="69">гр. Провадия</option>
<option city_en="Radomir" value="70">гр. Радомир</option>
<option city_en="Svilengrad" value="72">гр. Свиленград</option>
<option city_en="Svishtov" value="73">гр. Свищов</option>
<option city_en="Senovo" value="74">гр. Сеново</option>
<option city_en="Silistra" value="75">гр. Силистра</option>
<option city_en="Smolyan" value="76">гр. Смолян</option>
<option city_en="Tryavna" value="78">гр. Трявна</option>
<option city_en="Apriltsi" value="82">гр. Априлци</option>
<option city_en="Ardino" value="83">гр. Ардино</option>
<option city_en="Balchik" value="86">гр. Балчик</option>
<option city_en="Bankya" value="87">гр. Банкя</option>
<option city_en="Bansko" value="88">гр. Банско</option>
<option city_en="Batak" value="90">гр. Батак</option>
<option city_en="Belene" value="91">гр. Белене</option>
<option city_en="Belovo" value="93">гр. Белово</option>
<option city_en="Bobov Dol" value="95">гр. Бобов Дол</option>
<option city_en="Brezovo" value="102">гр. Брезово</option>
<option city_en="Perushtitsa" value="103">гр. Перущица</option>
<option city_en="Syedinenie" value="104">гр. Съединение</option>
<option city_en="Rakovski" value="105">гр. Раковски</option>
<option city_en="Pyrvomay" value="106">гр. Първомай</option>
<option city_en="Sadovo" value="107">гр. Садово</option>
<option city_en="Byala Slatina" value="108">гр. Бяла Слатина</option>
<option city_en="Knezha" value="109">гр. Кнежа</option>
<option city_en="Roman" value="110">гр. Роман</option>
<option city_en="Septemvri" value="113">гр. Септември</option>
<option city_en="Stamboliyski" value="114">гр. Стамболийски</option>
<option city_en="Strelcha" value="115">гр. Стрелча</option>
<option city_en="Rakitovo" value="116">гр. Ракитово</option>
<option city_en="Rila" value="117">гр. Рила</option>
<option city_en="Bratsigovo" value="118">гр. Брацигово</option>
<option city_en="Tsarevo" value="119">гр. Царево</option>
<option city_en="Sozopol" value="121">гр. Созопол</option>
<option city_en="Slynchev Bryag" value="122">гр. Слънчев Бряг</option>
<option city_en="Primorsko" value="124">гр. Приморско</option>
<option city_en="Nesebyr" value="125">гр. Несебър</option>
<option city_en="Kableshkovo" value="127">гр. Каблешково</option>
<option city_en="Zavet" value="128">гр. Завет</option>
<option city_en="Popovo" value="129">гр. Попово</option>
<option city_en="Kubrat" value="130">гр. Кубрат</option>
<option city_en="Isperih" value="131">гр. Исперих</option>
<option city_en="Tsar Kaloyan" value="132">гр. Цар Калоян</option>
<option city_en="Hisarya" value="133">гр. Хисаря</option>
<option city_en="Klisura" value="134">гр. Клисура</option>
<option city_en="Kirkovo" value="136">гр. Кирково</option>
<option city_en="Krumovgrad" value="137">гр. Крумовград</option>
<option city_en="Momchilgrad" value="138">гр. Момчилград</option>
<option city_en="Vyrshets" value="139">гр. Вършец</option>
<option city_en="Boychinovtsi" value="140">гр. Бойчиновци</option>
<option city_en="Dolna Oryahovitsa" value="141">гр. Долна Оряховица</option>
<option city_en="Strazhitsa" value="142">гр. Стражица</option>
<option city_en="Elena" value="143">гр. Елена</option>
<option city_en="Radnevo" value="145">гр. Раднево</option>
<option city_en="Gylybovo" value="146">гр. Гълъбово</option>
<option city_en="Dimitrovgrad" value="147">гр. Димитровград</option>
<option city_en="Kresna" value="148">гр. Кресна</option>
<option city_en="Harmanli" value="150">гр. Харманли</option>
<option city_en="Lyubimets" value="151">гр. Любимец</option>
<option city_en="Bozhurishte" value="153">гр. Божурище</option>
<option city_en="Boboshevo" value="154">гр. Бобошево</option>
<option city_en="Brusartsi" value="157">гр. Брусарци</option>
<option city_en="Veliki Preslav" value="158">гр. Велики Преслав</option>
<option city_en="Vylchedrym" value="161">гр. Вълчедръм</option>
<option city_en="Vylchi Dol" value="162">гр. Вълчи Дол</option>
<option city_en="General Toshevo" value="163">гр. Генерал Тошево</option>
<option city_en="Gotse Delchev" value="168">гр. Гоце Делчев</option>
<option city_en="Gurkovo" value="169">гр. Гурково</option>
<option city_en="Debelets" value="171">гр. Дебелец</option>
<option city_en="Dolni Dybnik" value="174">гр. Долни Дъбник</option>
<option city_en="Dragoman" value="176">гр. Драгоман</option>
<option city_en="Zlataritsa" value="180">гр. Златарица</option>
<option city_en="Zlatograd" value="181">гр. Златоград</option>
<option city_en="Kavarna" value="183">гр. Каварна</option>
<option city_en="Kiten" value="188">гр. Китен</option>
<option city_en="Kostinbrod" value="191">гр. Костинброд</option>
<option city_en="Kotel" value="192">гр. Котел</option>
<option city_en="Kocherinovo" value="193">гр. Кочериново</option>
<option city_en="Kranevo" value="194">гр. Кранево</option>
<option city_en="Kula" value="198">гр. Кула</option>
<option city_en="Lukovit" value="201">гр. Луковит</option>
<option city_en="Madan" value="202">гр. Мадан</option>
<option city_en="Miziya" value="205">гр. Мизия</option>
<option city_en="Myglizh" value="208">гр. Мъглиж</option>
<option city_en="Nikopol" value="210">гр. Никопол</option>
<option city_en="Novi Iskyr" value="212">гр. Нови Искър</option>
<option city_en="Novi Pazar" value="213">гр. Нови Пазар</option>
<option city_en="Omurtag" value="214">гр. Омуртаг</option>
<option city_en="Oryahovo" value="215">гр. Оряхово</option>
<option city_en="Pavel Banya" value="216">гр. Павел Баня</option>
<option city_en="Pavlikeni" value="217">гр. Павликени</option>
<option city_en="Pliska" value="220">гр. Плиска</option>
<option city_en="Polski Trymbesh" value="222">гр. Полски Тръмбеш</option>
<option city_en="Rudozem" value="229">гр. Рудозем</option>
<option city_en="Samokov" value="230">гр. Самоков</option>
<option city_en="Sveti Vlas" value="231">гр. Свети Влас</option>
<option city_en="Svoge" value="233">гр. Своге</option>
<option city_en="Simeonovgrad" value="234">гр. Симеоновград</option>
<option city_en="Simitli" value="235">гр. Симитли</option>
<option city_en="Slivnitsa" value="237">гр. Сливница</option>
<option city_en="Sredets" value="240">гр. Средец</option>
<option city_en="Suhindol" value="243">гр. Сухиндол</option>
<option city_en="Tvyrditsa" value="244">гр. Твърдица</option>
<option city_en="Tervel" value="245">гр. Тервел</option>
<option city_en="Teteven" value="246">гр. Тетевен</option>
<option city_en="Tutrakan" value="248">гр. Тутракан</option>
<option city_en="Cherven Bryag" value="249">гр. Червен Бряг</option>
<option city_en="Chepelare" value="250">гр. Чепеларе</option>
<option city_en="Shivachevo" value="252">гр. Шивачево</option>
<option city_en="Shipka" value="253">гр. Шипка</option>
<option city_en="Yablanitsa" value="254">гр. Ябланица</option>
<option city_en="Dulovo" value="256">гр. Дулово</option>
<option city_en="Devin" value="257">гр. Девин</option>
<option city_en="Tryn" value="260">гр. Трън</option>
<option city_en="Elhovo" value="263">гр. Елхово</option>
<option city_en="Straldzha" value="276">гр. Стралджа</option>
<option city_en="Pirdop" value="277">гр. Пирдоп</option>
<option city_en="Levski" value="281">гр. Левски</option>
<option city_en="Zlatitsa" value="286">гр. Златица</option>
<option city_en="Belogradchik" value="288">гр. Белоградчик</option>
<option city_en="Dolna Banya" value="294">гр. Долна Баня</option>
<option city_en="Dospat" value="295">гр. Доспат</option>
<option city_en="Krivodol" value="297">гр. Криводол</option>
<option city_en="Alfatar" value="299">гр. Алфатар</option>
<option city_en="Bulgaria" value="1033"> България</option>
<option city_en="Borovo" value="1238">гр. Борово</option>
<option city_en="Lyaskovets Sklad" value="1240">гр. Лясковец Склад</option>
<option city_en="Loznitsa" value="1241">гр. Лозница</option>
<option city_en="Kaspichan" value="1245">гр. Каспичан</option>
<option city_en="Hadzhidimovo" value="1253">гр. Хаджидимово</option>
<option city_en="Razlog" value="1270">гр. Разлог</option>
<option city_en="Dobrinishte" value="1272">гр. Добринище</option>
<option city_en="Belitsa" value="1277">гр. Белица</option>
<option city_en="Yakoruda" value="1278">гр. Якоруда</option>
<option city_en="Aksakovo" value="1284">гр. Аксаково</option>
<option city_en="Shabla" value="1290">гр. Шабла</option>
<option city_en="Obzor" value="1301">гр. Обзор</option>
<option city_en="Dve Mogili" value="1382">гр. Две Могили</option>
<option city_en="Banya" value="22454">гр. Баня</option>
<option city_en="Bolyarovo" value="22668">гр. Болярово</option>
<option city_en="Bregovo" value="22756">гр. Брегово</option>
<option city_en="Bylgarovo" value="22859">гр. Българово</option>
<option city_en="Byala Cherkva" value="22895">гр. Бяла Черква</option>
<option city_en="Vetren" value="22976">гр. Ветрен</option>
<option city_en="Vyrbitsa" value="23147">гр. Върбица</option>
<option city_en="Glavinitsa" value="23260">гр. Главиница</option>
<option city_en="Godech" value="23281">гр. Годеч</option>
<option city_en="Gramada" value="23481">гр. Грамада</option>
<option city_en="Gulyantsi" value="23516">гр. Гулянци</option>
<option city_en="Dimovo" value="23631">гр. Димово</option>
<option city_en="Dolna Mitropoliya" value="23735">гр. Долна Митрополия</option>
<option city_en="Dunavtsi" value="23895">гр. Дунавци</option>
<option city_en="Dylgopol" value="23942">гр. Дългопол</option>
<option city_en="Zhergovets" value="24037">гр. Жерговец</option>
<option city_en="Zemen" value="24138">гр. Земен</option>
<option city_en="Iskyr" value="24274">гр. Искър</option>
<option city_en="Kameno" value="24356">гр. Камено</option>
<option city_en="Kaolinovo" value="24373">гр. Каолиново</option>
<option city_en="Kermen" value="24432">гр. Кермен</option>
<option city_en="Koynare" value="24528">гр. Койнаре</option>
<option city_en="Koprivshtitsa" value="24584">гр. Копривщица</option>
<option city_en="Kostandovo" value="24609">гр. Костандово</option>
<option city_en="Kuklen" value="24745">гр. Куклен</option>
<option city_en="Letnitsa" value="24837">гр. Летница</option>
<option city_en="Lyki" value="24919">гр. Лъки</option>
<option city_en="Madara" value="24960">гр. Мадара</option>
<option city_en="Merichleri" value="25104">гр. Меричлери</option>
<option city_en="Momin Prohod" value="25198">гр. Момин Проход</option>
<option city_en="Nedelino" value="25286">гр. Неделино</option>
<option city_en="Nikolaevo" value="25315">гр. Николаево</option>
<option city_en="Opaka" value="25421">гр. Опака</option>
<option city_en="Pordim" value="25744">гр. Пордим</option>
<option city_en="Sapareva Banya" value="26144">гр. Сапарева Баня</option>
<option city_en="Slivo Pole" value="26321">гр. Сливо Поле</option>
<option city_en="Suvorovo" value="26562">гр. Суворово</option>
<option city_en="Sungurlare" value="26566">гр. Сунгурларе</option>
<option city_en="Syrnitsa" value="26600">гр. Сърница</option>
<option city_en="Topolovgrad" value="26671">гр. Тополовград</option>
<option city_en="Trystenik" value="26722">гр. Тръстеник</option>
<option city_en="Ugyrchin" value="26770">гр. Угърчин</option>
<option city_en="Tsarev Brod" value="26866">гр. Царев Брод</option>
<option city_en="Chiprovtsi" value="27038">гр. Чипровци</option>
<option city_en="Shtryklevo" value="27120">гр. Щръклево</option>
<option city_en="Dolno Shivachevo" value="27229">гр. Долно Шивачево</option>
<option city_en="Krayna" value="27312">гр. Крайна</option>
<option city_en="Krichim" value="27338">гр. Кричим</option>
<option city_en="Berkovitsa" value="27399">гр. Берковица</option>
<option city_en="Panichishte" value="27465">гр. Паничище</option>
<option city_en="AEC Kozloduj" value="27493"> АЕЦ Козлодуй</option>
<option city_en="Lukoil Neftohim" value="27500">гр. Лукойл Нефтохим</option>
<option city_en="Mobilen RC" value="27543">гр. Мобилен РЦ</option>
<option city_en="izvoz" value="55950">гр. Извоз</option>
<option city_en="Fürth" value="61003">гр. Фюрт</option>
<option city_en="Mobilen RC (Rujinci)" value="61233">гр. Мобилен РЦ (Ружинци)</option>
</select>
Here is what i find to be used for sorting options, but it is sorting them for value.
var options = $("#shipping-city-select option"); // Collect options
options.detach().sort(function(a,b) { // Detach from select, then Sort
var at = $(a).text();
var bt = $(b).text();
return (at > bt)?1:((at < bt)?-1:0); // Tell the sort function how to order
});
options.appendTo("#shipping-city-select"); // Re-attach to select
How can i REsort all the options in this select menu by city_en attribute alphabetically using jQuery ?
Thanks in advance!
Firstly, your HTML is invalid. You cannot invent your own attributes. If you want to store custom data with an element, use a data-* attribute, like this:
<option data-city-en="Aytos" value="1">гр. Айтос</option>
From there you can amend your sort logic to read that data attribute:
$("#shipping-city-select option[data-city-en]").sort(function(a, b) {
var at = $(a).data('city-en');
var bt = $(b).data('city-en');
return at > bt ? 1 : (at < bt) ? -1 : 0;
}).appendTo("#shipping-city-select");
Example fiddle
Note that you don't need to detach() the elements before you append() them in the corrected order.
Also note that you can sort directly on the text containing the Cyrillic characters if you use localeCompare():
$("#shipping-city-select option[data-city-en]").sort(function(a, b) {
return $(a).text().localeCompare($(b).text());
}).appendTo("#shipping-city-select");
Example fiddle
I have two select boxes:
<select name="county" id="countyselect">
<option value="Dixie">Dixie</option>
<option value="Hernando">Hernando</option>
<option value="Holmes">Holmes</option>
<option value="Jackson">Jackson</option>
<option value="Liberty">Liberty</option>
<option value="Putnam">Putnam</option>
</select>
<select name="site" id="siteselect">
<option value="Florahome">Florahome</option>
<option value="Green Swamp">Green Swamp</option>
<option value="NE Jackson County">NE Jackson County</option>
<option value="N Holmes County">N Holmes County</option>
<option value="S Liberty County">S Liberty County</option>
<option value="Suwannee">Suwannee</option>
</select>
When one box is changed, the other needs to change to the corresponding index (i.e. if Dixie is selected in "county", Florahome should be selected in "site"). My attempt using jQuery is below but does not seem to work.
$('select#countyselect').change(function() {
var countySelector = $('select#countyselect').attr("selectedIndex");
$('select#siteselect').attr('selectedIndex', countySelector);
});
$('select#siteselect').change(function() {
var siteSelector = $('select#siteselect').attr("selectedIndex");
$('select#countyselect').attr('selectedIndex', siteSelector);
});
Any ideas?
You want prop, not attr. Something like:
function matchUp(selected, toselect)
{
var idx = selected.prop('selectedIndex');
toselect.prop('selectedIndex', idx);
}
$('#countyselect').change(
function() {
matchUp($('#countyselect'), $('#siteselect'));
}
);
$('#siteselect').change(
function() {
matchUp($('#siteselect'), $('#countyselect'));
}
);
function matchUp(selected, toselect)
{
const idx = selected.prop('selectedIndex');
toselect.prop('selectedIndex', idx);
}
$('#countyselect').change(
function() {
matchUp($('#countyselect'), $('#siteselect'));
}
);
$('#siteselect').change(
function() {
matchUp($('#siteselect'), $('#countyselect'));
}
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="county" id="countyselect">
<option value="Dixie">Dixie</option>
<option value="Hernando">Hernando</option>
<option value="Holmes">Holmes</option>
<option value="Jackson">Jackson</option>
<option value="Liberty">Liberty</option>
<option value="Putnam">Putnam</option>
</select>
<select name="site" id="siteselect">
<option value="Florahome">Florahome</option>
<option value="Green Swamp">Green Swamp</option>
<option value="NE Jackson County">NE Jackson County</option>
<option value="N Holmes County">N Holmes County</option>
<option value="S Liberty County">S Liberty County</option>
<option value="Suwannee">Suwannee</option>
</select>