I needed help regarding selection copying, as I know nothing about it. Here's my problem: I need to select a state from one select, and then have it automatically select the same state in another select. But my values are different for each select, as the info will be processed to the server (otherwise, there wouldn't be a problem, because I wouldn't need to copy from one select to the other). Here is my format:
<select name="state" size="1" id="stateSelect">
<option value="AL">Alabama</option>
<select>
<select name="state" size="1" id="stateSelect2">
<option class="AL" value="Alabama">Alabama</option>
</select>
And this is my current jQuery that I've pieced together from all over the internet (that obviously doesn't work):
$(function(){
$("select[name*='state']").change(function(){
$("#stateSelect2").children(':selected').hasClass( $("#stateSelect").val() )
})
})
So, what I need is to be able to do is copy the value selected by "stateSelect", and select the value of "stateSelect2" by the class that has the value of the selected option of "stateSelect". I don't know how easy or hard this is to do, but I sure would appreciate any and all help with this issue. if you use JSFiddle, bonus points to you. Thanks!
$('#stateSelect').on('change', function(){
var v = $(this).val();
$('#stateSelect2 .'+v).prop('selected', true);
});
http://jsfiddle.net/dipser/9ca0eL1d/
Something like this should suffice:
$(document).ready(function(){
$('#stateSelect').on('change', function(){
var val = $(this).val();
if(val.length > 0 && $('#stateSelect2 option.' + val).length > 0) {
$('#stateSelect2 option.' + val).attr('selected', 'selected');
// could also use .prop() here instead of attr
// which would be .prop('selected', true);
}
});
});
The if statement makes sure that the selected option has a value and also exists in the second select.
JSFiddle Demo
Related
I have a HTML form with the following select element in it:
<select class="form-control" onchange="$('form#filter').submit()" id="sort" name="sort">
<option value="0" selected="selected">A - Z</option>
<option value="1">Z - A</option>
</select>
The issue is that when I select a different option, the HTML doesn't update and set the option I chose as the selected option.
I have absolutely no idea why it isn't updating and I've been at it for hours now.
This is the function that is bound to the submit event on the form in case you need it:
$("form#filter").on("submit", function(evt)
{
var form = $(this);
var target = $("div#bands");
var url = form.attr("action") + "/" + form.find('option[selected]').val();
console.log(url);
$.get(url).done(function(data)
{
target.html(data);
});
evt.preventDefault();
});
Change
form.find("option[selected]").val()
to
form.find("option:selected").val()
or:
form.find("select").val()
or:
$("#sort").val()
The selector option[selected] doesn't find the option that's currently selected, it finds the option that has the selected attribute in the DOM (this is normally the one with the selected attribute in the HTML, although it's possible to change it using Javascript).
The accepted answer is incorrect. Here is a correct solution (tested on latest JQuery and Bootstrap at time of writing):
$("#mySelect").find("option:selected").val();
Thanks to Barmar for the inspiration, though only 1 of the 4 suggestions works, and only by accident. But I adapted that to log out the correct value attribute for the currently selected option. (The selected state of the initial option does not update when using the dropdown, see Chris O'Kelly's comment.)
How do I get all selected options from a <select> using jQuery?
<select id="mySelector" ... >
<option value="1" selected="selected">option1</option>
<option value="2" selected="selected">option2</option>
<option value="3">option3</option>
</select>
I tried $('#mySelector').find(":selected"). It returns [].
But if my options have only selected property instead of selected="selected" $('#mySelector').find(":selected") returns the correct results.
Am I doing something wrong?
There is little difference between attributes and properties.
Attributes does have assigned values like attr="value".
While properties are just a property which does not have any value assigned like checked, selected etc..
so to answer your question i would say then you have to use .map() iterations to create array:
var arr = $('#mySelector option').map(function(){
return $(this).attr('selected') === "selected"
}).get();
You can try both, one after another:
$('#mySelector').find(":selected")//animate...
$('#mySelector').each(function(){
if ($(this).attr('selected') === "selected"){
//animate...
}
}
Setting the attribute selected="selected" will work as a pre-selected option and will be displayed first in the drop-down list.
However, I guess the user chooses something and you want to get that value.
$('select option:selected').each(function () {
alert($(this).val());
});
Iterate through each one in the select element and with the pseudo selector :selected just get it's value.
JsFiddle demo
Note: If you instead want the text, not the value, use .text() instead of .val()
I mean, I feel like a total idiot, but I just can't seem to get this right, even after searching for almost two hours.
This select is followed by a hidden text field:
<select name="location_id" class="select green-gradient" single>
<option value="2">New York</option>
<option value="3">London</option>
<option value="4">Singapore</option>
<option value="5">San Francisco</option>
<option value="6">Milan</option>
</select>
<input type='text' name="selected_location_id" class="hidden" value="">
// I usually use this code for checkboxes. It toggles the contents of a hidden text box. I understand that checking a select's values is different. But I can't seem to get it right.
$(document).ready(function(){
$('.switch').change(function( ){
if($(this).next().val() == 1){
$(this).next().val(0);
} else {
$(this).next().val(1);
}
});
})
// I've tried this: but it's not useful since I need to do this for all selects on the page. And it still doesnt update the hidden text box.
$(document).ready(function(){
$('.select').change(function( ){
var selectedValue = $(this "option:selected").val();
$(this).next().val(selectedValue);
});
})
// Maybe I'm just tired. But it's time to ask for help. Thanks in advance.
I think it should be
$('select').change ///(without the dot)
not
$('.switch').change
neither
$('.select').change
var selectedValue = $("option:selected").val();
Works in a jsfiddle by taking the "this" out.
Within the listener, this references the element. You can also get the name of the hidden element from the select element's name, so if they're in a form:
this.form['selected_' + this.name].value = this.value;
and you're done without a single function call.
I have a select element that allows for multiple selections. I'd like to display the selected values in another part of the page (in a div or something) as the user makes changes to what is selected.
Is the only way of doing this to iterate over the "options" and check if "selected" is true? this would not be preferable since each "onchange" event would require the entire select element to be iterated over.
Here's a fiddle that demonstrates how I am currently doing it, but I'm hoping maybe there's a better way than having to iterate over all the options on every "change": multiple select elment onchange fiddle
.val() on a multiple select returns an array.
See the snippet below as an example:
$(function() {
$('#fruits').change(function(e) {
var selected = $(e.target).val();
console.dir(selected);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple="true" id="fruits">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="mango">Mango</option>
<option value="grape">Grape</option>
<option value="watermelon">watermelon</option>
</select>
In your fiddle, I just used .val(). This returns an array
JSFiddle Link
$(function() {
$('#fruits').change(function() {
console.log($(this).val());
});
});
If you could use jQuery it might be as easy as:
$('select').change(function() {alert($(this).val())})
You could use blur instead of change, so that the select is only processed once, rather than on each selection. http://jsfiddle.net/2mSUS/3/
$(function() {
$('#fruits').change(function(e) {
var selected = $(e.target).val();
console.dir(selected);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple="true" id="fruits">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="mango">Mango</option>
<option value="grape">Grape</option>
<option value="watermelon">watermelon</option>
</select>
You can use the :selected Selector of jQuery instead, but I believe that under the hood, jQuery does a loop on the selected = true.
element.addEventListener('click', function(){alert(this.value)})
This is a solution in JS, you can port it over to jQuery pretty easily. The idea is to add a click listener to each option in the selection. This will not work in IE8 and below because of addEventListener, there are ways to get around this though.
I think this is a better approach then having to reiterate over the list. You will have to have a listener attached to each option though.
This works:
var MyControl = document.getElementById('Control_ID');
var newValue = MyControl[MyControl.selectedIndex].value;
Of course, Control_ID is the ID of the select control.
I'm doing a form submit. My template helper looks like this:
'submit #update': function(event) {
event.preventDefault();
var obj_opts = event.target.tags.selectedOptions; //returns HTMLCollection
var array_opts = Object.values(obj_opts); //convert to array
var stray = array_opts.map((o)=> o.text ); //to filter by: text, value or selected
//stray is now ["Test", "Milk Free"] for example, depending on the selection
//...do stuff...
}
You could use a similar pattern for 'onchange'
I have the following HTML
<select onchange="this.form.submit()" name="name">
<option value="9995101E01#17201044055PM">9995101E01#17201044055PM</option>
<option value="GRR-Example">GRR-Example</option>
<option value="admin">admin</option>
<option value="123w">123w</option>
</select>
May I know how I can use JQuery to option with value "admin"?
$('select[name=name] option:eq(2)').attr('selected', 'selected');
Demo.
Like this:
$("select[name='name'] option:eq(2)").attr("selected", "selected");
EDIT:
To do what you want in your new edit, that is, select the option that has the value of admin:
$("select[name='name'] option:contains('admin')").attr("selected", "selected");
See it working.
I think the nth-child pseudo-class is what you're looking for:
$('select option:nth-child(3)').attr('selected', 'selected');
I'd not advice setting value of select by using .attr('selected', 'selected').
It's bad practice. If two options have 'selected' attribute - then what is the value of select?
Here is the simple and easy version that will work:
$('select[name="name"]').val('admin');
DEMO
Just updating in case it helps someone. I had a similar requirement but in my case the dropdown was stored as a JavaScript variable. Also I liked how Denis Matafonov suggested to make the option in question selected. So here's the final block of code:
var target_dd = $('select[name=name]');
$(target_dd).val($(target_dd).find('option:eq(2)').html());
If you want to select nth option and trigger onchange event then:
function selectOption(nr) {
var select = $("select");
if (select.children().length >= nr) {
let value = select.find('option:eq(' + nr + ')').val();
select.val(value).change();
}
}