If I have only one option in my dropdownlist, I need to select this option as default. How can I do this using jQuery?
I think you are new to SO, the usual procedure here is to provide some code of your own efforts on the matter before posting. That said, this is simple JQuery:
Edit to fit new specifications:
if($("#select_id option").length == 2){ //if there are exactly 2 options in the select element
$("#select_id option:nth(1)").attr("selected",true); //take the second option (element 0) inside the element with id "select_id" and set the selected attribute.
} //I think we do not need an else if any other thing will select the first option by default
Anyway, first option should be selected by default.
<select id="select_id">
<option value=1>First option is selected by default</option>
</select>
<!--adding proof that it is selected-->
<script>
$(function(){
alert($("#select_id").val()); //this will alert 1, since is the value of my first option
});
</script>
Related
For example i have 2 records pre-selected as seen in screenshot below.
I noticed that aria-selected="true" for selected ones.
How can I find it by title and remove/reset it so it will not be part of current selected items.
Thanks in advance.
I think this should work:
$('#idSelect option[title="myTitle"]').first().remove();
Hope it helps.
select2 has link to particular <select> element in DOM. So, first you need to change select option, and then trigger change event of select2
For change option text you can like this
<select id="mySelect">
<option value="option1">Text</option>
</select>
var $select2 = $("#mySelect").select2();
$('#mySelect option[value="option1"]').text = 'Another text';
And then trigger change event for select2:
$select2.trigger("change");
Remove item
$('#mySelect option[value="option1"]').remove();
$select2.trigger("change");
Select one option
$select2.val("option1").trigger("change");
Select multiple options
$select2.val(["option1", "option2"]).trigger("change");
Remove one from selected
If you need remove one option from already selected, you need to get selected options, remove one, and set new options to select2.
var sel = $select2.val(); // array
sel.splice(sel.indexOf("option1"), 1);
$select2.val(sel).trigger("change");
I have multiple selects on my page, each has multiple options.
However, If I select an option then the attribute selected of the option is not updating. Shouldn't this happen automatically?!
Example:
<select id="browsers">
<option value="Firefox">Bing</option>
<option value="InternetExplorer" selected="selected">Internet Explorer</option>
<option value="Chrome">Chrome</option>
</select>
By inspecting the DOM with the developer console, you should see, that the selected attribute is not changing even after selecting another option.
However I found a workaround. To solve this issue we can use this code:
$(document).on("change","select",function() {
$("option[value=" + this.value + "]", this)
.attr("selected", true).siblings()
.removeAttr("selected")
});
Example:
$(document).on("change","select",function() {
$("option[value=" + this.value + "]", this)
.attr("selected", true).siblings()
.removeAttr("selected")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="browsers">
<option value="Firefox">Bing</option>
<option value="InternetExplorer" selected="selected">Internet Explorer</option>
<option value="Chrome">Chrome</option>
</select>
This works kind of. However, If I select another option than the default option, e.g. Chrome and reload the page, then the option Chrome is still selected even after reload, BUT the selected attribute still points to Internet Explorer!
Which is the best approach to solve this?
My idea is to run through all selects on $(document).ready() and select the option where the selected attribute points to.
But why does this all not happen automatically?
Is it a bug or a feature?
The selected attribute defines if an element should be selected on pageload. If you post a form with a select element, the chosen option will be the one posted, regardless of the initial selected element.
What do you need the selected-attribute for in your case?
Edit: Based on your comments I made a fiddle
Fiddle 1 https://jsfiddle.net/q3fpafov/1 selects like you want
Fiddle 2 https://jsfiddle.net/bge9bsa7/2/ only files available for a chosen language are shown
I hope it's somewhere along the lines of what you're looking for.
The reason for your option still being selected when you reload is browser based. But the selected-attribute does nothing for the usability of the option. Also, it won't change because you don't change the way the HTML-element itself is being rendered (at page load)
Note: selected="selected" is not necessary, simply selected attribute will work as well.
When present, select attribute specifies that an option in select should be pre-selected when the page loads.
Also, the pre-selected option will be displayed first in the drop-down list.
Those 2 should be only effects of the selected attribute.
Note the keywords - when the page loads. He is either there or not when a browser loads the page.
If you wanna make it dynamic you need to use JavaScript. What do you wanna achieve with this? Having attribute selected on the correct element when reloading page or programmatically select the correct element after the page has been loaded?
If you simply wanna make element selected there is easier way trough either value:
jQuery("#browsers[value='the value of the one you like']").attr('selected','selected');
Or by index (mind, indexes start at 0 not 1):
document.getElementById("browsers").selectedIndex = "2";
The problem before was, that after selecting an option and reloading the page, the option was remembered during page reload, even though the attribute selected pointed to another option.
I solved it by calling the function below everytime. The function finds out which is the truly selected option, even after page reload.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="downloadSelect" id="select_179">
<option value="-">Please select</option>
<option value="link_2748" selected="selected">Deutsch</option>
<option value="link_2749">Chinese</option>
</select>
<button onclick="return showSelectedOption('select_179');">Show Option Text</button>
<script>
function showSelectedOption(pSelectID)
{
var text;
$("#"+pSelectID)
.find("option")
.each(function(){
if ($(this).prop("selected")) {
text = $(this).text();
}
});
console.log(text);
}
</script>
You can check the value of the select when it changes to see what it has been changed to.
var select = document.getElementById('browsers');
select.addEventListener('change', function(e) {
localStorage.setItem('browser', this.value);
});
var browser = localStorage.getItem('browser');
if (browser) {
select.value = browser;
}
<select id="browsers">
<option value="Firefox">Firefox</option>
<option value="InternetExplorer" selected="selected">Internet Explorer</option>
<option value="Chrome">Chrome</option>
</select>
edit
So, I missed the part about storing the value so that it persists when the page is reloaded, and depending on the OP's use case, I would suggest using localStorage to save the value when it is changed, and to read from it when the page is reloaded.
I have edited the snippet to reflect this (code is simplified)
I am showing option with chosen plugin and latter add option to it.
I am trying below
<select id='one'>
<option>a</option>
<option>b</option>
</select>
and calling chosen plugin
$('#one').chosen();
it working fine now i am remove chosen part and adding new option to select box
$('#one').append(' <option>g</option>');
$('#one').addClass('abc').attr('id', '');
$('#one_chosen').remove();
$('.abc').attr('id', 'myid');
$('#myid').chosen();
as you can see that i have added id by class and calling chosen() on it but this time its not working. And i can not keep id one in select box if there is no chosen
jsfiddle
You must clone the element in order to make it work:
$('#one').chosen();
$('#one').find('option:first').remove();
$myid = $('#one').clone().attr('id', 'myid').insertBefore('#one');
$("#one, #one_chosen").remove();
$myid.show().chosen();
Updated demo
i am not sure i understand your question. But you can refresh chosen with .trigger("chosen:updated"); i.e you can do something like
$('.select-chosen').chosen();
$('#one').addClass('abc').attr('id', '');
$('.abc').attr('id', 'myid');
$('.select-chosen').trigger("chosen:updated");
Update:
Ideally, if you want to fully change the select chosen, it is better to just hide and show new select chosen. In case, if you want to add or remove option from select and want to gain fully functionality of chosen you can do it easily with
// add custom option
$(".select-chosen").append('<option>Custom Option</option>');
// remove existing option
$(".select-chosen option[value='a']").remove();
Refer : http://jsfiddle.net/qubkhtsc/5/
I am using some jQuery to populate various dropdowns. I was able to get the jquery to show current value as the first option.
However, I need it to not only show as the first option, but as the currently selected option so that the selection doesn't appear twice in the dropdown.
As shown in the images below, you see the current value is Target. But after clicking the dropdown button, Target is listed twice:
Here is what the current jQuery looks like:
$(function()
{
$eexist = $(this).attr('data-exist');
$('#eexist option:first').val($eexist).text($eexist);
}
Which goes into this modal form dropdown select:
<div id="editCustModal">
<form id="editCustForm" name="editCustForm">
<label for="eexist">Existing/Target</label>
<select class="form-control" id="eexist" name="eexist">
<option></option> // keeping this or not does nothing
</select>
</form>
</div>
The value and the text are the words Target and Existing.
To reiterate, if the current value is Target, then when you click on the dropdown, you should only see Target as the currently selected item AND only see it once.
If you want to select first option then below is the code:
$('select option:first-child').attr("selected", "selected");
But if you want to select the current value then below is the code:
$('#eexist option:first').val($eexist);
this should only work if $eexist exists as value in dropdown
Since you didn't provide much so it's hard to tell..At least provide a jsfiddle link when you ask a question
Do it this way...
$(document).ready(function(){
$("#myselect").change(function(){
var toR = $('<div>').append($('#myselect option:selected').clone()).html();
console.log(toR);
$("#myselect option:selected").remove();
$("#myselect").html(toR+$("#myselect").html());
});
});
Working Fiddle
I'm trying to get the HTML code as a string with the attribute updates.
I've a select tag, whose options I update using JavaScript.
By default, a first option is selected using the HTML attribute selected="selected".
If I unset selected from the first option using option1.selected = false and set option2.selected = true for the second option, and then call the outerHTML of a select, I get
<select>
<option selected="selected">one</option>
<option>two</option>
<option>three</option>
</select>
As you can see, selected attribute is still on the first option, while it has been moved to the second option. The expected result is
<select>
<option>one</option>
<option selected="selected">two</option>
<option>three</option>
</select>
Here's an example http://jsbin.com/adAbAMe/2/edit?html,js,console,output (click run with js to get a result) which shows, that if a selected attribute has been changed, it doesn't change in the HTML code.
But I need to get the final HTML from outerHTML with the successful attribute updates, because if I move this select somewhere I won't get any updates I've made before using JavaScript.
Is there any method to get the HTML as a string with the real attributes values?
The selected attribute isn't automatically updated, but you can set it to be removed and added to the proper elements.
//remove "selected" from first
if (i==0) {
option.selected = false;
option.removeAttribute("selected");
}
//add "selected" to second
if (i==1) {
option.selected = true;
option.setAttribute("selected", "selected");
}
Here's a working fiddle.
You can use
option.setAttribute('selected', 'selected');
and
option.removeAttribute('selected');
Try
$('button').click(function () {
console.log($('select').prop('outerHTML'))
})
$('select').change(function(){
$(this).find('option[selected]').removeAttr('selected');
$(this).find('option:selected').attr('selected', 'selected');
})
Demo: Fiddle
From the DOM Specification:
selected of type boolean
Represents the current state of the corresponding form control, in an interactive user agent. Changing this attribute changes the state of the form control, but does not change the value of the HTML selected attribute of the element.
(emphasis mine)
To get the effect you're looking for, you want option.setAttribute('selected', 'selected'), though you'll also need option.removeAtrribute('selected') on the other options.