I'm having trouble getting and setting the "simplified" selected value of a select using jquery or vanilla js. i.e. <option value="foo" selected> vs. <option value="foo" selected="selected">.
Below only works if the option is selected like below, but all the programmatic ways to set the value of a select option I have tried result in <option value="value" selected="selected">. I need to set and get the simplified selected.
const sortBySelect = document.getElementById('sortBy');
let currVal = sortBySelect[sortBySelect.selectedIndex].value;
console.log(currVal);
<select id="sortBy">
<option value="title" selected>Title</option>
<option value="date">Date</option>
<option value="name">Name</option>
</select>
I've tried these and all the permutations I could find on Stack:
$(`#sortBy option[value='${storageValue}']`).attr('selected', true);
$(`#sortBy option[value='${storageValue}']`).prop('selected', "selected");
Instead of using attr() or prop() functions, just directly set the select value by using the val() function
$('#sortBy').val('${storageValue}');
Related
I have a multiple select where each option has a class set to it.
Depending on the class i can pre-select all options with a specific class so the user doesn't have to select them all by himself.
So far it works fine, till to the point where i manually select one option by clicking on it. From this point on the pre-selects seem to don't work anymore. BUT only the visuals don't work anymore, the options still get the 'selected="selected"' applied to them. Also .val() on the select returns all values selected by the pre-selector. So in the background everything works fine, but the user can't see that it worked.
Here's my select:
<select class="form-control d-block w-100 col-8 col-xl-12" id="brand-select" name="brands" size="15" multiple>
<c:forEach var="brand" items="${brands}">
<option class='<c:choose>
<c:when test="${brand.isCompanyBrand()}">COMPANYBRAND</c:when>
<c:otherwise>FOREIGNBRAND</c:otherwise>
</c:choose>' value="${brand.brandCode}">${brand.description}
</option>
</c:forEach>
</select>
And here's one of the selectors:
selectCompanyBrands.addEventListener("click", function()
{
$("#brand-select option").attr("selected", false)
$("#brand-select option.COMPANYBRAND").attr("selected", true);
}, false);
I'm currently out of ideas what i can do to resolve this problem.
Read through this in jquery doc and I quote for specificity:
Attributes vs. Properties
The difference between attributes and properties can be important in
specific situations. Before jQuery 1.6, the .attr() method sometimes
took property values into account when retrieving some attributes,
which could cause inconsistent behavior. As of jQuery 1.6, the .prop()
method provides a way to explicitly retrieve property values, while
.attr() retrieves attributes.
Jquery, or rather its later versions, clearly distinguishes between attributes and properties. So the simple rule is that if you want to set a property (something that is related to a user action like a form element) use #prop() and otherwise use #attr().
Here you should be using #prop like this:
selectCompanyBrands.addEventListener("click", function() {
$("#brand-select option").prop("selected", false)
$("#brand-select option.COMPANYBRAND").prop("selected", true);
}, false);
Here is a sample working code to help you. I have used prop():
$(document).ready(function() {
$("select option").prop("selected", false)
$('select option.someclass').prop('selected', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="multiple" size="15">
<option class="someclass">some option</option>
<option class="someclass">some option</option>
<option class="newclass">some option</option>
<option class="someclass">some option</option>
<option class="someclass">some option</option>
<option class="newclass">some option</option>
<option class="newclass">some option</option>
<option class="newclass">some option</option>
<option class="someclass">some option</option>
<option class="someclass">some option</option>
<option class="someclass">some option</option>
</select>
So here is the thing:
I have a java app and it creates a group of selects based on a db. Also, if it happens that an element (let's call it product) has that value, it print the option with the selected attribute.
<select>
<option value="1">text1</option>
<option value="2" selected>text2</option>
<option value="3">text3</option>
<option value="4">text4</option>
<option value="5">text5</option>
</select>
<select>
<option value="1">text1</option>
<option value="2">text2</option>
<option value="3">text3</option>
</select>
<select>
<option value="1">text1</option>
<option value="2">text2</option>
</select>
What i want to do is set in blank (set a value of zero) to the selects that not has an element with a selected value.
If you know another form to set to blank a list (diferent from put a default empty element in every select), please let me know.
The way to do this without an empty option, is to set the selectedIndex to -1
$('select:not(:has(option[selected]))').prop("selectedIndex", -1);
FIDDLE
Demo $('option:not(:selected)').val(0); use :not and :selected and set the value to 0
I have html code that looks like this:
<select id="invoice_line_items_attributes_0_product_id" class="select required form-control" name="invoice[line_items_attributes][0][product_id]">
<option value=""></option>
<option value="34" data-price="123.0">asdsad</option>
<option value="35" data-price="123213.0">asd</option>
</select>
<select id="invoice_line_items_attributes_1_product_id" class="select required form-control" name="invoice[line_items_attributes][0][product_id]">
<option value=""></option>
<option value="31" data-price="1223.0">asdsad</option>
<option value="32" data-price="12333213.0">asd</option>
</select>
And now I want to iterate through all this selects and when one of this change this value alert this date-price attribute. I trying to do this with the following code:
$('[id*="product"]').each ->
$(this).change ->
alert $(this).attr("data-price")
But It gaves me undefined instead of this data-price value.
Three things:
1) You do not need to iterate over select element individually and then bind the even. Selector will do that on its own for matched elements.
2) You need to find selected option and then get data price value.
3) use .data() instead of using .attr() to get data attribute values.
Use:
$('[id*="product"]').change(function(){
alert($(this).find('option:selected').data('price'));
});
Working Demo
That is because your select doesn't have data-attr, I think you want the selected options data-attr.
And to get data-attributes jquery provides .data function.
do like bellow.
$('[id*="product"]').change(function(){
alert($(this).find(':selected').data('price'));
});
DEMO
I've got a grid with dropdown in every row and I need to render it's state from DB.
So I've got dropdowns defined like that with selected option specified for preselecting the value from DB.
<select id='selectId'>
<option value='1'>Option 1</option>
<option value='2' selected='selected'>Option 2</option>
<option value='3'>Option 3</option>
</select>
The problem is in that when I change the value of a dropdown defined like that in a browser it changes on UI but selected attribute don't move and stays where it was.
So when I then call $("#selectId").val() I get the old one value.
What's the appropriate way to initialize dropdown control and then have an ability to freely change it's value in browser or by jQuery?
This seems to be working fine (Firefox on Ubuntu):
HTML
<select id='selectId'>
<option value='1'>Option 1</option>
<option value='2' selected='selected'>Option 2</option>
<option value='3'>Option 3</option>
</select>
JS
$('#selectId').change(function() {
var opt = $(this).find('option:selected');
console.log([opt.val(), opt.text()]);
});
var opt_sel = $('#selectId option:selected');
opt_sel.val(99);
opt_sel.text('Changed option');
If you select the options, you'll see that it will print the changed version. Working example:
http://jsfiddle.net/vm4Q8/
Hope this helps.
It should work fine. May be you are not setting it correctly.
You should pass the value of the option to val() method to select it.
E.g $('#selectId').val('1'); will set first option as selected and afterwards calling $('#selectId').val() will give you 1 and not 2.
Here is the working example http://jsfiddle.net/3eu85/
You can get the val of the option selected, instead of the select
$('select#selectId option:selected').val();
Docs: http://api.jquery.com/val/
Which browser are you trying this in? Your code looks fine to me, and appears to be working in this jsFiddle.
please use this code instead,
$('#selectId option:selected').val();
I have the next select:
<select name="priority" id="priority" class="update_priority">
<option value="root" label="Without parent">Without parent</option>
<option value="72" label="Rank3">Rank3</option>
<option value="71" label="Rank1">Rank1</option>
<option value="67" label="Rank2">Rank2</option>
<option value="64" label="Rank4">Rank4</option>
</select>
In JS i have a variable with something value. For example:
selected = 71;
Now, with help of jQuery I want to make option selected with this value(in our example 71).
you don't need jquery for this. you can just use plain old javascript:
document.getElementById("priority").value = "71";
But if you still want to with jquery you can do the same thing:
$("#priority").val("71")
EDIT: Here is an example. You can comment out either one you want to see the other one work:
http://jsfiddle.net/BupWA/