How to change option value with Jquery? - javascript

I am looking for a way to change the option value from a select tag when users click on a link.
For example I have a select option html:
<select> <option value="0">Please Select</option>
<option value="1">red</option>
<option value="2">white</option>
</select>
And I have 2 links red white
When user clicks red the option will switch to red and white will switch to white. I am using the following code but it is not working.
jQuery("a.preview_link").click(function() {
var title = jQuery(this).attr("title");
jQuery(this).parent('p').children("select :selected").text(title);
});
Any suggestions?

Your way will set the option's text to the title attribute. Try:
jQuery("a.preview_link").click(function() {
var title = jQuery(this).attr("title");
jQuery(this).parent('p').find("select option").filter(function() {
return $(this).text() == title;
}).attr('selected', 'selected');
});
See filter.

Hmm, you're going about this wrong: Instead of changing the text of the selected option you need to loop over the <option/> elements and select the appropriate one, something like this:
$("select option").each(function() {
if($(this).text() == "red")) {
this.selected = true;
}
});
Edit: There might be a select() function in jQuery. If that's the case then use that over the DOM property.

This?
$("select #some-option").attr("selected", "selected");
Or this?
$("select").val(index);

Related

Creating a sub-category select list from parent select list

I am trying to create a select list that is populated depending on what the selected value is in the main category list. So far I've had little success, perhaps there is an easy way to do this, and I am over-thinking it.
I don't know much about jQuery, still learning.
Here is my attempt thus far
https://jsfiddle.net/b4cg04bj/3/
$('#category').on('change', function() {
if(this.value = "Desktop Programming") {
$("#subcategory").html("<option value='C/C++'>C/C++</option><option value='Python'>Python</option><option value='Visual Basic'>Visual Basic</option><option value='Visual C#'>Visual C#</option>");
}
else if(this.value = "Graphic Design") {
$("#subcategory").html("<option value='Adobe Illustrator'>Adobe Illustrator</option><option value='Adobe Photoshop'>Adobe Fireworks</option><option value='Adobe Photoshop'>Adobe Photoshop</option><option value='Adobe Photoshop'>Adobe InDesign</option><option value='Adobe Lightroom'>Adobe Lightroom</option><option value='Gimp'>Gimp</option><option value='Coral Draw'>Coral Draw</option>");
}
});
As it stands just now, when you select Desktop Programming the list behaves as I was expecting.. however after you select something you can't change the parent select box. As I said, I am new to jQuery and feel as though I'm doing this incorrectly so I would appreciate any alternative methods of accomplishing this.
I feel as though the reason the list isn't updating is because after the function runs it stops listening for the on change event.
This sets the value of the drop-down to "Desktop Programming":
if(this.value = "Desktop Programming")
To test the value, use === instead:
if(this.value === "Desktop Programming")
Fiddle 1
An alternative to putting the options within the JavaScript is to put them within the HTML as hidden optgroups:
CSS:
#subcategory optgroup {display: none;}
#subcategory .GraphicDesign {display: block;}
HTML:
<select id="subcategory">
<optgroup class="GraphicDesign">
<option value="Adobe Illustrator">Adobe Illustrator</option>
<option value="Adobe Fireworks">Adobe Fireworks</option>
...
</optgroup>
<optgroup class="DesktopProgramming">
<option value="C/C++">C/C++</option>
...
</optgroup>
</select>
You could then show the appropriate optgroup when selecting from the main select box:
$('#category').on('change', function () {
var cl= '.'+this.value.replace(/ /g,'');
$('#subcategory optgroup').hide();
$(cl).show();
$('#subcategory').val('');
});
Fiddle 2

Click on a select html element

