Get selected index of dropdown from array Jquery - javascript

I am saving all inputs in a form in the form of array into a variable.
Example: var data = $('inputs,select')
Now, I want to get selected index of dropdown using variable data.
Please help.
Edit: Added Fiddle for reference
Fiddle

If I have understood your question properly, you save a jQuery object with every input and select in a variable­. To get the selected index of a dropdown you would have to iterate over your variable to find out if its a select or a regular input, and then get its selected index.
//loop over every dom element in the variable
data.each(function () {
//if its a select
if ($(this).is("select")) {
//find its selected index using native DOM and do something with it
$(this)[0].selectedIndex;
}
});

You probably want to add $( "select option:selected" ).text(); to select the selected item.
This was from: http://learn.jquery.com/using-jquery-core/faq/how-do-i-get-the-text-value-of-a-selected-option/

Related

Multiple select - value of deselect returns null

Description
I am using a jquery plugin chosen which pretty much does something like this:
This lets me add each option one by one or remove each option one by one. For every option selected, I create a new element with the selected option's value as the id.
Problem
The problem is when I remove an option from the list. For example:
$('#multiple-select').on('change', function(e){
alert($(e.target).val());
});
Will return the correct value if an option is added, however it returns null if we remove an option. I need to be able to get the value of the option being deselected so I can remove it in the other element.
Question
How can I get the deselected option's value to return the actual value instead of null? Or is there another way to bypass this problem?
All I need to be able to do is find the option being deselected and removing it from the other element (knowing that the element's id is built on the option's value).
Update
Remove code as requested:
$('body').on('change', benefs, function(e){
var $nbparts = $(participantNbParts),
$target = $(e.target),
$val = $target.val(),
$name = $target.text();
if($val == null){
//this is because we deleted something thus we need to remove it from $nbparts which is a pitty since we don't know what it was before it got deleted
}else{
//someone was added
$(create_row_expense_nb_parts_participant($name, $val)).appendTo($nbparts).show('slow');
$nbparts.parent().show('fast');
}
});
jQuery chosen provides selected and deselected using which you can identify selected and deselected values respectively, like:
$("#your_element_id").on('change', function (evt, params) {
var selected = params.selected;
var removed = params.deselected; //gives you the deselected value
//assuming your option ids are numbers
if( removed > 0 ) {
console.log( "Value removed is:" + removed );
}
});
From its documentation in the change event description you have
Chosen triggers the standard DOM event whenever a selection is made
(it also sends a selected or deselected parameter that tells you which
option was changed).
This suggests you should observe the arguments received by the event handler at run time to get a hint about (and most likely a reference to) the removed/deselected option.

How to insert selected element from multiple selection into an input?

hi everyone i have a problem.
i have a multiple selection and i want to select something and put it into an input through a button i hope i have been clear :
i manage to get the select item with this jquery code :
var chosen= $('#droite option:selected').val();
droite is an id for the multiple selection
and i want to put it into the input wich has an id : chosen item here is my jquery code:
$("#chosenitem").prepend(chosen);
and it won't work do you have any idea why .?
You need to call val() on the select itself, not the options it contains:
var chosen = $('#droite').val();
Similarly, to set the value of the #chosenitem input, use val() with a parameter:
$("#chosenitem").val(chosen);
Note that if multiple options are selected in the #droite element, the value returned will be a comma delimited string, eg. foo,bar,baz.
You should call val() to set the value of #chosenitem
$("#chosenitem").val(chosen);

How to change data on select option dropdown

