I am trying to check if there is hos paramaeter in the url has anything and if there is, then pass that value as the selected attribute to the dropdown on page refresh, so the dropdown option remains selected even after refresh
var value = window.location.href.match(/[?&]hos=([^&#]+)/) || [];
if (value.length == 2) {
$('#hospitalDropDown[value="' + value[1] + '"]').attr('selected', 'selected');
}
Here is the dropdown:
<select id="hospitalDropDown" onchange="window.open(this.options[this.selectedIndex].value,'_top')"> <option value="http://mysite.com/events/Pages/default1.aspx">All Hospitals</option> <option value="http://mysite.com/events/Pages/default1.aspx?hos=Dyer">Dyer</option> <option value="http://mysite.com/events/Pages/default1.aspx?hos=Carmel">Carmel</option> </select>
It looks like your options have the querystring value—All Hospitals, Dyer, Carmel—as the text, but the whole url as the value.
As a result, match on your option's value with *=
if (value.length == 2) {
$('#hospitalDropDown option[value*="' + value[1] + '"]').attr("selected", "selected");
Related
I have a dropdown box (Sub District) and a "listbox_source" (villages). I prepare value for the dropdown and listbox from sql server and listbox's values depend on drop down, dynamic.
Then, I have another "listbox_destination" for moving selected village from "listbox_source". I've done for moving value from listbox_source to listbox_destination.
but, then, there is questions,
how do I know if listbox_destination still empty or has values ?
how do I know if there is no double value in listbox_destination
when Sub District dropdown was selected for the second time and with
the same value ?
Please, advice...
I try give an example of my code:
Dropdown:
<select id="ID_Villages" size="10" multiple="">
<option value="42">Bandul</option>
<option value="43">Dedap</option>
<option value="44">Mekar Delima</option>
<option value="45">Putri Puyu</option>
<option value="46">Tanjung Padang</option>
<option value="47">Tanjung Pisang</option>
<option value="187">Kudap</option>
<option value="188">Selat Akar</option>
<option value="189">Mengkopot</option>
<option value="190">Mengkirau</option>
$(document).ready(function (e) {
$('#btn_To_Right').click(function (e) {
var selectedList = $('#ID_Villages option:selected').toArray();
if ($('selectedList').length == 0) {
alert("Nothing to move.");
e.preventDefault();
} else {
<!-- #1. how to check listbox_destination still empty or has values ? -->
$(selectedVillage).append($(selectedList).clone());
$(selectedList).remove();
alert(selectedVillage.length);
} else {
<!-- #2. how to avoid double values -->
$each(selectedList, function (index, value) {
if($selectedVillage ??? ).length == 0){
<!-- add new value -->
} else {
alert ("data already exist");
}
}
}
}
})
})
UPDATE
for first moving (#1), from listbox_source to listox_destination, I check listox_destination by using
if ($("#lst_ID_Desa_Selected option").length == 0) {
$(selectedVillage).append($(selectedList).clone());
$(selectedList).remove();
}
and then for double values protection (#2)
$.each(selectedList, function (index, value) {
alert($("selectedList option[value='" + 42 + "']").length);
alert($("selectedList option[value='" + value.value + "']"));
alert($("selectedList <option value='" + value.value + "'>"));
})
I tried to get value from
alert($("selectedList option[value='" + value + "']").length);
by using alert but popup value appears "0". Whereas, selectedList is the source data of villages.
I tried to get value from
alert($("selectedList option[value='" + value.value + "']"));
by using alert and the return value as [object Object]
while I tried to get value from
alert($("selectedList <option value='" + value.value + "'>"));
there is error message:
syntax error, unrecognized expression: selectedList <option value='42'>
I think, I have to check selectList syntax before I use it for if under $.each syntax.
Please, I need further advice for this JS/jQuery syntax.
To find whether list is empty or not, is can be done using the following code after $(selectedList).remove();
$("#ID_Villages option").length; //If 0 then no options in the select list
To check for duplicates, you can use something like:
$("selectedDesa option[value='42']").length;
If the value of above is 0 then no option found in the destination list. If the length is 1 then option already exists. You can replace the value attribute based on the selected option value from the source list.
Update:
There is no need to loop. You can use the logic as below:
var selectedList = $('#ID_Villages option:selected').toArray();
var selectedVal = $('#ID_Villages option:selected').val(); // New code
Then while checking for duplicates, use the below:
$("selectedDesa option[value='" + selectedVal + "']").length;
I'm debugging some jQuery. Here's the active script snippet:
<select id="myselect[]" multiple="multiple">
<option value="any">any</option>
<option value="item1" selected="selected">description 1</option>
<option value="item2">description 2</option>
<option value="item3">description 3</option>
</select>
function myselect_change() {
var listid = '#myselect\\[\\]'; // for ease of reading
var current_sel_in = ($(listid).val() || ['any']); // Ensures correct when none selected
alert ('selection on entry: ' + current_sel_in.join(", "));
// if "any" is selected, clear all selections
if (!jQuery.inArray('any', current_sel_in)) {
$(listid + ' option:selected').removeAttr('selected');
}
// if nothing selected, select "any"
if ($(listid + ' option:selected').length == 0) {
$(listid + ' option[value="any"]').attr('selected', 'selected');
}
var current_sel_out = ($(listid).val() || ['any']);
alert ('selection on exit: ' + current_sel_out.join(", "));
}
$('#myselect\\[\\]').on('change', function() {
myselect_change();
});
I test the code by using clicks and ctrl+clicks to select and deselect options, for example:
Select multiple items then ctrl-click "any" to add "any" as a selection (expected: "any" selected, but all others deselected)
Select a single item, then ctrl-click that same item again so nothing selected (expected: "any" selected, all others deselected)
What's weird is that I can see the correct start+end values in the alerts, so the logic seems to be doing what it should. But the GUI isn't showing the programmatically changed options when the event ends. On exit, when it says that "any" is the only selected option, sometimes no options are highlighted in the select box on the GUI.
To confuse things, sometimes the selection is partly modified on the GUI when the alerts are left in but not when they're deleted - sorry that's confused, it seems almost random.
I haven't seen other similar code needing forcible refresh handling, so that doesn't seem to be an issue either.
What's going on?
When any is clicked remove the selected attribute for all the option except the one with any.
Replace $(listid + ' option:selected').removeAttr('selected'); with $(listid + ' option[value!="any"]:selected').removeAttr('selected');
function myselect_change() {
var listid = '#myselect\\[\\]'; // for ease of reading
var current_sel_in = ($(listid).val() || ['any']); // Ensures correct when none selected
alert ('selection on entry: ' + current_sel_in.join(", "));
// if "any" is selected, clear all selections
if (!jQuery.inArray('any', current_sel_in)) {
$(listid + ' option[value!="any"]:selected').removeAttr('selected');
}
// if nothing selected, select "any"
if ($(listid + ' option:selected').length == 0) {
$(listid + ' option[value="any"]').attr('selected', true);
}
var current_sel_out = ($(listid).val() || ['any']);
alert ('selection on exit: ' + current_sel_out.join(", "));
}
$('#myselect\\[\\]').on('change', function() {
myselect_change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="myselect[]" multiple="multiple">
<option value="any">any</option>
<option value="item1" selected>description 1</option>
<option value="item2">description 2</option>
<option value="item3">description 3</option>
</select>
Hello this is my current code:
<select id="link_course">
<option value="">Select Course</option>
<option value="ALL">ALL</option>
<option value="BSIT" selected>BSIT</option>
<option value="BSA">BSA</option>
<option value="BSBA">BSBA</option>
<option value="BSHRTM">BSHRTM</option>
</select>
<script>
$("#link_course").change(function()
{
document.location.href = "home.php?course=" + $(this).val();
});
</script>
If you click any of those options, for example BSBA, it will go to home.php?course=BSBA, and also you can see that the selected attribute is on the option BSIT. What I wanted to do is whenever I click another link, for example BSHRTM, the selected attribute will go to BSHRTM like it would be <option value="BSHRTM" selected>BSHRTM</option>. Any thoughts?
You can do selection via JavaScript :
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
if(getQueryVariable('course') != false) {
$('#link_course option[value="' + getQueryVariable('course') + '"]').prop('selected', true);
}
Reference
After loading the new page, you need to run JavaScript code to set the value on the correct item from the list.
Use window.location.hrefto get current URL. Then check on which page is user currently on and finally select corresponding option.
if(window.location.href.indexOf('home.php?course=BSHRTM)') != -1) {
$('select#link_course option[value=BSHRTM]').attr("selected","selected");
}
To avoid code duplication see Parse query string in JavaScript
You should do it in PHP:
<option value="BSHRTM" <?php if($course == 'BSHRTM') echo 'selected';?>>
Supposing that you previsously set $course = $_GET['course'];
I have created two identical dropdown select boxes as below:
HTML
<select id="ddl1" name="ddl1">
<option value="1">TEXT 1</option>
<option value="2">TEXT 2</option>
<option value="3">TEXT 3</option>
</select>
<select id="ddl2" name="ddl2">
<option value="1">TEXT 1</option>
<option value="2">TEXT 2</option>
<option value="3">TEXT 3</option>
</select>
Using jquery I have created code to update the value of one when the other changes and vice versa as below:
JQUERY
var a = ('#ddl1'),
b = ('#ddl2');
$(a + ',' + b).change(selectddl);
$(selectddl);
function selectddl() {
var val = $(this).val();
var text = $(this).text();
if (this.id === 'ddl1') {
$(b + ' option[value="' + val + '"]').prop('selected', true);
$(b).selectmenu('refresh');
} else if (this.id === 'ddl2') {
$(a + ' option[value="' + val + '"]').prop('selected', true);
$(a).selectmenu('refresh');
}
};
My requirements now are to update the select boxes based on their contained TEXT and not their value.
QUESTION
How to update a dropdown select box based on another select box contained TEXT?
After some research I have tried but failed to do this as below:
JQUERY
var a = ('#ddl1'),
b = ('#ddl2');
$(a + ',' + b).change(selectddl);
$(selectddl);
function selectddl() {
var val = $(this).val();
var text = $(this).text();
if (this.id === 'ddl1') {
$(b + ' option[value="' + val + '"]').prop('selected', true);
$(b).selectmenu('refresh');
} else if (this.id === 'ddl2') {
$(a + ' option:contains("' + text + '")').prop('selected', true);
$(a).selectmenu('refresh');
}
};
CLICK FOR DEMO
Can anyone explain how this can be achieved?
The correct answer to this question would NOT use contains due to the conflicts that could arise with text such as:
TEXT
TEXT1
You can use the .filter() function to achieve what you are requesting. You will basically need to select all of the options, then call .filter(), passing in a function that only accepts the option who's text is equal to what you expect.
For example, your else if statement might look like this:
else if (this.id === 'ddl2') {
$(a + ' option').filter(function() {
return this.text === text;
}).prop('selected', true);
$(a).selectmenu('refresh');
}
Also, it looks like you need to change your text variable as well. You should change it to something that will select the text of the currently selection option, like so:
var text = $(this).find(':selected').text();
Here's a working Fiddle.
When an option is selected that wasn't previously, the onChange handler can detect this. How can a preselected option be detected (i.e., whether a select field has any option selected)? Is this possible without jQuery? Is there a handler, such as onSelected (not the same as onSelect for highlighted text) for this event?
Example:
<select onSelected="FunctionRunIfOptionSelected()">
<option> ... </option>
...
</select>
The preselected option will have been selected on page load. i.e., with the HTML dynamically rendered:
<option selected> ... </option>
If I understand, the task is to tell if an option has the selected attribute hard-coded into the HTML? If so, this should work:
function test () {
var opts = document.getElementById("myselect").options;
var i, len = opts.length;
for(i = 0; i < len; i++) {
if (opts[i].getAttribute("selected" ) != null ) { // opts[i] has the selected attribute
change_other_select(i); // pass the option index to your other function
break;
}
}
}
window.onload = test;
The trick is to distinguish between the selected property and the selected attribute, and also between a null value and an empty string.
var myselect = document.getElementByid('selectid');
myselect.options[myselect.selectedIndex];
To test for selected option on page load, you'll need to catch these in the window.onload handler
One the page is loaded you'll need to continue to use the onChange handler, but use selectedIndex property to test if this is populated with an index within your option list.
Alternatively give your options values in the HTML and check the values themselves. This will allow deterministic behavior when expanding the option list.
Yes, using the .options[] and .selectedIndex methods you can handle this cleanly and unobtrusively like so:
HTML
<select name="select" id="select">
<option value="">...</option>
<option value="1">One</option>
<option value="2" selected="selected">Two</option>
</select>
JavaScript
window.onload = function(){
var select = document.getElementById("select"), selected = select.value;
select.onchange = function(){
var val = select.options[select.selectedIndex].value;
if(val != selected) {
alert("Another value " + val + " was selected, which is not the same as the default value of " + selected);
} else {
alert("Same value as the default of " + selected + " was selected");
}
};
};
From within the JS, you can check and manipulate the val variable as you like.
You can detect if the select field does not have the default value selected like this:
var selects = document.getElementsByTagName("select");
for (i=0;i<selects.length;i++) {
if (selects[i].selectedIndex != 0) {
eval(selects[i].getAttribute("onSelected"));
}
}