I've got a Problem. I have a Select Option in HTML
<div id="eilig">
<select id="eiligselect" data-role="slider">
<option value="2" selected="selected">n. Eilig</option>
<option value="1">Eilig</option>
</select>
</div>
On page default "n. Eilig" is selected. After I have made a ajax post request (with "Eilig" selected) the select option should go back to default ("n. Eilig")
I have tried it with $('#eiligselect').val(2); but this only change the value back but the select option shows "Eilig" (but internal value is "n. Eilig".
This select is with a data-role "slider" which emulates a on / off switch like in ios.
So I think I have to click that slider with javascript to change it back instead of just change the value.
Do you have a clue? Thanks.
Try this : put selected attribute for option with value="2"
$('#eiligselect option[value="2"]').attr('selected',true);
Bind the event on change for slider on select value change,
$('#eiligselect').on('change', function() {
var activeLabel = $('span.ui-slider-label');
var mySlider = $(this);
var new2 = 'n. Eilig';
var new1 = 'Eilig';
if(mySlider.val() == 1) {
activeLabel.text(new2);
} else {
activeLabel.text(new1);
}
mySlider.slider( 'refresh' ); // .trigger( 'create' )
});
This Code may help you solving your problem,
var eiligselect = $("#eiligselect")[0];
eiligselect.seletedIndex = 0;

Use JQuery to get data from select multiple tab

I would like to use select multiple tab in html like
<select name="foo" multiple>
<option value="all">option1</option>
<option value="all">option2</option>
<option value="all">option3</option>
</select>
How can I get data in javascript from this multiple select tab
I tried
var foo = [];
$('#foo:selected').each(
function(i,selected) {
foo[i] = $(selected).text();
}
);
But no luck, it doesn't work. It shows foo.length==0
What is the correct way to do this? Thanks!
$('#foo:selected')
should be
$('#foo option:selected')
Selected attribute is a property of the options inside select and not select element.
Secondly you have no element with id="foo"
$('[name=foo] option:selected') // for this case
$('#foo:selected')
This tries to find instances of #foo which are selected. But that's the select element itself, not the options therein. Try with the options:
$('#foo option:selected')
Update: It looks like the first part of the selector is wrong, too. You don't actually have an element of id foo so #foo won't find anything. What you have is a select element with the name foo. So something like this instead:
$('select[name="foo"] option:selected')
Try this instead:
var foo = [];
$("[name='foo']").change(function () {
$("[name='foo'] option:selected").each(function (i, selected) {
foo[i] = $(this).text();
});
})
.trigger('change');

Alert when user select the same <option> in dynamically created <selects>

I have a PHP page that creates multiple selects depending on how many the page before it gives it and creates the same number of options that there are selected (it's to choose the priority).
<select name="select1" id="idSelect" onchange="javascript:SelectOnChange();">
<option value="Select one">Select one</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
What I want to do is, whenever the user chooses an option that was already selected in another selection, to show an alert in order to let them know that their choice has already been taken and deny the change.
I want to compare the currently selected option to every previously selected option every time the user selects something from every select.
Basically your looking for a change event to loop through each select and notify duplicates.
$("select").change(function() {
var currentSelection = this.value;
$("select").each(function() {
if (this.value == currentSelection) {
alert("you've already chosen this!");
}
});
});
Something like this should work
Listen for change events
Get the element's seletedIndex
Grab all of the selects with getElementsByTagName()
Loop through and get the selected index
Compare to see if used
This could maybe work :
var $selects = $('select');
// WHen a select is changed.
$selects.onchange(function() {
// Storing it's selected value, assuming there is only one per select.
var value = $(this).selected().first().attr('value');
var $changedSelect = $(this);
// For each select...
$selects.each(function() {
var $otherSelect = $(this);
// ...that is not the one that just changed.
if( ! $otherSelect.is($changedSelect)) {
// If that other select's selected value is the same as the changed one's
if($otherSelect.selected().first().attr('value') === value) {
alert('...');
}
}
});
}
I didn't try it though, you might have to change a few details in it if it doesn't work.

Change FORM SELECT (dropdown menu) depending on other dropdown in JS/Jquery

I have a form with two drop down menus and I want the selectable values in the second drop down menu to change depending on what is chosen with the first drop down
This is drop down one:
<select name="cat" id="1">
<option>MAMMAL</option>
<option>REPTILE</option>
<option>BIRD</option>
</select>
And depending on the selection I immediately want one of these forms displayed:
<select name="type" id="type1">
<option>CAT</option>
<option>DOG</option>
</select
<select name="type" id="type1">
<option>SNAKE</option>
<option>LIZARD</option>
</select
<select name="type" id="type1">
<option>HEN</option>
<option>ROBIN</option>
</select
The form is for multiple entries so there's many rows with the id number increasing each time.
My jQuery so far is:
$(document).ready(function()
{
$(".cat").live("click", function(event)
{
cid=event.target.id;
catchosen = event.target.value;
switch (catchosen)
{
case 'MAMMAL':
case 'REPTILE':
case 'BIRD':
return {}
};
event.preventDefault();
});
});
How do I change/replace the values in a dropdown list with jQuery?
Firstly, if you use the selector $(".cat") , you should have your first select box the class cat assigned. But it's always good to select using a id in this case. And I would suggest you to use change event instead of click event on detecting change of select option of the first select box.
You can use the .empty() jquery function to clear the 2nd drop down's options and then use .append() to add new options to it.
Something like
$("#type1").empty(); //clear all options
$("#type1").append('<option value="CAT">CAT</option>');
Give separate ids for you select. i.e, type1, type2 and type3. Change youe script like this.
$(document).ready(function()
{
$(".cat").live("click", function(event)
{
catchosen = this.value;
$("#type1, #type2, #type3").hide();
switch (catchosen)
{
case 'MAMMAL':
$("#type1").show();
break;
case 'REPTILE':
$("#type2").show();
break;
case 'BIRD':
$("#type3").show();
break;
};
});
});

Categories