Add or remove dropdown elements from the javascript or jquery - javascript

I have dropdownlist whose value is filled using the value of the other drop down. The problem here is that i need to bind the value of the second when the value of the first changes. I need to do it from the javascript.
Only thing i need to do is remove and add the select options in the second dropdown as the first dropdown changes.
How can i do this?
Thanks in advance.

Not too sure exactly what you want with the limited information provided but here is a solution that I think you are looking for:
HTML:
<select id="primary">
<option value="one">One</option>
<option value="two">Two</option>
</select>
<select id="secondary"></select>
jQuery:
var opts = {
'one':['a','b','c'],
'two':['d','e','f']
};
$('#primary').change(function(){
var select = [];
$.each(opts[this.value], function(k, v){
select.push('<option>'+ v +'</option>');
});
$('#secondary').html(select.join(''));
});
Demo: http://jsfiddle.net/28TQZ/

$("#dropdownlist1").change(function () {
var selected = $("#dropdownlist1 option:selected");
//clear
$("#dropdownlist2").html("");
$("#dropdownlist2").append($("<option/>").text(selected.text()).val(selected.val()));
})

Create all the drop downs you need, but only add options to the first one. The next ones only have a "default" value.
On selecting the first drop down, you use jQuery to get the values for the second drop down, based on the value selected in the first drop down:
$.post('ajax/aj_populate2nddropdown.php', $("#firstdropdown").val(), function(result) {
$('div.placedaround2nddropdown').html(result);
});
The file ajax/aj_populate2nddropdown.php collects the values of the second drop down, and returns them, inserted as options into the dropdown.

One simple way to do it is to just have a main dropdown and a bunch of secondary dropdowns that start hidden. when you choose something from the first, then you unhide the related second one

Try this If you are trying at client side
Replace your controls with asp.net server controls

Related

jQuery: How do you check to see if a selected dropdown item is already in a textbox list?

I've got a dropdown box to the left of a select/option box.
I would like for jquery to check to see if the item already exists by value. The value for each option won't be in any order.
Text box:
<select id="selectbox">
<option value="20:32">Something1</option>
<option value="103:16">Something2</option>
</select>
The dropdown will have a list of items that also share the same values.
Is there a way to do something like:
$("#boxbutton").click(function () {
if (('#dropdownbox :selected').val() doesn't exist inside #selectbox list)
{
...add dropdownbox item;
} else { do nothing };
});
I want to make sure the function is checking the entire selectbox value list and NOT selected/highlighted entries in the selectbox. The textbox won't always have selected entries and will need to be checked anyway.
When The user goes to the dropdown box to add another entry to the selectbox it should repeat the search.
Not having any luck using the .length keyword. Any ideas?
Try this:
var value = $('#dropdownbox').val(); // :selected is unnecessary
var hasValue = ( $('#selectbox option[value="'+value+'"]').size() > 0 );
Keep one Array and put all of your values into it. Then you can easily validate your text box value with that array.
Or you have to get all option tag value by using DOM iteration.

Remove previous drop down selection from future drop down options

I have a modal that presents you with an option to insert a row. The row has a drop down menu with around 10 values to choose from. When I click the insert button to insert another row I need the new drop down that is generated to NOT have the previous row's selected value in the options. Basically it's like a bunch of cascading drop downs. The new drop down will not have the previous drop down's selected option.
Basically my question is how could/should I go about implementing this with JavaScript/JQuery?
It would be good to see your code to give a good answer, but you can remove an option like this...
$("#yourdropdownlistid option[value='thevalueofthetargetoption']").remove();
You might try changeing the option value of the selected item to 'remove' on change, then you can target all of the 'remove' option values.
$("#yourdropdownlistid option[value='thevalueofthetargetoption']").each(function() {
$(this).remove();
});
you can see it running here...
http://jsfiddle.net/pUeue/1420/
Assuming you have the following HTML:
<div id='container'>
<button>add</button>
<div class='row'>
<select>
<option>hi</option>
<option>hello</option>
<option>how</option>
<option>are</option>
<option>you</option>
</select>
</div>
</div>
You can do it as follows:
$('button').click(function () {
var clone= $('.row').last().clone();
clone.find('option:selected').remove();
if($(clone).find('option').length>0)
$('#container').append(clone);
});
check this JSFiddle

Add and select a "fake" <option> value to a <select>

I need to add a "fake" <option> to a <select>, that will be shown as the selected one, but that can't be selected in the dropdownmenu if the user want to change item.
For example: I have a page that displays 10 fruits. Each fruit has his weight. Using the select, I can filter the fruits by weight:
<select id="fruits">
<option>1 kg</option>
<option>2 kg</option>
<option>3 kg</option>
</select>
if I select the 2nd option (2kg), the page will remove every fruit that has weight != 2kg, and obviously show only those with weight == 2kg.
Now I need to add a "weight range", for example "show fruits whose weight is between 1 and 2 kg". I don't want to add a new option to the , I just want to filter the table showing fruits with weight between the selected range (1 and 2kg), and show this range as the selected value in the select. So my CLOSED dropdown menu will have value = "1-2kg", but if I click on the select, I will not find "1-2kg" option (that's why I wrote "fake" option in the title).
In a nutshell I just want to edit the selected-shown select text, not his options... Something like, using JS
var select = document.getElementById("fruit-select");
select.value = "1-2kg";
obviously this is not working because the option "1-2kg" does not exists..
Is this possible? I hope I was clear enough.. Thanks in advance for any helps, best regards
Solution (not working on Safari...)
Thanks to Ricardo I came to this solution: http://jsfiddle.net/4suwY/5/
HTML:
<select id="asd">
<option>hello</option>
<option>I'M THE CHOSEN ONE</option>
<option>asd</option>
<option>wer</option>
<option>qwe</option>
</select>
JS:
var sel = document.getElementById("asd");
var optnz = sel.getElementsByTagName("option")[1];
sel.value = optnz.value;
optnz.style.display = "none";
the "I'M THE CHOSEN ONE" option is displayed as selected, but is not clickable (not even visible in the options list)
Thanks guys!
I think what you need to do here, is actually have a visible select with all those values, 1kg, 2kg, etc and then you have a hidden select, that will contains those ranges, like 1-2kg, etc (if the ranges are fixed). Everytime you select something from the visible dropdown you change the selected item of the hidden dropdown to the desired range.
It sounds like you want to include a range of weights. You may want to consider a different type of input, such as a range slider. Here's an example from the jQuery UI project. I'm not suggesting you use jQuery UI per se, just showing you one way it can be implemented.
You could use <select multiple> and whenever someone selects more than one option you get the maximum and minimum and show that interval.
try this:
http://jsfiddle.net/4suwY/4/
the only problem I see is losing the value on select click on this function:
$("#asd").mousedown(function () {
$("#asd option[value='1-2kg']").remove().change();
});

