I am basicly trying to take a specific option from select and move it at the top of the list. What I am trying to do now is this.
$("select[name=list]").find('option[value="car"]').insertBefore($("select[name=list]").find('option:eq(1)'));
and for some reason it executes twice leaving two options at the top
<option value="car">Car</option>
<option value="car">Car</option>
Not sure what am I doing wrong, maybe someone knows?
thank you.
From the jQuery Documentation:
If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved before the target (not cloned) and a new set consisting of the inserted element is returned.
[..]
If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first, and that new set (the original element plus clones) is returned.
So, there is a clue! My guess is that your selector, is too much embracing, and you are selecting more than one element... Even in another select list in the document.
You may provide a little more HTML code for your example, but let me show how I would do it...
Html
<select id='MyNiceList'>
<option value='my_option_1'>First Option</option>
<option value='my_option_2'>Second Option</option>
<option value='my_option_3'>Third Option</option>
</select>
Js
$('#MyNiceList option[value="my_option_2"]').insertBefore('#MyNiceList option[value="my_option_1"]');
If you pay attention on the selector that I used, I eliminate any possibility of select more than one element, so, the rule on the second part I quoted is obeyed.
Example:
http://jsfiddle.net/sASCg/1/
I hope I helped you on my first Answer! : )
There may be 2 problems
If you insert a new option, then you simply may have 2 options with the same values, as you did not remove it.
The first item is numbered "0" not "1"
http://jsfiddle.net/4kHuA/
var $el = $("select[name=list]").find('option[value="car"]');
$("select[name=list]").find('option[value="car"]').remove();
$("select[name=list]").find('option:eq(0)').before($el);
:eq(1) will select the second element rather than the first element. Other than that, the code you've posted should work fine:
var $select = $("#mySelect");
$mySelect.find('option[value="car"]')
.insertBefore($mySelect.find('option:eq(1)'));
http://jsfiddle.net/B5W4B/
try this
$("select[name=list]").find('option[value="car"]').prependTo($("select[name=list]"));
$("select[name=list]").val('car')
Related
Two identical select boxes
<select class="select">
<option>- OPTION -</option>
<option>1</option>
<option>1</option>
</select>
<select class="select">
<option>- OPTION -</option>
<option>1</option>
<option>1</option>
</select>
Replace - OPTION - with - SELECT -
$(".select option:first").text("- SELECT -");
Code above replaces only first select box, ignores the second. Why? How to apply to all/any?
https://jsfiddle.net/oLbfs901/2/
:first will only select the first element of all the options combined together.
:first-child will select all elements that are the first child of their parent.
$(".select option:first-child").text("- SELECT -");
UPDATE regarding speed
Below, user #kosmos suggested using .find(). This method is much less performant than using :first-child. Some developers usually don't think twice about performance because it's still really quick but these can add up. Now you know that faster ways exist to achieve the same result so I would suggest using this knowledge.
This is the test case I set up to confirm: http://jsperf.com/find-versus-first-child
Though the other answers are valid, you could also type
$(".select").find("option:first").text("- SELECT -");
to get all .select elements and, for each one, get the first option child.
you can try with below code
$(".select option:first-child").text("- SELECT -");
I have a very basic question. I want to select the SELECTED text and dropdown value from the dropdown and show in the alert box.
My attempt:
Dropdown
<p id="test">
Select a draft:
<select id="Select" name="Select">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</p>
JS
$("#Select").change(function()
{
alert($(this).val()); // IF THIS WORKS FINE THEN NEXT LINE CODE SHOULD WORK TOO
alert($(this).text()); // WHY THIS SHOWS ALL THE DROPDOWN TEXTS
alert($("#Select option:selected").text()); // THIS JUST WORKS FINE
});
Question 1: What $(this) signifies? If it's signifies selected element then it should show the text also when doing $(this).text(). BUT IT DOESN'T work as expected.
Question 2: If I need to select the value and text of the dropdown is above mentioned is the efficient way to go about it.
Please guide me.
My JSFIDDLE Attempt
In your change event handler, $(this) is the <select> element.
The element represented by $(this) depends on the context where it is used.
It usually is the element which triggered an event (like here), or the element targeted by the iteration of an .each() loop, for example.
When an <option> is selected, the <select> take its selected option value as a value...
It doesn't do it for the text of the selected option.
So that is why the second alert() statement doesn't work.
The keyword this in your example represents the element on which the event triggered. This means the select element. .text() return all text included in the element, so it gives all elements. .val() returns the value of an input, in this case it will return the value of the select, but beware as it does not return more than one value if you set mutiple=true.
Since we now know that .text() returns the text, and this is the input that changed, we can deduct that you'd prefer using .val() to get the value as it may differ from the display text.
alert($(this).find("option:selected").val());
$(this) is used to make the this object a JQuery object which includes some extra functionality.
You can try this if you want to get the selected item value and text:
$(this).find(":selected").val(); // Gets the value of the selected option, if the value attribute in the option element is null it will give you the text
$(this).find(":selected").text(); // Gets the text of the selected option
hi the 'this' part is the raw DOM element from javascript $(this) makes it a jquery object, so you can use jquery. In this case it's the select.
If I need to select the value and text of the dropdown is above mentioned is the efficient way to go about it.
Yes it's fine.
jQuery get specific option tag text
Answer to question 1:
$(this) means that you pass this to the $ function. In other words, you create a jQuery object from the this object. In your context, this refers to the elements matching the #Select selector: your select element.
$(this).text() is working normally because internally it calls innerText on the select tag: which contains the DOM code of your select and innerText contains all the text (not HTML) of the children of the select.
Answer to question 2:
To retreive the label of the selected option: $("#Select option:selected").text()
To retreive the value of the selected option: $("#Select option:selected").val()
You can alter what you already have written by changing this:
alert($(this).val() + $(this).text());
to:
alert($(this).val() + $("option:selected", this).text());
And overall giving you the code you already have.
$("#Select").change(function()
{
alert($(this).val() + $("option:selected", this).text());
alert($("#Select option:selected").text());
});
$(this) is just selecting the identified object that you are choosing to use 'change' on which in this case is the select box.
$("#Select").change(function() binds the function defined after this point to the HTML element <select id="Select" name="Select">. Therefore within that function, $(this) refers to that Select element. The information within that select element is: <option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>. This is why $(this).text() will give you all the options; you're asking for all the text inside that element.
($this).val() gets you the value of the overall select element, which is the text of the currently selected option.
this refers to the context which was used to invoke the function.
When you change the select option, this refers to the whole select dropdown.
If you look below, when I print the value of $(this).val, it gives the function which returns the value of the selected option.
Whereas, when I print the value of $(this).text, it gives the function which gives the whole select dropdown inner text.
To answer your second question, I think $(this).val() is more efficient as by using $(this) will always refer to the context which invokes the function. Thus, you can create modular code using it, by separating the use of anonymous function into a named function and using it for other select dropdown in your site, if you want in the future.
$("#Select").change(function()
{
console.log($(this).val);
console.log($(this).text);
console.log($(this).val()); // IF THIS WORKS FINE THEN NEXT LINE CODE SHOULD WORK TOO
console.log($(this).text()); // WHY THIS SHOWS ALL THE DROPDOWN TEXTS
console.log($("#Select option:selected").text()); // THIS JUST WORKS FINE
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="test">
Select a draft:
<select id="Select" name="Select">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</p>
I am attempting to retrieve and set the selected value of a select element (drop down list) with jQuery.
for retrievel i have tried $("#myId").find(':selected').val(), as well as $("#myId").val() but both return undefined.
Any insight into this problem would be much appreciated.
to get/set the actual selectedIndex property of the select element use:
$("#select-id").prop("selectedIndex");
$("#select-id").prop("selectedIndex",1);
The way you have it is correct at the moment. Either the id of the select is not what you say or you have some issues in the dom.
Check the Id of the element and also check your markup validates at here at W3c.
Without a valid dom jQuery cannot work correctly with the selectors.
If the id's are correct and your dom validates then the following applies:
To Read Select Option Value
$('#selectId').val();
To Set Select Option Value
$('#selectId').val('newValue');
To Read Selected Text
$('#selectId>option:selected').text();
$('#myId').val() should do it, failing that I would try:
$('#myId option:selected').val()
When setting with JQM, don't forget to update the UI:
$('#selectId').val('newValue').selectmenu('refresh', true);
$("#myId").val() should work if myid is the select element id!
This would set the selected item: $("#myId").val('VALUE');
Suppose you have created a Drop Down list using SELECT tag like as follows,
<select id="Country">
Now if you want to see what is the selected value from drop down using JQuery then, simply put following line to retrieve that value..
var result= $("#Country option:selected").text();
it will work fine.
I know this is old but I just had a bear of a time with Razor, could not get it to work no matter how hard I tried. Kept coming back as "undefined" no matter if I used "text" or "html" for attribute. Finally I added "data-value" attribute to the option and it read that just fine.
<option value="1" data-value="MyText">MyText</option>
var DisplayText = $(this).find("option:selected").attr("data-value");
$( "#myId option:selected" ).text(); will give you the text that you selected in the drop down element. either way you can change it to .val(); to get the value of it . check the below coding
<select id="myId">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>`
<option value="4">Dr</option>
<option value="5">Prof</option>
</select>
Try this
$('#your_select_element_id').val('your_value').attr().add('selected');
I faced with a strange behaviour of select element. So, I have a select element with several options. One of option is empty - it's required by plugin to output placeholder.
I needed functionality that would clear selected options and I wrote something like:
$(element).val('');
$(element).find("option:selected").removeAttr("selected");
The thing is that "selected" attribute is still here and it's on old option - you can see it in the code sample.
So, I have 2 questions:
1) Why .val() method of jQuery library do not update "selected" attribute in options list?
2) Why I can not update "selected" attribute in my case? If I switch these statements it's working:
$(element).find("option:selected").removeAttr("selected");
$(element).val('');
Code sample:
$(function(){
$("#unselect").click(function(){
$("#lang_type").val('');
$("#lang_type").find("option:selected").removeAttr("selected");
alert($("#lang_type").html());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="lang_type">
<option value=""></option>
<option value="01">01 - Language of text</option>
<option value="02">02 - Original language of a translated text</option>
<option selected="selected" value="03">03 - Language of abstracts</option>
<option value="04">04 - Rights language</option>
<option value="05">05 - Rights-excluded language</option>
<option value="06">06 - Original language in a multilingual edition</option>
<option value="07">07 - Translated language in a multilingual edition</option>
<option value="08">08 - Language of audio track</option>
<option value="09">09 - Language of subtitles</option>
</select>
<button id="unselect">Unselect</button>
EDIT:
You can use prop(false) property like this
$(function(){
$("#unselect").click(function(){
$("#lang_type").val('');
$("#lang_type").find("option:selected").prop('selected',false);
});
});
Like #yezzz said, read this :
Note: Do not use removeProp() method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.
If I'm not mistaken, a multi-select can be initially unselected, but once any option is selected, it can not be unselected any more. RFC 1866 states in section 8.1.3:
The initial state has the first option selected, unless a SELECTED attribute is present on any of the elements.
This lets me to believe that one option MUST always be selected. Obviously, different browsers interpret this differently...
But it does not seem to be a jQuery issue, rather a browser implementation issue.
The selected attribute reflects merely the initial state of the select input. You shouldn't really care about removing it, as it affects nothing once a different option is selected (either by the user or by a script on your page).
The current state of the input can be read or modified via the selectedIndex property, where a value of -1 means no option is selected (which never is the default, as there always is an option selected initially). However, you seem to want to select a particular "empty" option.
Setting the value on a select box results in the corresponding option being selected, which, in your case, is the very first one.
The code probably does exactly what you want. So don't mind checking the HTML, as the selected attribute - again - is unrelated to the current state of the input.
The :selected selector, however, matches the elements that are currently selected. Your first snippet selects an option, thus making it :selected, then attempts to remove a non-existent attribute from it. The second snippet of yours assumes that the selection remains on the option that was initially selected, and then removes the attribute from it. What follows is the "empty" option getting selected, and no more steps need to be taken, as that's all it takes to select an option.
To summarize: you can safely drop all the code that deals with the removal of the selected attribute, as it doesn't affect the current state of the element, the state being already tied to the correct option.
I'm building a recipe-finder for a new food blog. The design I have basically involves the user selecting ingredients, one at a time, from a drop down <select>, the option disappearing from the list (so they can't select it again) and appearing on another HTML list with a link to remove it from the list. Once they're done, they click a button and that takes them through to a results page.
Here's the select markup as generated by the PHP:
<select>
<option value="">Please select</option>
<option value="beef-mince">Beef mince</option>
<option value="carrots">Carrots</option>
...
</select>
It's not drastically complex but it does raise a few questions on how I'm going to do some of these things. I'm using jquery.
I need to store the selected items in memory so I know what to send to the search page when they've done selecting items. What's the best way of doing that in your opinion as each item has two values (its "real" value and its database-value)?
How do I make "Please select" the selected option after they've selected something (preferable without triggering the onchange event)?
Once I've stored it in memory and added it to the displayed list of things they're searching for, how do I delete that item from the available items? Can I just "hide" or disable it (safely)?
If in #3 I have to delete it from the DOM, when I add it again, can I sort the list (based on either value) and keep the please-select option at the top?
1.) You can append hidden form elements to the page whose value is the value of the selected option.
2.)
jQuery("#select-list")[0].options[0].selected = true // assuming it's the first item
3.) I would remove the element from the DOM using jQuery("#select-list option:selected").remove()
4.) You can use before(). jQuery(your_default_option).before("#select-list option:first");
You can store the 'two values' in a hidden form field as an object in JSON notation. This will make it easy to modify in jQuery as the user interacts with the page.
You will need to use a combination of the onchange, keyup and keydown event to capture possible changes to the form so that you can re-select the 'Please Select' option.
You will need to remove the option from the dom and re-add it later. You can easily do this through jquery through something like this:
$("select option:selected").remove();
You can write a sorting function for the options starting with index 1, and keep the 'Please Select' as the first option.
1)
Basic idea, you need to check to make sure the first is not picked
var selections = [];
var mySel = document.getElementById("mySelectId");
var ind = mySel.selectedIndex;
selections.push( mySel.options[ind].value ); //add to a list for you to remember
mySel.options[ind] = null; //remove
2)
mySel.selectedIndex = 0;
3)
See #1
4) Yes you can add it anywhere you want by using insertBefore
Example here: http://www.pascarello.com/lessons/forms/moveSelectOptions.html
Will leave this answer here but I think I failed to read your whole post, so it might not help much.
You need to give your select a id like this:
<select id="MySelect">
<option value="">Please select</option>
<option value="beef-mince">Beef mince</option>
<option value="carrots">Carrots</option>
...
</select>
And to get it is just something like this:
<?php
$value = $_REQUEST["MySelect"];
echo $value;
?>
Code is not tested and $_REQUEST can be replaced by $_GET or $_POST regarding what you have specified as action on your form. $_REQUEST will eat it all though.