change the default selected option in a select via jquery - javascript

I have a select list where one option is selected by default when the page loads.
When a different option is selected, the html I view in Firebug does not change.
I have a button that makes copies of this element, and would like the copies to have the same selected value as this one, but they all have the default value selected.
How can I make the copies have the same selected values as the original?

When you clone the element you should be able to set the cloned select's value to that of the original. E.g.,
var $select = $('#my-select'),
$clone = $select.clone().val($select.val());
// I don't know where you really want the clone, just an example...
$clone.insertAfter($select);

Related

jQuery clone select list remove selected

I have a button that is cloning an element on the page each time the user clicks it. It is duplicating a select list for them to choose another option.
However, its cloning the whole element including the option that was selected so all of the new ones appended have a default value which I dont want.
globalLocales = $("<div />").append($('[name=localeID]:first').clone()).html();
$('select').select2();
Is there a way I can remove the selected option during the cloning process so it doesn't carry over to the new element?
I tried using .removeProp('selected') in the append as well as .prop('selected',false); but that didn't work for me
One way to fix the proble is to select a nonexistent value:
$("<div />").append($('[name=localeID]:first').clone().val(-1)).html();
Or you can find selected option and remove selected attribute:
$("<div />").append($('[name=localeID]:first').clone()
.find(':selected').removeAttr('selected').end()).html();
but this is a little clumsy.
you can remove the selected attribute with this code.
$('[name=localeID] option:selected').removeAttr('selected');

jquery cloning select box without selected option

Need to clone select box from previous one ( ie, add select box 'n' number of time from the previous one )
But when I added each time, all the previously selected options should not be available in the cloned select box list.
$('.field_select_box_list').each(function(){
$(this).find('option:selected').remove();
});
This code removes the parent select boxes selected option too.. but I want remain them to have the selected option.
any help.
Your clone code can just do something like
$('el').clone().find('option:selected').remove().end()
The .end() causes the selector to return to being $('el') rather than the filtered option:selected selector, so you can continue running things like .appendTo() etc without needing to break the chain.
I think you need use one select_box original, hidden it. Then you can remove with select_box second not hidden or add more element from select_box original.

Select element by dynamically changed attribute

Solved by #Grundy, solution at bottom of post
I have a form with a radio option where the elements are selected programmatically and without the user directly clicking on the radio element.
var $elem = $("input[name=type][value^=foo_]"); // Select the element with name "type" where the value starts with "foo_" (assume only one value is ever found)
if ($elem.length > 0) // If element is found then toggle the checked value of the radio value
{
$("input[name=type][checked=checked]").attr("checked", false); // Uncheck all existing checked items
$elem.attr("checked", true); // Check the found element from before
}
This works, I can see the attributes change in Chrome's developer tools. The previous checked input is unchecked and the appropriate item becomes checked. This works every time specifically works multiple times (I'll explain why that's relevant later).
Next I hide all the unchecked radio buttons and show only the checked one.
$("input[name=type] + label").hide();
$("input[name=type]:checked + label").show();
This works the first time an input is selected. All the unchecked inputs will be hidden and the checked one will be unhidden. If the input is selected a second time (either immediately again or after other options have been selected in between) then all of the inputs are hidden including the checked one.
If I check the number of matched elements for $("input[name=type]:checked + label") it returns 1 for the first time and 0 for the second time meaning it won't be selected only after the second time. I feel like this is because the checked attribute has been changed dynamically at that point but that may not be the cause of the problem.
EDIT - Here's a Fiddle
fiddle Clicking on the gray box will show you its normal behavior when changed by the user clicking on the values. Each value can be selected multiple times in any order but if you click the text at the bottom (they're poor looking buttons) it will change the form programmatically. It only works for the first time, it does not seem to care if it was selected by the user previously.
Solution - Credit #Grundy
Since I know the $elem object I found earlier is the object being changed I can reference it directly instead of trying to search for an element with the checked attribute. So I use this:
var $elem = $("input[name=type][value^=foo_]"); // Created before all the changes
$elem.next("label").show(); // Referenced after all the changes
Instead of using this:
$("input[name=type]:checked + label").show(); // Referenced after all the changes
try use
$elem.next("label").show();
instead of
$("input[name=type]:checked + label").show();
because $elem is checked checkbox that you find

Autofocus blank space in dropbox without creating an empty option?

I have a select that has dynamically created option option[0] always ends up being autofocused making my onchange not work if I want to choose the first option.
The index of the options matter so creating a " " option won't work.
Any ideas?
edit: The user creates an object. When the user saves the object, it creates a new option in the select tag. The user selects something from the select tag to go back to that object.
The autofocus is always on option[0] until they selected something else even if they created a new object/option so if they wanted to pick the first thing, but was on the second or third the user would have to click on another option first then click on the one they want.
What I want is that it doesn't focus on any of the options so that they could click on option[0] from the beginning regardless of whether they've selected anything from the dropdown.
Seems like a lot of work to workaround this issue, instead of changing one of your requirements. You say that the index corresponds to an index into an array of objects. Why can't you have the first option blank or "Select...", and then simply subtract one for your lookup into the array?
Or, have the values correspond to the array index, or use custom data attributes to store the array indexes? Seems like any of these would be easier than trying to force a consistent behavior for an unsupported functionality across multiple browsers.
A Select box always has one of its options selected (unless it doesn't have any options). You might need to use a different event (onclick, perhaps) and test the value to see if it has changed.
You can add a default empty selected option with:
<option selected="selected" disabled="disabled" hidden="hidden" value=""></option>
The select is empty by default, with the void option not selectable in the options list.

<option> tag, display:none and jquery

I have a div that is being used as a dialog with jQuery's .dialog(). This div has a select box with options. The options the user has already selected are displayed on the main page. They can remove options from the main page and can open the dialog multiple times to add more options.
I populate the select box with all possible options on page load, but then when I open the dialog box I use jQuery's hide() to hide the options that the user has already selected and are displayed on the main page. This adds the CSS display:none; to the element in question, which IE ignores on <option> tags and displays anyway.
I can easily enough call remove() instead and remove it from the DOM. However, if the user selects some options, them removes them on the main page, then opens the dialog again to select more options, the options are no longer in alphabetical order, the options that were removed from the DOM and put back in it are now at the bottom since I used .append().
Is there any way to get IE to hide <option> tags? Or is there a better way to do this? Or is there a way to insert in alphabetical order simply?
If you need to remove it from the DOM, you could store the options in an array. One array (or object) for each option list. Then removing options from the list itself is reversable. You can always rebuild the select menu again from the array. Just populate the array once the dom-ready event fires.
Demo online: http://jsbin.com/avuru
$(function(){
// Define variables to be used throughout this code
var colors = [];
var list = $("select[name='colors']");
var btnRestore = $("button[name='restore']");
var btnRemove = $("button[name='remove']");
// Cycle through each option, adding its value and text to our collection
$("option", list).each(function(i, o){
colors.push({ 'key':$(this).val(),'val':$(this).text() });
});
// Remove any remaining options, and add collection back into dropdownlist
$(btnRestore).click(function(){
$("option", list).remove();
for (var i = 0; i < colors.length; i++) {
$("<option>").val(colors[i].key).text(colors[i].val).appendTo(list);
}
});
// Remove first option from list - used to test 'Restore' functionality
$(btnRemove).click(function(){
$("option:first", list).remove();
});
});
I would clone the list of options before modifying it and keep the original around. That way you can reinsert it clean by replacing the modified one with the orignal.

Categories