I have a select box, and when I click on a button, an ajax request is made, and it returns json object the object contains a new list of options for the select box. Is there any way that I can remove all the options from the select box and replace them with the new list?
<select id="cat-0" >
<option value="0">Select One...</option>
<option value="1">Text 1</option>
<option value="2">Text 2</option>
<option value="3">Text 3</option>
</select>
Use .html() to insert new options clearing the existing ones.
$('#cat-0').html(newOptions);
But of course you need to construct options from your JSON Data something like this.
var json=[{value:'1', text:'Option1'},
{value:'2', text:'Option2'},
{value:'3', text:'Option3'}];
var options=$('<select/>');
$.each(json, function(id, ob){
options.append($('<option>',
{value:ob.value,
text:ob.text}));
});
$('#cat-0').html(options.html());
Fiddle
//Clear the select list
$('#cat-0').empty();
//then fill it with data from json post
$.each(data, function(key, value) {
$('#cat-0')
.append($("<option></option>")
.attr("value",key)
.text(value));
}
Related
I've got this weird problem with my JavaScript code.
I'm trying to create dynamically loading select boxes without the luxury of something like React.
It compares values of other select boxes so that a value can only be selected in once. So if a value is already set in one select box, it cannot be selected again.
For this I use a list of original values, clone those values into a new variable and remove the ones already selected and then create new lists.
Works fine albeit the numerous loops. The only problem is that if I remove an item from the cloned variable, the original also changes.
Even if I push the original variable in a prototype object or use const.
window.initial_abstract_list = ["Option one", "Option two", "Option three", "Option four", "Option five"];
// Set the option values
function reset_abstract_list() {
var in_list = [];
var new_list = window.initial_abstract_list;
console.log(window.initial_abstract_list); /// window.initial_abstract_list changes!!!
// Get selected value of all select boxes
$.each($('select.values-list'), function(index, value) {
in_list.push($(value).val().toString())
});
// Remove already set values from list
$.each($('select.values-list'), function(index, value) {
$.each(in_list, function(index2, value2) {
delete new_list[value2.toString()];
});
});
// Generate new options for select boxes
$.each($('select.values-list'), function(index, value) {
var current_selected_key = $(value).val().toString();
var current_selected_val = $('option:selected', value).text();
$(value).empty();
$(value).append($('<option></option>')
.attr('value', current_selected_key)
.text(current_selected_val));
for (var index2 in new_list) {
"use strict";
$(value).append($('<option></option>')
.attr('value', index2)
.text(new_list[index2]));
};
});
}
// Alter content on change select boxes
jQuery(document).ready(function($) {
$(document).on('click', 'button', function(e) {
reset_abstract_list();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="values-list">
<option value="0">Option one</option>
<option value="1">Option two</option>
<option value="2">Option three</option>
<option value="3">Option four</option>
</select>
<select class="values-list">
<option value="0">Option one</option>
<option value="1">Option two</option>
<option value="2">Option three</option>
<option value="3">Option four</option>
</select>
<select class="values-list">
<option value="0">Option one</option>
<option value="1">Option two</option>
<option value="2">Option three</option>
<option value="3">Option four</option>
</select>
<button>Ye olde button</button>
When you set your new_list to the default list, it's basically creating a reference to the original. You need to instead copy the values of the original list so they aren't coupled.
var new_list = window.initial_abstract_list.slice();
By doing var new_list = window.initial_abstract_list; you are only creating a reference to the original array. Any changes made to new_list will reflect in the initial array.
What you want to do is create a deep copy of the initial array, so as to get a different variable but with the same values. You can do this like so:
var new_list = jQuery.extend(true, {}, window.initial_abstract_list);
I am using Jquery chosen plugin and it's working fine. I have used this plugin in my one of the module. My dropdown values are something like that:
<select id="itemcode" onchange="get_data()">
<option value="1">ITEM001</option>
<option value="2">ITEM002</option>
<option value="1">ITEM001</option>
<option value="3">ITEM003</option>
</select>
It's working fine. But problem is that when user select first option and then try to change third option onchange event does not fire because both options values are same. Is there any way to call onchange event every time if values are same or differ ?
Options values is a unique key of item so it's repeated in dropdown. Dropdown value is duplicate we have allowed to use same item in others module
I saw your implementation and it is working fine in code pen here is the link no need to change anything
<select id="itemcode" onchange="get_data()">
<option value="1">ITEM001</option>
<option value="2">ITEM002</option>
<option value="1">ITEM001</option>
<option value="3">ITEM003</option>
</select>
var get_data =function(){
alert("saas")
}
http://codepen.io/vkvicky-vasudev/pen/dXXVzN
Try this
$('#itemcode').click(function() {
console.log($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="itemcode">
<option value="1">ITEM001-A</option>
<option value="2">ITEM002</option>
<option value="1">ITEM001-B</option>
<option value="3">ITEM003</option>
</select>
Edit: This doesn't work. Sorry!
You could add a data attribute that differs for each element, for example:
<select id="itemcode" onchange="get_data()">
<option value="1" data-id="1">ITEM001</option>
<option value="2" data-id="2">ITEM002</option>
<option value="1" data-id="3">ITEM001</option>
<option value="3" data-id="4">ITEM003</option>
</select>
If you're using Rails or another framework to generate the <option> tags, it should be easy to add an incremental id to each element.
There is no way to fire get_data() with your current data.
The solution below is more of a hack. When you populate the options, prepend the value with something unique.
Eg.
<select id="itemcode" onchange="get_data()">
<option value="1_1">ITEM001</option>
<option value="2_2">ITEM002</option>
<option value="3_1">ITEM001</option>
<option value="4_3">ITEM003</option>
</select>
Thus your get_data() method will be called everytime. And in your get_data() method, split the value using underscore _ and you can get the actual value there.
function get_data(){
var actualValue=$(this).val().split("_")[1];
//do other processing
...
}
You can use other characters like $, or anything you like, instead of _
Ideally you want to change the data coming from the backend so that you don't get duplicate data. However if this is not possible, another approach would be to sanitise the data before putting it in the select. E.g
https://jsfiddle.net/vuks2bpt/
var dataFromBackend = [
{key:1,
value: "ITEM0001"
},
{key:2,
value: "ITEM0002"
},
{key:1,
value: "ITEM0001"
},
{key:3,
value: "ITEM0003"
}
];
function removeDuplicates(array){
var o = {};
array.forEach(function(item){
o[item.key] = item.value;
});
return o;
}
function get_data(){
console.log('get_data');
}
var sanitised = removeDuplicates(dataFromBackend);
var select = document.createElement('select');
select.id = "itemcode";
select.addEventListener('change', get_data);
Object.keys(sanitised).forEach(function(key){
var option = document.createElement('option');
option.value = key;
option.textContent = sanitised[key];
select.appendChild(option);
})
document.getElementById('container').appendChild(select);
i am using jquery instead of java script
<select id="itemcode">
<option value="1">ITEM001</option>
<option value="2">ITEM002</option>
<option value="1">ITEM001</option>
<option value="3">ITEM003</option>
</select>
jquery
$('#itemcode:option').on("click",function(){
alert(saaas);
})
I have to filter the options of a dropdownlist by value selected from another dropdown. In my database I have a table with all countries and a table with all cities of the world with a FK to the respective country.
Here is a part of my view and my page:
And my controller methods (the GET method of the page, the loading of all countries and the loading of all cities of a country): (I removed the image)
I have to handle the "onchange" event of the first dropdownlist to modify all the options of the second (calling the LoadCities method in my controller and passing the value of the selected item of first drop) but I have no idea about how to do it.
Thank you for your help!!
UDPADE
Thank #Shyju for your advices but it still does not working. I am a student and I don't know much about the topic, here are the results:
You can see that the Content-Length is 0, in fact the response panel is empty.
Why the type is xml? What is "X-Requested-With"? How can I fix it?
Use the onchange method (client side) of the first select and fill up seconds' options with an AJAX call.
You can listen to the change event on the first dropdown(Country), read the value of the selected option and make an ajax call to your server to get the cities for that country.
$(function(){
$("#Country").change(function(){
var countryId = $(this).val();
var url = "#Url.Action("LoadCities,"Country")"+countryId;
$.getJSON(url,function(data){
var options="";
$.each(data,function(a,b){
options+="<option value='"+ b.Value +"'>" + b.Text + "</option>";
});
$("#City").html(options);
});
});
});
Now your LoadCities should return the list of citites as Json.
public ActionResult GetCities(int id)
{
// I am hard coding a bunch of cities for demo.
// You may replace with your code which reads from your db table.
var dummyCities = new List<SelectListItem>
{
new SelectListItem { Value="1", Text="Detroit"},
new SelectListItem { Value="2", Text="Ann Arbor"},
new SelectListItem { Value="3", Text="Austin"}
};
return Json(dummyCities,JsonRequestBehaviour.AllowGet);
}
use javascript or jquery OnChange method.
and pass the 1st dropdown Id and use ajax to call the method by passing dropdown Id.
<div class="ui-widget">
<select id="pick">
<option value="">Select one...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="drop">
<option value="">Select one...</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
</select>
</div>
$("#drop").change(function () {
var end = this.value;
var firstDropVal = $('#pick').val();
});
I found a nice demo on an old JSFIddle for Moving items from one multi-select box to another with JavaScript
You can see the demo here: http://jsfiddle.net/jasondavis/e6Y7J/25/
The problem is, the visual part works correctly but when I put this on a server with PHP, it only POST the last item added to the new select box. So instead of POSTING an array of items, it will only POST 1 item regardless of how many items exist in the selection box.
Can anyone help me?
The JavaScript/jQuery
$(document).ready(function() {
$('select').change(function() {
var $this = $(this);
$this.siblings('select').append($this.find('option:selected')); // append selected option to sibling
});
});
I believe I've hit this issue before. For the PHP $_POST array to populate this correctly you need to add a name field with [] at the end of the name. PHP will then interpret the result as an array of all the values and not just the last selected one.
Example:
<select name="demo_multi[]" multiple="multiple">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
When you recall the item in the $_POST array leave off the square brackets.
$values = $_POST['demo_multi'];
Change the multiselect name to an array
<select name="post_status[]" multiple id="select2" class="whatever" style="height: 500px; width: 222px;"></select>
I think you also have to select all items in the
This is pre jquery but it works.
`<form onsubmit="selectAll();"> ....</form>
function selectAll()
{
for(j=0; j<document.formdata.elements.length; j++)
{
// if a multiple select box then select all items in the box so they are sent with the form
var currObj = document.formdata.elements[j];
if (currObj.tagName == 'SELECT' && currObj.multiple == true)
for (i=0; i<currObj.length; i++)
currObj.options[i].selected = true;
}
}`
This will then be loaded into the array named in the
I'm trying to select a certain option in a select box, but it's not working:
var category = $(row + 'td:nth-child(4)').text();
$('#category_id', theCloned).load('/webadmin/video/get_categories',function(){
$('#category_id', theCloned).val(category);
});
There's no error thrown, but it doesn't change the select box. What am I doing wrong here?
Here is an example of the options loaded by the load() call:
<option value="1">Capabilities</option>
<option value="2">Application Focus</option>
<option value="5">Fun</option>
The value of the category variable is "Fun" or "Capabilities", etc.
var $selectbox = $('#category_id', theCloned), // cache the element to avoid lookup overheads
category = $(row + 'td:nth-child(4)').text();
$selectbox.load('/webadmin/video/get_categories', function(){
$selectbox
.find('option')
.filter(function(){
return $(this).text() === category;
})
.prop('selected', true);
});
Update 1
Updated the code to adjust to the code you presented in your update. This will work. However if an option will contain a part of the string and not the full string it will still be part of the selected elements. E.g.
If the options will be
<option value="1">Capabilities</option>
<option value="2">Application Focus</option>
<option value="5">Fun</option>
<option value="6">Fun Time</option>
<option value="6">Funhouse</option>
And the category variable will have the value Fun, all three last options will be part of the selector.
Update 2
Changed the code to filter the options whose text fully matches the value of the category variable. Thus, you won't have to worry about the Update 1 above.
$('#id_of_select_box').val('your_value');
this will do
Try this
$('#category_id', theCloned).val($.trim(category));
At last i found a new solution Fiddle
<select>
<option value='1'>one</option>
<option value='2' >two</option>
<option value='3' >three</option>
</select>
Script
$("select").on("change",function(){
alert($("select option:selected").text());
});