How to add "selected" in option attribute using Javascript or jQuery? - javascript

Below is code for select option and generate using php from database and i try to add selected="selected" to value="4" using jQuery or any javascript:
<select id="countryselect" name="country">
<option value="1">Afghanistan</option>
<option value="2">Albania</option>
<option value="3">Algeria</option>
<option value="4">Malaysia</option>
<option value="5">Maldives</option>
</select>
i try to refer this post but still can't .. below is my current script :
<script>
localStorage.setItem("Select1", "Malaysia");
$('#countryselect').find('option').each(function(i,e){
if($(e).val() == localStorage.getItem("Select1")){
$('#countryselect').prop('selectedIndex',i);
}
});
</script>
thanks.

The selected attribute is a boolean attribute, its presence sets the value of the related DOM property to true. If the attribute is absent, the value of the selected property is false.
If an option has the selected attribute, then when the page is first loaded, or the form the control is in is reset, that option will be the selected option.
If the option's selected property is set to true, then that option will be selected. However, if the form is reset, the default selected option will be selected (i.e. the one with the selected attribute, or the first option, or none).
To set the selected attribute (i.e. make the option the default selected option):
var select = document.getElementById('countryselect');
var option;
for (var i=0; i<select.options.length; i++) {
option = select.options[i];
if (option.value == '4') {
// or
// if (option.text == 'Malaysia') {
option.setAttribute('selected', true);
// For a single select, the job's done
return;
}
}
Note that this may not make the option the currently selected option, it will just add the selected attribute. To make sure it's selected (if that is what is required), the also set the selected property to true (see below).
Note that the second argument to setAttribute is supposed to be a string that is used to set the attribute's value. However, the selected attribute doesn't have a "setable" value, so the second argument is ignored (e.g. even false will still set the attribute and make the option the default selected option). That causes some confusion. :-)
To set the selected property (i.e. just make the option the current selected option):
var select = document.getElementById('countryselect');
var option;
for (var i=0; i<select.options.length; i++) {
option = select.options[i];
if (option.value == '4') {
// or
// if (option.text == 'Malaysia') {
option.selected = true;
return;
}
}

This should work simple, $("#countryselect").val('4')​
It will automatically set selected=selected
Demo: http://jsfiddle.net/muthkum/zYRkC/

localStorage.getItem("Select1") will return Malaysia and $(e).val() will return 1,2...5 in each loop. So your condition will never be true. Instead use
<script>
localStorage.setItem("Select1", "4");
$('#countryselect').find('option').each(function(i,e){
if($(e).val() == localStorage.getItem("Select1")){
$('#countryselect').prop('selectedIndex',i);
}
});
</script>

As of jQuery 1.6 "To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method."
$("#countryselect option[value=4]").prop("selected", "selected")

Just try
$("#countryselect").val('4')
//OR
$("#countryselect option").val('4')​.attr("selected", true)​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Check this FIDDLE

$('#countryselect > option[value *= "4"] ').attr('selected',true);
this will work

Related

Get new value selected in ng-option on change in a multiple select

I have in my .html page a dropdown list as a multiple select:
<select class="form-control"
multiple
ng-model="filter.types"
ng-change="onChange()"
ng-options="option for option in filterOptions.types">
{{option}}
</select>
In my controller, I have the onChange function:
$scope.onChange= function(newOptionSelected){
console.log(newOptionSelected);
}
Here I want to get the current item being added to the selected filter.types.
How could I achieve this?
If it was a single select I could pass simply the ng-model to the onChange function.
<select class="form-control"
ng-model="filter.type"
ng-change="onChange(filter.type)"
ng-options="option for option in filterOptions.types">
{{option}}
But how to achieve this with a multiple select?
Any ideas? :)
I want to delete all the elements selected if the option added is "All". And if the "All" option is selected, then when I select the next item I need to remove only the "All" option.
You cannot achieve this using ng-change because you need to keep track of what was the last selected option. You have to $watch your filter.types which is an array and then based on new value and old value you can decide what to do.
$scope.$watch('filter.types', function(newVal, oldVal) {
if (newVal.length > oldVal.length) { //Updating only on selecting
var lastSelectedOption = [];
lastSelectedOption = $scope.diff(newVal, oldVal);
if (lastSelectedOption[0] == 'All') {
var i = newVal.length;
while (i--) {
if (newVal[i] != 'All') {
newVal.splice(i, 1); //Deleting other options
}
}
} else if (newVal.indexOf('All') > -1) {
newVal.splice(newVal.indexOf('All'), 1); //Deleting 'All' option
}
}
});
Working JSFiddle link for your reference. Good luck!
You can check documentation of angular to get answer to this question. https://docs.angularjs.org/api/ng/directive/select
Plunker:- https://plnkr.co/edit/rhX9AiAhPfHXB2c2BUZF?p=preview