need a small help to change data from option selected.
The data is populated first to the dropdown option list from a JSON result, in the same JSON is the second data thta need to be changed on select the option from dropdown.
What i want os to change the price on select the store.
This is my javascript code:
$(function() {
var pricestore = [{"product_id":"1","store_id":"1","price":"120.00","sequence":"0","id":"1","parent_id":"0","name":"Store 1","email":"store1#store1.com"},{"product_id":"1","store_id":"2","price":"140.00","sequence":"0","id":"2","parent_id":"0","name":"Store 2","email":"store2#store2.com"}];
$.each(pricestore, function(i, option) {
$('#sel').append($('<option/>').attr("value", option.id).text(option.name));
}),
//Trying to populate the price on div id
$$('#price-store').each(function(el) {
el.innerHTML = pricestore;
});
})
This is the HTML to get the data
<select id="sel"></select>
<div id="price-store"></div>
Here is also an example on jsfiddle
http://jsfiddle.net/A386B
Any help is appreciated.
Check this:-
Demo
As per what i understood from your question you need to show the price in the div as the dropdown values are changed. You can use below method. You need to use use a change event on the dropdown.
This approach uses Index() of the option element selected and retrieves the corresponding record from JSON.
$('#sel').change(function () {
$('#price-store').text(
pricestore[$('option:selected', this).index()].price);
});
Another way is to use data-attributes on the option element to store the respective price and retrieve it on change of dropdown value.
Demo
$('#sel').append($('<option>',
{
"value" :option.id,
"data-price" :option.price
}).text(option.name));
}),
$('#sel').change(function () {
$('#price-store').text($('option:selected', this).data('price'));
});
You use $$ to select your div instead of $. $('#price-store')
The second parameter of the function passed to the .each() method is the element not the first. function(i, el) {
Why are you using .each() for one div?
You'll have to format the data in pricestore to display it in a div, otherwise all you'll get is [Object object],[Object object].
Or this one:
<div id="price-store"></div
<form>
<select id="price">
<option>120</option>
<option>140</option>
<option>160</option>
</select>
</form>
and:
$('#price').change(function() {
$('#price-store').text($('#price').find(":selected").text());
});
http://jsfiddle.net/XcSZL/8/

jQuery - Get the value of unselected item in multiselect

Although this may sound dead simple, the matter is complicated by the fact I can only use the change() trigger on the select element. I am using the 'Chosen' jQuery plugin which basically modifies the multi select box on the page.
Whenever a item is selected or unselected, the plugin triggers the change event on the original select element. I am obviously able to get all the unselected items, but I need the one that was just unselected that caused the change event to trigger.
So I have the following function, the bit in the middle is what I need to capture the item that was just unselected. #cho is the id of the original select element.
$("#cho").chosen().change( function() {
// Need code here to capture what item was just unselected, if any...
})
Store value when the user changes the the check box.
var preVal;
$("input[name='g']").on("change",function(e){
if(preVal){
alert(preVal);
}
preVal=$(this).val();
});
Check this http://jsfiddle.net/fcpfm/
1.Use hidden field
2.Hidden field value initially empty.
3.Onchange put the selected value in a hidden field.
4.If onchange is happening again , hidden field value is the previously selected value.
$("#cho").chosen().change( function() {
var hidvalue = $('#hiddenfield').val();
if (hidvalue ) {
//Get the previously selected ids
var prev_ids = $('#hiddenfield').val();
//Then Update currently selected ids
$('#hiddenfield').val('currently selected ids');
} else {
//Update currently selected ids
$('#hiddenfield').val('currently selected ids');
}
})
Try using a variable to store the selected item. Update it each time when item changed. I cant add comment. That is why I am posting it as an answer.

Select attribute not changed after change of select element

I have a table in which a few columns contains select elements. In the tfoot I have one input element for each row used for filtering the row based on the selected value in the select element.
When loading the table and directly filtering the columns with selects, than it works and the table is filtered.
But when making a change in the select elements, the filter function is not taking any notice that the value has changed.
Checking out the html I can see that the "selected" attribute is still on the option that was selected when loading. Hence, it doesn't get updated when making an actual changed (identified in both FF and Chrome).
But from jQuery, searching for the selected value (.find(":selected")) works. So I figure that I can use that to find the value and then set the selected attribute to whatever was selected. This is how I am trying to do it:
$("select[id^='qu_owner']").live('change', function (e) {
var owner = $(this).val();
console.log(owner);
var ticketid = $(this).attr('id').substr(9);
$($(this) + " option[value=" + owner + "]").attr("selected", "selected"); //Update: this has been removed
});
But the selected attribute is still not updated in the element.
Any clue how to do this? I need the filtering to work and it's looking at the selected attibute. Is it not possible to make this kind of update to the select element?
UPDATE
Ok, based on the comments and answers below I understand there are better ways of doing what I did above. So instead of using $(this).find(":selected").val(); I now use $(this).val();. Also, I did remove the last row since I understand one shouldn't try to set the selected attribute.
And also, I now understand that the code where I have the actual problem is the filter function. This is for DataTables so it's a plugin but this is the significant part:
aData[i] is the actual table cell. Hence, it's just text but in this case it's the text for my select element. I think below is heading in the right direction, but still not working (check comments next to console.log-rows):
function( oSettings, aData, iDataIndex ) {
var ret = true;
//Loop through all input fields i tfoot that has class 'sl_filter' attached
$('tfoot .sl_filter').each(function(i, obj){
//$(this) can be used. Get the index of this colum.
var i = $("tfoot input").index($(this));
//Create regexp to math
var r = new RegExp($(this).val(), "i");
//Get the selected option from the column
console.log($(aData[i]).attr('id')); //Properly prints the ID
console.log($(aData[i] + " option:selected").text()); //Prints all options, not only the selected on
console.log($(aData[i] + " option:selected").val()); //Prints the value of the id that was selected when data was loaded, even if a new option has been chosen
console.log($(aData[i]).val()); //Prints the value of the id that was selected when data was loaded, even if a new option has been chosen
var str = $(aData[i] + " option:selected").text();
/*Test to see if there is a match or if the input value is the default
(the initial value of input before it has any fokus/text) */
if(r.test(str) || $(this).val()=="Search"){
//Return true only exits this function
return true;
}else{
/*Return false returns both function an .each. Retain 'false' in a variable scoped
to be reached outside the .each */
ret = false;
return false;
}
});
//Return true or false
return ret;
}
It is the text for the selected element I need to get hold of. That's what should be filtered upon. How can I do that?
Update
To narrow it down, I have created a jsfiddle with what's necessary. It's all about how to extract the text from the selected option: jsfiddle
aData[i] = the table cell. In jsfiddle, i use "sel" as variable for the content of the cell. The text for sel is copied form aData[i].
There's no need to change the attribute of the <option> - that's supposed to contain the original state of the element as it was downloaded from the server.
Your filter should be checking the selected property of the chosen option, e.g.:
.filter(function() {
return this.selected; // check the boolean property
})
This is also how the :selected pseudo-selector works - it checks the current value of the property, not the attribute.
Note that in the change handler for a <select> element, you can just use this.value to get the currently selected value.
$('select').on('change', function() {
// current value
var value = this.value;
// text of the currently selected option.
var text = this.options[this.selectedIndex].text;
}

Categories

Resources