Maintain a set of select drop down lists using Javascript

I have a set of drop down lists (8 in all). All drop downs have the same set of drop down options available to them. However the business requirement is to make sure that the user cannot select the same option more than once.
Looking at the problem, at first it appears simple but it's rapidly becoming lots of code. However it seems like a relatively common problem. Does anyone know of a solution, have any tips on how to do this without writing reams of Javascript. Some sort of reusable jquery plugin might be handy for this too. Does one exist?
One issue is that when a select item is chosen, it then becomes unavailable to the other select lists. The item is removed from the other select drop downs. When it becomes available again (a drop down changes) it needs to be inserted at the correct point in the list (the drop down options have an order). This is the bit where my solution has started to get quite complex.
Personally, the way I'd implement it is to have a "master" drop down containing all possible options, simply for the purpose of caching. These options are then replicated in each of the "slave" drop downs. Whenever any slave drop down is changed, they're all re-populated again to ensure that no two drop downs can share the same selected value.
For the purpose of demonstration, I've only worked with 3 drop down lists in the code below, but it should scale up pretty easily. Just add mode drop downs and make sure they contain the attribute class="slave".
Also, if you want any of the options to be immune from being removed, so that it's possible to exist in all of your slave drop downs (such as the default option in the code below), just add the attribute class="immune" to the option tag in the master drop down.
<script type="text/javascript">
// document - on load
$(document).ready(function() {
// initially populate all the drop downs
PopulateAllDropDowns();
// populate all drop downs on each subsequent change
$('select.slave').change(function(){
PopulateAllDropDowns();
});
});
function PopulateAllDropDowns()
{
// populate all the slave drop downs
$('select.slave').each(function(index){
PopulateDropDown($(this).attr('id'));
});
}
function PopulateDropDown(id)
{
// preserve the selected value
var selectedValue = $('#'+id).val();
// clear current contents
$('#'+id).html('');
// attempt to add each option from the master drop down
$('select#ddlTemplate').children('option').each(function(index){
// scope-safe var
var masterOptionValue = $(this).val();
// check if option is in use in another slave drop down, unless it's immune
var optionInUse = false;
if (!$(this).hasClass("immune"))
{
$('select.slave option:selected').each(function(index){
if (masterOptionValue == $(this).val() )
optionInUse = true;
});
}
// if it's not in use, add it to this slave drop down
if (!optionInUse)
{
// create new option
var newOption = $('<option></option>').val($(this).val()).html($(this).text());
// ensure selected value is preserved, if applicable
if (selectedValue == $(this).val())
newOption.attr('selected', 'selected')
// add the option
$('#'+id).append(newOption);
}
});
}
</script>
<form>
<!-- master drop down -->
<select id="ddlTemplate" class="master" style="display:none">
<option value="" class="immune">Select ...</option>
<option value="a">Option A</option>
<option value="b">Option B</option>
<option value="c">Option C</option>
<option value="d">Option D</option>
<option value="e">Option E</option>
</select>
<!-- slave drop downs -->
<select id="ddlOne" class="slave"></select>
<select id="ddlTwo" class="slave"></select>
<select id="ddlThree" class="slave"></select>
</form>
Hope that helps.
The simplest way to do what you want is binding a function in the select event from dropdown list that filter content from all other dropdowns and remove or disable the options with value already selected.
To keep the order from your list, cache the options list in array, then you can remove and add in the right position, or remove all options and re-add the current possible options.
If you want re-select the cached already chosen options, and you don't lose anything.