jQuery - if select option value equal with a data add class

I have a select box with 3 option, and a div with 3 that they has data attribute.
now i want each option that has selected=seclected and also value (number) equal with a data then add class to
for example:
if option selected / and value = with data:
<option value="2" selected="selected">
do (add class):
<a class="menuitem active" data="2"></a>
JSFiddle
$("#myselect option").each(function(){
var num = $('.menucontainer').children('a.menuitem').attr('data');
if($(this).is(':selected').val()==num){
$('.menucontainer').children('a.menuitem').addClass('active');
}
});
});
You had many small mistakes. Like
1.) Jquery was not included in fiddle.
2.) .is returns a boolean value, and you were doing $(this).is(':selected').val(). You should be doing $(this).is(':selected') && $(this).val().
3.) There was }); extra in the end.
And I think iterating other way arround will be better. Like bellow
$('.menucontainer .menuitem').each(function(){
if($(this).attr('data')==$('#myselect :selected').val())
$(this).addClass('active');
})
DEMO

Deselect option before selecting option through javascript

I have a problem where I have multiple select buttons in a form and onclick on each button should select different options of the same selectbox. The below code works fine if I pass a value while onclick but the old value is retained if no value is passed instead of setting it to nul.
Tried formname.reset() before selecting an option to refresh, but this is not selecting any value at all.
For eg, select1 is clicked and first value of select box is selected. After clicking select2 instead of resetting itself to null, it shows the old value (1). Select3 works fine again selecting the second value of the select box.
<script>
function editvalues(arr)
{
$('#parent_id option[value='+arr+']').attr('selected','selected');
}
</script>
Select1
Select2
Select3
<select id="parent_id" name="parent_id">
<option value=''>Select Any</option>
<option value='1'>First</option>
<option value='2'>Second</option>
</select>
Se the value to '' in case no argument is passed.
$('#parent_id option[value='+(arr || '')+']').attr('selected','selected');
In the above code, (arr || '') will return arr if it is passed to the function. Else it will return '' (which happens to be the value of the <option> that represents no selection).
In your case using val method will solve the issue:
function editvalues(arr) {
$('#parent_id').val(arr);
}
However you should consider using jQuery more rather then old-school inline handlers approach. For example:
Select1
Select2
Select3
JS:
$('.select').on('click', function() {
var val = $(this).data('value');
$('#parent_id').val(val);
});
Demo: http://plnkr.co/edit/iuFEjBKkQZZEpk8keaqx?p=preview
You can deselct any selection 1st:
function editvalues(arr)
{
//deselect 1st
$("#parent_id option:selected").prop("selected", false)
//then select passed in value
$('#parent_id option[value='+arr+']').attr('selected','selected');
}

Changing selection in a select with the Chosen plugin

