How to populate a dropdown select box by matching contained text? - javascript

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.

Related

Detecting value in listbox with jQuery

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;

Why isn't the select box reflecting the values shown in alerts? (Javascript/jQuery)

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>

How to add dynamically a combobox using jQuery

I've this working code which is creating one combobox:
You can see it working here: jsfiddle
$('body').on('change', '.combo', function() {
var selectedValue = $(this).val();
if ($(this).find('option').size() > 2) {
var newComboBox = $(this).clone();
var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
var newComboBoxIndex = thisComboBoxIndex + 1;
$('.parentCombo' + thisComboBoxIndex).remove();
if (selectedValue !== '') {
newComboBox.attr('data-index', newComboBoxIndex);
newComboBox.attr('id', 'combo' + newComboBoxIndex);
newComboBox.addClass('parentCombo' + thisComboBoxIndex);
newComboBox.find('option[val="' + selectedValue + '"]').remove();
$('body').append(newComboBox);
}
}
});
Which is resulting something this, everytime I fill a combobox, the next one is opened.
How can I change that code to have this? Which means two comboboxes opening (please forget the style)
Thank you.
I'm not entirely sure if your intent, but it seems like you want to have groups of two select elements and then adding a new group when the user selects a value.
In that case I suggest grouping your two selects in a fieldset like this:
<fieldset>
<select id="combo1" class="combo" data-index="1">
<option></option>
<option val="Opt1">Opt1</option>
<option val="Opt2">Opt2</option>
<option val="Opt3">Opt3</option>
</select>
<select id="combo2" class="combo" data-index="2">
<option></option>
<option val="Opt1">Opt1</option>
<option val="Opt2">Opt2</option>
<option val="Opt3">Opt3</option>
</select>
</fieldset>
​
And then looking up that parent fieldset and cloning it like this:
$('body').on('change', '.combo', function() {
var selectedValue = $(this).val();
var fieldset = $(this).parents('fieldset');
if ($(this).find('option').size() > 2) {
var newFieldset = fieldset.clone();
var newComboBox = $(fieldset).children('.combo:first');
var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
var newComboBoxIndex = thisComboBoxIndex + 1;
$('.parentCombo' + thisComboBoxIndex).remove();
if (selectedValue !== '') {
newComboBox.attr('data-index', newComboBoxIndex);
newComboBox.attr('id', 'combo' + newComboBoxIndex);
newComboBox.addClass('parentCombo' + thisComboBoxIndex);
newComboBox.find('option[val="' + selectedValue + '"]').remove();
$('body').append(newFieldset);
}
}
});​
There are some details probably not exactly the way you need it, but in general this is the approach I'd recomment.
Find the updated Fiddle here: http://jsfiddle.net/JaVVe/8/
If you just want to double the amount of combo boxes you could use a for-loop and set their values depending on the value of the counter-variable.

Counting no. of dropdownlists inside a div

<div id="myDiv">
<select id="ddl1" name="31">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3" selected="selected">Three</option>
</select>
<select id="ddl2" name=32>
<option value="1">A</option>
<option value="2" selected="selected">B</option>
<option value="3">C</option>
</select>
</div>
Thats my div. The number of dropdowns inside this div vary. What I want is this in a string:-
31,3||32,2
The above is name attribute value of dropdowns, 2nd number after comma is the "value" of the selected option and values of both dropdownlists are separated by pipe symbol. The dropdowns can be 3 and 4 in number too. How can I acheive this in jquery?
A little something like this:
var selects = [];
$("#myDiv select").each(function() {
selects.push(this.name + "," + $(this).val());
});
var output = selects.join("||");
Where the .each() method is used to iterate through all the select elements and push their name and current value into the selects array, then the array .join() method is used to turn the array into a string using "||" as the separator.
try this snippet:
var output = [];
$('#myDiv select').each(function() {
output.push([this.name, $(this).val()].join(','));
});
console.log(output.join('||'));
Try the following:
var values = [];
$('#myDiv select').each(function() {
values.push($(this).attr('name') + ',' + $(this).val());
});
var result = values.join('||');
var val = "";
$("select").each(function(){
val += $(this).attr("name") + "," + $("option:selected",this).val()+ "||";
})
if(val != "")
val = val.substring(0, val.length - 2);
console.log(val);

keep dropdownselection? what am i doing wrong?

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");

Categories

Resources