Selecting options from a drop down

I'm building a recipe-finder for a new food blog. The design I have basically involves the user selecting ingredients, one at a time, from a drop down <select>, the option disappearing from the list (so they can't select it again) and appearing on another HTML list with a link to remove it from the list. Once they're done, they click a button and that takes them through to a results page.
Here's the select markup as generated by the PHP:
<select>
<option value="">Please select</option>
<option value="beef-mince">Beef mince</option>
<option value="carrots">Carrots</option>
...
</select>
It's not drastically complex but it does raise a few questions on how I'm going to do some of these things. I'm using jquery.
I need to store the selected items in memory so I know what to send to the search page when they've done selecting items. What's the best way of doing that in your opinion as each item has two values (its "real" value and its database-value)?
How do I make "Please select" the selected option after they've selected something (preferable without triggering the onchange event)?
Once I've stored it in memory and added it to the displayed list of things they're searching for, how do I delete that item from the available items? Can I just "hide" or disable it (safely)?
If in #3 I have to delete it from the DOM, when I add it again, can I sort the list (based on either value) and keep the please-select option at the top?
1.) You can append hidden form elements to the page whose value is the value of the selected option.
2.)
jQuery("#select-list")[0].options[0].selected = true // assuming it's the first item
3.) I would remove the element from the DOM using jQuery("#select-list option:selected").remove()
4.) You can use before(). jQuery(your_default_option).before("#select-list option:first");
You can store the 'two values' in a hidden form field as an object in JSON notation. This will make it easy to modify in jQuery as the user interacts with the page.
You will need to use a combination of the onchange, keyup and keydown event to capture possible changes to the form so that you can re-select the 'Please Select' option.
You will need to remove the option from the dom and re-add it later. You can easily do this through jquery through something like this:
$("select option:selected").remove();
You can write a sorting function for the options starting with index 1, and keep the 'Please Select' as the first option.
1)
Basic idea, you need to check to make sure the first is not picked
var selections = [];
var mySel = document.getElementById("mySelectId");
var ind = mySel.selectedIndex;
selections.push( mySel.options[ind].value ); //add to a list for you to remember
mySel.options[ind] = null; //remove
2)
mySel.selectedIndex = 0;
3)
See #1
4) Yes you can add it anywhere you want by using insertBefore
Example here: http://www.pascarello.com/lessons/forms/moveSelectOptions.html
Will leave this answer here but I think I failed to read your whole post, so it might not help much.
You need to give your select a id like this:
<select id="MySelect">
<option value="">Please select</option>
<option value="beef-mince">Beef mince</option>
<option value="carrots">Carrots</option>
...
</select>
And to get it is just something like this:
<?php
$value = $_REQUEST["MySelect"];
echo $value;
?>
Code is not tested and $_REQUEST can be replaced by $_GET or $_POST regarding what you have specified as action on your form. $_REQUEST will eat it all though.

Categories