I have this HTML
<select id="drpRequestCategories" class="form-control" Width="100%">
<option value="-1">All</option>
</select>
and here is the function I fill the Select from it
function filldropdownlistcategory(res) {
var test = $.parseJSON(res.d);
$("#drpRequestCategories").empty();
$(test).each(function () {
var option = $('<option />');
option.attr('value', this.ServiceID).text(this.ServiceName);
$('#drpRequestCategories').append(option);
});
}
when I click on Search button on my page
1-it clear this dropdownlist but I need to keep the last selected value.
2- I call this function on every treeview node change so when I remove this
$("#drpRequestCategories").empty();
it doesn't remove the old dropdown values but append the new values to the old .
Ok first using localstorage set a key holding the last selected item ,while every node change first empty the select box and use the localstorage item to fill the box again
//Add the onchange listener for the select box
$("#drpRequestCategories").on('change',function(evt){
var optionSelected=evt.target.value;
localStorage.setItem("recent",optionSelected);
}
//Now your function
function filldropdownlistcategory(res){
//empty the box
$("#drpRequestCategories").empty();
$(test).each(function () {
var option = $('<option />');
option.attr('value', this.ServiceID).text(this.ServiceName);
$('#drpRequestCategories').append(option);
});
//Once U have appended the options attach the previous list to the select box
var prevOptions=JSON.parse(localStorage.getItem("options"));
for(var key in options){
var option=$('<option />')
option.attr("value",options[key]).text(options[key])
$("#drpRequestCategories").append(option)
}
//Now Select the Last selected option
var lastSelected=localStorage.getItem("recent");
$("#drpRequestCategories").val(lastSelected);
//Once all the options are populated call the storeOptions Function
storeOptions();
}
//Function to store the options
function storeOptions(){
var options=$("#drpRequestCategories").children();
var obj={};
for(var i=0;i<options.length;i++){
var optionText=options[0].value || options[0].innerHTML //Depends on what you want
//update the obj
obj["option"+i]=optionText;
}
//Now Store them in localStorage
localStorage.setItem("options",JSON.stringify(obj))//stringify will convert the object into a string
}
Related
My situation is i have a comb-Box which i fill with items that are integer values dynamically through javascript.
The problem is when i click on item to select it , It is still not selected , after clicking at that item, again i need to click outside the combo box to get it selected. I don't know why ?
My code to do so is (it's inside table) :
<body onload="loadView();">
<table>
<tr>
<td>
<select id="mydropdown" name="mydropdown" onblur="comboItemselect(this)"></select>
</td>
</tr>
</table>
</body>
And how i fill the item in combo is like this :
function loadView()
{
var sel = document.getElementById('mydropdown') // find the drop down
for (i = 1; i <= 50; i++) { // loop through all elements
var opt = document.createElement("option"); // Create the new element
opt.value = i; // set the value
opt.text = i; // set the text
sel.appendChild(opt); // add it to the select
}
}
/*When an item is selcted from CoboBox*/
function comboItemselect(item)
{
var selectedItem = item.options[item.selectedIndex];
alert("selected item is : " +selectedItem);
}
What i have done before in wpf or any other application was , i just clicked on the item to be selected in combobox and it was selected, but why i need to click once on the item and then again click outside the combobox to get it selected ?
How to select item just by clikinng once on that combo box item
Change event from onblur to onclick. it will work fine
function loadView() {
var sel = document.getElementById('mydropdown') // find the drop down
for (i = 1; i <= 50; i++) { // loop through all elements
var opt = document.createElement("option"); // Create the new element
opt.value = i; // set the value
opt.text = i; // set the text
sel.appendChild(opt); // add it to the select
}
}
/*When an item is selcted from CoboBox*/
function comboItemselect(item) {
var selectedItem = item.options[item.selectedIndex];
alert("selected item is : " + selectedItem.value);
}
<body onload="loadView();">
<table>
<tr>
<td>
<select id="mydropdown" name="mydropdown" onchange="comboItemselect(this)"></select>
</td>
</tr>
</table>
</body>
You were close. All you need to do is change
var selectedItem = item.options[item.selectedIndex];
to
var selectedItem = item.value;
for any elemt you can access the attributes like id and value just by using
<variable>.id
<variable>.value
and as for the clicking outside, it is because you have it onBlur which means after losing focus. So it will call the function after you click off the the select box. What you can do is add it to the .click function. JQuery would be even better for this operation as you can do an onClick event to initialize your select and an onChange event to get the selected item
I have a multiselect Listbox and fetching the list of selected values using
$('[id*=ListBox]').click(function(){
var selectedItems = $(this).val();
var lastItem = $("[id*=ListBox] option:selected").last().val();
});
This returns me comma separated array of selected values. But the problem is the array is always sorted by values and not generated by order in which selected values were clicked.
3000 , 3005 , 3009 , 3011
But if I first click item with value 3011, then 3005 , then 3000 and last 3009 I want values in that order
3011 , 3005 ,3000 , 3009
How to get selected values in order in which they were clicked ?
EDIT
Getting the most recent value selected also solves my problem.
How to get most recent selected item ?
First, set an event that adds an integer to each listbox item whenever the user clicks. Store the integer in a hidden element somewhere on the page, or do something clever by setting a data-attribute on the element like this:
$(function() {
$("#ListBox").data("selected-index", 0);
});
$("#ListBox option").on("click", function() {
var currentSelectedIndex = $("#ListBox").data("selected-index");
$(this).data("counter", currentSelectedIndex++);
});
Then in order to get all those in the order they've been clicked:
function getOrderOfItems() {
var arrayOfSelected = new Array(),
// Use Math and .map() to get the highest data-counter:
counters = $("#ListBox option[data-counter]").map(function() {
return parseInt($(this).data("counter"), 10);
}).get();
var highestCounter = Math.max.apply(Math, counters);
// We have the highest counter, so use a for loop to select the selected options.
for (var i = 0; i < highestCounter; i++) {
arrayOfSelected.push($("#ListBox option[data-counter=" + i + "]"));
}
console.log(arrayOfSelected);
return arrayOfSelected;
}
Where arrayOfSelected contains the ListBox items in the order they were clicked.
Note, html from #PaulRoub 's Answer used , as no html appear at OP
If interpret Question correctly , try substituting change event for click event ; creating an array of selected values , utilize .slice(-2)[0] to view previously selected item .
$("#ListBox").data("prev", []).change(function(e) {
$(this).data().prev.push(this.value)
console.log($(this).data().prev.slice(-2)[0], // last selected item
$(this).data().prev) // array of selected items , in order selected
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<select id="ListBox" multiple>
<option value="3000">3000</option>
<option value="3001">3001</option>
<option value="3002">3002</option>
<option value="3003">3003</option>
<option value="3004">3004</option>
</select>
This is what worked for me . I had to take a global array and after each click compare selected items of listbox with elements in array . The difference between them gave me latest selected item .
$(document).ready(function () {
var arr = [];
$("[id*=listBox]").click(function () {
var lastItem = '';
var selArr = [];
var flag = 0;
selArr = $(this).val();
// alert(selArr);
if ( $(this).val()!=null) {
if ($(this).val().length > 2) {
lastItem = $(selArr).not(arr).get();
selArr = $.grep(selArr, function (value) {
return value != lastItem;
});
flag = 1;
//arr = [];
}
}
arr = selArr;
$(this).val(selArr);
if (flag == 1)
alert("Cannot select more than 2 items");
});
});
This question made me discover two strange things .
$("#Listbox option").click() doesn't fire on Internet explorer ( i used version 9 ) but
works fine on others . I don't know why option element in not
fetched in IE.
$(#Listbox).val() gives comma seprated list of selected values in
sorted order and not in order in which the items were selected. This
proved to be a major surprise and headache .
im adding table row data using json response. here is my code
var i;
for (i = 0; i < result.length; i++) {
$.get('LoadserviceSplit', {
"sectcode" : result[i]
},
function (jsonResponse) {
if (jsonResponse != null) {
var table2 = $("#table_assign");
$.each(jsonResponse, function (key, value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['serviceId']);
rowNew.children().eq(1).text(value['title']);
rowNew.children().eq(2).html('<input type="text" id="date_set" name="date_set"/>');
rowNew.children().eq(3).html('<input type="text" id="date_set1" name="date_set1"/>');
rowNew.children().eq(4).html('<input type="text" id="date_set2" name="date_set2"/>');
rowNew.children().eq(5).html('<select class="status1" id="status1">');
rowNew.appendTo(table2);
});
}
});
var pass_unit_code = "001";
$.get('LoadDivisionCodeServlet', { //call LoadDivisionCodeServlet controller
unitCode : pass_unit_code //pass the value of "sample" to unitCode:
}, function (jsonResponse) { //json response
var select = $('#status1'); //select #status1 option
select.find('option').remove(); //remoev all item in #divcode option
$.each(jsonResponse, function (index, value) {
$('<option>').val(value).text(value).appendTo(select); //response from JSON in array value{column:value,column:value,column:value}
});
});
}
it works fine except the select tag part. only the first row of table have value. the rest has no value. i want all drop-down list inside the table has same value.. can anyone help me about this.
Take a look at
rowNew.children().eq(5).html('<select class="status1" id="status1">');
You're creating new select elements in a $.each and assigning the same id, that is status1 to all of them.
Then you're selecting the select element that has an id of status1 like
var select = $('#status1'); //select #status1 option
Therefore, only the first select element will be selected.
EDIT:
Your question is not completely clear.
However, this is how you can add different Id for select inside each of your <td>
Replace this
rowNew.children().eq(5).html('<select class="status1" id="status1">');
With something like
rowNew.children().eq(5).html('<select class="status1" id="status'+key+'">');
So this will have different Ids.
I know I can get the selected value like:
var selectVal = $('#mainIssueType: selected').val();
But how can I do the same thing passing in a variable as the select box id?
What I've tried:
var selectVal = $('#'+element.id+' :selected').val();
var selectVal = $(element+' :selected').val();
var selectVal = $([element]+' :selected').val();
Full function:
$(function(){
$('select').on( 'change', function( element ){
$('#'+this.id).nextAll('select').remove();
//get current selected option
var selectVal = $(element+' :selected').val();
// ^^ this is the problem
//create a new select box and add to branchDiv
var sel = $('<select>').appendTo('#branchDiv');
//give the new element an id matching
//the selected value from the previous element
sel.attr('id',selectVal);
//set the select box's options using the values
//from the "selectVal" object within the "tree" object
$(tree[selectVal]).each(function() {
sel.append($("<option>").attr('value',this.val).text(this.text));
});
});
});
If you want to use the event argument to retrieve the value of the selected option, you have to pass the target property of it to frame a Jquery object
Try,
var selectVal = $(element.target).find(':selected').val();
Or simply,
var selectVal = $(this).find(':selected').val();
It's not work because element in your case refer to select element not option, you want:
var selectVal = $(this).find('option:selected').val();
Just try like this http://jsfiddle.net/8nhmU/20/
<select id="selDemo">
<option value="1">Hi</option>
<option value="2">Hifds</option>
<option value="3">Hifsdf</option>
<option value="4">Hids</option>
</select>
Script:
$(document).ready(function() {
$('#selDemo').change(function(){
alert($('#selDemo').val());
});
});
I am trying to get the custom attribute values from the select box. It is triggered by a checkbox click which I already have working. I can get the name and value pairs just fine. I want get the custom attributes (therapy) (strength) (weight) and (obstacle) from the option value lines. is this possible?
select box
<option value="2220" therapy="1" strength="1" weight="0" obstacle="0">Supine Calf/Hamstring Stretch</option>
<option value="1415" therapy="0" strength="0" weight="0" obstacle="0">Sitting Chair Twist</option>
<option value="1412" therapy="0" strength="0" weight="0" obstacle="0">Static Abductor Presses</option>
jQuery
// exercise list filter category
jQuery.fn.filterByCategory = function(checkbox) {
return this.each(function() {
var select = this;
var optioner = [];
$(checkbox).bind('click', function() {
var optioner = $(select).empty().scrollTop(0).data('options');
var index=0;
$.each(optioner, function(i) {
var option = optioner[i];
var option_text = option.text;
var option_value = parseInt(option.value);
$(select).append(
$('<option>').text(option.text).val(option.value)
);
index++;
});
});
});
};
You need to find the selected , like this:
var $select = $('#mySelectBox');
var option = $('option:selected', $select).attr('mytag');
That is how to get selected option attribute:
$('select').find(':selected').attr('weight')
Get selected option and use attr function to get the attribute:
$("select").find(":selected").attr("therapy")
JSFIDDLE