I'm trying to change the currently selected option in a select with the Chosen plugin.
The documentation covers updating the list, and triggering an event when an option is selected, but nothing (that I can see) on externally changing the currently selected value.
I have made a jsFiddle to demonstrate the code and my attempted ways of changing the selection:
$('button').click(function() {
$('select').val(2);
$('select').chosen().val(2);
$('select').chosen().select(2);
});
From the "Updating Chosen Dynamically" section in the docs: You need to trigger the 'chosen:updated' event on the field
$(document).ready(function() {
$('select').chosen();
$('button').click(function() {
$('select').val(2);
$('select').trigger("chosen:updated");
});
});
NOTE: versions prior to 1.0 used the following:
$('select').trigger("liszt:updated");
My answer is late, but i want to add some information that is missed in all above answers.
1) If you want to select single value in chosen select.
$('#select-id').val("22").trigger('chosen:updated');
2) If you are using multiple chosen select, then may you need to set multiple values at single time.
$('#documents').val(["22", "25", "27"]).trigger('chosen:updated');
Information gathered from following links:
1) Chosen Docs
2) Chosen Github Discussion
Sometimes you have to remove the current options in order to manipulate the selected options.
Here is an example how to set options:
<select id="mySelectId" class="chosen-select" multiple="multiple">
<option value=""></option>
<option value="Argentina">Argentina</option>
<option value="Germany">Germany</option>
<option value="Greece">Greece</option>
<option value="Japan">Japan</option>
<option value="Thailand">Thailand</option>
</select>
<script>
activateChosen($('body'));
selectChosenOptions($('#mySelectId'), ['Argentina', 'Germany']);
function activateChosen($container, param) {
param = param || {};
$container.find('.chosen-select:visible').chosen(param);
$container.find('.chosen-select').trigger("chosen:updated");
}
function selectChosenOptions($select, values) {
$select.val(null); //delete current options
$select.val(values); //add new options
$select.trigger('chosen:updated');
}
</script>
JSFiddle (including howto append options):
https://jsfiddle.net/59x3m6op/1/
In case of multiple type of select and/or if you want to remove already selected items one by one, directly within a dropdown list items, you can use something like:
jQuery("body").on("click", ".result-selected", function() {
var locID = jQuery(this).attr('class').split('__').pop();
// I have a class name: class="result-selected locvalue__209"
var arrayCurrent = jQuery('#searchlocation').val();
var index = arrayCurrent.indexOf(locID);
if (index > -1) {
arrayCurrent.splice(index, 1);
}
jQuery('#searchlocation').val(arrayCurrent).trigger('chosen:updated');
});

"defaultValue" property for <select>?

Javascript has textObject.defaultValue=somevalue for retrieving the default value (stored value from page load) of an input even if you wipe the input and replace the contents, you can still get the default back. Like this:
// in the html page
<input id="addr1" type="text" value="21 Oak St." />
// the jquery
myInput = $("#addr1"); // the input, default value on page load = 21 Oak St.
$(myInput).val('51 New St'); // wipe default and set new
// alerts 21 Oak St
alert($(myInput).val($(myInput)[0].defaultValue));
How do you accomplish this on a select?
selectedIndex is boolean, not the value, so that does not work.
Thanks!
You probably want to look at the "defaultSelected" attribute of "option" elements.
Initially, "defaultSelected" will be true if the original HTML of the option tag had an explicit "selected" attribute. You can change that by setting the attribute on option tags with Javascript after the page has loaded, in response to whatever conditions you like.
This is the jquery that works for me:
$('select[name="name_of_select"] option[selected]').val()
with Jquery we can do sth like this :
$('select[name="type_id"] option').map(function()
{
if($(this).attr('defaultSelected')==true) return this
}).get(0).value;
This will return the default Selected option value
:)
I used the following to loop through a forum, check their default values and their current values.
if the script comes a cross a single selectbox it will loop through the children on the selectbox.
oFormObject = document.forms[0];
for(i=0; i<oFormObject.elements.length; i++)
{
oValue = oFormObject.elements[i].value;
oType = oFormObject.elements[i].type;
if(oType=='select-one') {
for(k=0; k<oFormObject.elements[i].children.length; k++)
{
if(oFormObject.elements[i].children[k].defaultSelected==true){
oformElement = oFormObject.elements[i].children[k].value;
}
}
}else{
oformElement = oFormObject.elements[i].defaultValue;
}
console.log(oformElement);
console.log(oValue);
console.log(oType);
}
there may be multiple "selected" option elements, in that case pick the first if no other requirements are set. #Pointy tip is correct but be aware that the "defaultValue" property can be overwritten by other code in the same page. If it were read-only it would be more useful :-)
I found a shortest way to do this :
$('select#myselect').find('option[defaultSelected]');
I run this on page load to manually set the defaultValue for Select boxes.
// Set a default value property on selectboxes (for reverting)
$('select').each(function(index,ele) {
var origvalue = $(this).val(),
defaultvalue = $(this).prop('defaultValue');
// If the default value hasn't already been set for this selectbox
if(!defaultvalue) {
$(this).prop('defaultValue', origvalue);
}
});
The simplest way to do this is:
$('#selectbox option').prop('selected', function() {
return this.defaultSelected;
});

Categories

Resources