I have a form with a select box, like so:
<select id="school">
<option>Choose school</option>
<option value="656462">test</option>
<option value="653671">test1</option>
<option value="653688">test2</option>
</select>
How do I get the option values from the above options? I want to use the values in the below jQuery code:
$("select#school").change(function(){
$("select#locatie").html('<option value="">Course</option>');
$("select#lijst").html('<option value="">List</option>');
$("#cat1").html($("#school option:selected").text());
$("#cat2").html('Course');
$("#cat3").html('List');
var options = '';
$(function(){
$("select#school").change(function(){
$("select#location").html('<option value="">Location</option>');
$("select#list").html('<option value="">List</option>');
$("#cat1").html($("#school option:selected").text());
$("#cat2").html('Course');
$("#cat3").html('List');
var options = '';
if($("#school").val() == 656462){
options += '<option value="">Course</option>';
options += '<option value="12345">test1</option>';
}
if($("#school").val() == 653671){
options += '<option value="">Course</option>';
options += '<option value="89887">test2</option>';
}
if($("#school").val() == 653688){
options += '<option value="">Course</option>';
options += '<option value="548798">test25</option>';
}
$("select#locatie").html(options);
});
});
Basically, for every option value there's a new if statement. Problem is that the selectbox is filled with a lot of option values which are generated automatically. So now I have to do everything by hand instead of automatically generated if statements.
So what I try to do is:
1) get all the option values from the
2) use these option values to create an if statement for every value
Any help greatly appreciated
If I understand what you're trying to do, you want to create new options for a second select based on the results of the first? I'd probably store the possible options in an array on an object:
var courseSelection = {
"656462": [ { value: "123456", text: "Course 1" }, { value: "234567", text: "Course 2" } ],
"653671": [ { value: "345678", text: "Course 3" }, { value: "456789", text: "Course 4" } ],
"653688": [ { value: "567890", text: "Course 5" }, { value: "678901", text: "Course 6" } ]
};
And then in your change event handler, (as you state) you can loop through each object in the array to build the appropriate list:
$("select#school").change(function(){
var options = '',
courses = courseSelection[$(this).val()];
$('select#course').empty();
options += '<option value="">Course</option>';
$.each(courses, function() {
options += '<option value="' + this.value + '">' + this.text + '</option>';
});
$('select#course').append(options).show();
});
JSFiddle describing what I mean. Let me know if I've got the wrong end of the stick here!
Re-think your approach. In this case, I'll do one of the following:
On the #school change event send the selected value to the server to get the list of matching options; or
If you want to do it all on the client side, create an array that for each possible value, gives matching options. This way you can avoid all this ugly if statements.
Related
I trying to create a html and java script front-end for my python back-end. I am parsing the data from a tsv file and then dynamically updating the drop down list. I don't have much experience with html and javascript and am trying to learn.
I am using jQuery drop down multiselect
<form id="form-user" action="#" method="post">
<center>
<select id='testSelect1' multiple>
<option value='1'>Item 1</option>
<option value='2'>Item 2</option>
<option value='3'>Item 3</option>
<option value='4'>Item 4</option>
<option value='5'>Item 5</option>
<option value='1'>Item 1</option>
<option value='2'>Item 2</option>
</select>
</center>
</form>
Code for html layout
$('#testSelect1').multiselect({
columns: 1,
placeholder: 'Select Shoporder',
selectAll: true,
minCount: 30
});
This is how I am initializing it:
function updateShopOrder(data) {
var inner_HTML = [];
var temp = "<option value=";
const element = document.getElementById('testSelect1');
var value = "hello";
$(document).ready(function() {
for (i = 0; i < 20; i++) {
//var newOption = document.createElement("option");
//newOption.value = "tt";
//newOption.text = "test";
//element.add(newOption);
element.innerHTML += temp.concat(i.toString(), ">", "item ", i.toString(), "</option>");
//document.multiselect('#testSelect1').append("<option value=\"" + i.toString() + "\">" + value
+ " </option>");
//$('#testSelect1').multiselect( 'refresh' );
//$('#testSelect1').multiselect( 'rebuild' );
}
});
}
Code for how i am trying to update the the list. Commented out are stack overflow solutions I tried before. However everything I tried so far updates the html but does not update the wrapper (observation from devtools) enter image description here.
Any help would be greatly appreciated.
// DYNAMICALLY LOAD OPTIONS
$('select[multiple]').multiselect( 'loadOptions', [{
name : 'Option Name 1',
value : 'option-value-1',
checked: false,
attributes : {
custom1: 'value1',
custom2: 'value2'
}
},{
name : 'Option Name 2',
value : 'option-value-2',
checked: false,
attributes : {
custom1: 'value1',
custom2: 'value2'
}
}]);
I found this in the documentation but how would i go about implementing it using a for loop?
Try this code
$.each(data, function (index, value) {
// APPEND OR INSERT DATA TO SELECT ELEMENT.
$('#testSelect1').append('<option value="' + value.ID + '">' + value.Name + '</option>');
});
Iterate over your data somehow and append that to the html file. Refresh periodically for the change to reflect in your html
I have the following code to populate a dropdown box based on the selection of a different drop down box:
ps4models = new Array("Select My Model", "PS4 (Release Model)", "PS4 Slim", "PS4 Pro");
xboxonemodels = new Array("Select My Model", "Xbox One (Release Model)", "Xbox One Slim", "Xbox One Scorpio");
populateSelect();
$(function() {
$('#console').change(function() {
populateSelect();
});
});
function populateSelect() {
console = $('#console').val();
$('#model').html('');
if (console == 'ps4') {
ps4models.forEach(function(t) {
$('#model').append('<option>' + t + '</option>');
});
}
if (console == 'xboxone') {
xboxonemodels.forEach(function(t) {
$('#model').append('<option>' + t + '</option>');
});
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="console">
<option value="selectconsole">Select My Console</option>
<option value="ps4">PS4</option>
<option value="xboxone">Xbox One</option>
</select>
<select id="model"></select>
This populates the second dropdown box, but it does it without adding the "value" parameter. How would I adapt the code to create a "value" parameter with each option?
Instead of:
$('#model').append('<option>' + t + '</option>');
Do:
$('#model').append($('<option>').val(t).text(t));
NB: This is more the jQuery way of appending options, and will escape special characters like " and & automatically.
I feel like I'm missing something, but to append options with values, you append options, just like you are, with values, just like you did in the HTML snippet that has values:
$('#model').append('<option value="' + t + '">' + t + '</option>');
In plain old JavaScript, you can create an Option element like so:
var modelSelect = document.getElementById('model');
var selectOption = document.createElement('option');
selectOption.text = 'Select My Model';
selectOption.value = 'Select My Model';
modelSelect.add(selectOption);
You can create a jQuery plugin to handle populating the dropdowns for you. All you need to do is pass in the data. It can be either an array or an object.
You can also specify a key and text field, if each item in the array is an object.
Also, you should create a data object and access the different values by keys. This will allow you to loop over the data easily.
(function($) {
$.fn.populateDropdown = function(data, removePrevious, value, text) {
text = text || value;
if (removePrevious === true) {
this.find('option').remove();
}
if ($.isArray(data)) {
this.append(data.map(function(item) {
let value = $.isPlainObject(item) ? item[value] : item;
let text = $.isPlainObject(item) ? item[text] : item;
return $('<option>').val(value).text(text);
}));
} else {
this.append(Object.keys(data).map(function(key) {
return $('<option>').val(key).text(data[key][value]);
}));
}
return this;
}
})(jQuery)
var viewData = {
ps4models: {
text: 'PS4',
value: ["Select My Model", "PS4 (Release Model)", "PS4 Slim", "PS4 Pro"]
},
xboxonemodels: {
text: 'Xbox One',
value: ["Select My Model", "Xbox One (Release Model)", "Xbox One Slim", "Xbox One Scorpio"]
}
};
$('#console')
.append($('<option>').val('selectconsole').text('Select My Console'))
.populateDropdown(viewData, false, 'text');
$(function() {
$('#console').change(function(e) {
$('#model').populateDropdown(viewData[e.target.value]['value'], true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="console"></select>
<select id="model"></select>
I would like to create a dropdown list with JavaScript that contains actual objects instead of just a single value.
For example, I have an object with two members, ID and Name. On the dropdown list, I would like the name to be displayed for each object. However, if someone selects a name, I would like to easily be able to get the associated ID.
Not sure of how to do this without two separate containers, one for what's in the DDL and one that has corresponding indices for IDs.
If i understand you correctly, select already supports this. Option text and option value are two separate things
<select>
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Opel</option>
<option value="4">Audi</option>
</select>
Check this fiddle
https://jsfiddle.net/pg92tqka/
When you get the value of the selected option you can get stored id and by this value access the actual object (id can be index in array, ...)
html
<select id="selector"></select>
JS
var data = [
{ name :'david', id:1 },
{ name :'daniel', id:2 }
]
data.forEach(function(item){
var option = document.createElement('option');
option.value = item.id;
option.innerHTML = item.name;
selector.appendChild(option)
})'
selector.onchange = function(){
alert(this.value);
}
see the following fiddle : https://jsfiddle.net/1jcrxoy9/
There's a few ways of doing this, however this is my favorite currently:
JavaScript
var data = [{
id : 1,
name : 'Foo'
}, {
id : 2,
name : 'Bar'
}, {
id : 3,
name : 'Baz'
}];
var select = document.createElement('select');
select.innerHTML = data.map(function(v){
return '<option value="' + v.id + '">' + v.name + '</option>';
}).join('');
Then you can append the select somewhere in your body with all the options.
Use the value attribute for your ID.
var ddl_items = [{ ID: 1, Text: "One" }, { ID: 2, Text: "Two" }];
for (var i = 0; i < ddl_items.length; i++ ) {
$("#ddl").append("<option value='" + ddl_items[i].ID + "'>" + ddl_items[i].Text + "</option>");
}
<select id="ddl">
</select>
Fiddle: https://jsfiddle.net/dap3x83v/
This question already has answers here:
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 8 years ago.
I am having json as below
[{
"name": {
"1": "User Name",
"2": "User Email",
"3": "User Mobile",
"4": "User Address"
},
"filename": [
["upl_1407158917.xls"]
]
}]
I want to apend it to drop down list in ajax and filename want to store in hidden field.
I don't want to append filename in my drop down list.
can anyone help me out.
Updated :
I tried this :
$.each(data, function(key, value) {
//alert(value);
$('.excelHead').append( $('<option value="' + value + '">' + value + '</option>') );
});
You need to run EACH loop for adding it to drop down.for example :
select_box = '<select>';
$.each(data.name, function(k, v) {
withdraw_option +='<option value="'+k+'">'+v+'</option>';
});
select_box += '</select>';
Will produce :
<select>
<option value="1">value1</option>
<option value="2">value2</option>
<option value="3">value3</option>
<option value="4">value4</option>
</select>
You gave no specifics as to what you want appended where, so here's just some simple code that shows how to get each item in your array, and append the data. Here's what you need to do:
in a jQuery each, parse the data, then pass it into the callback. It then becomes as simple as you'd expect.
$.each(data, function(index, value) {
var option = $("<option>")
.text(value.name["1"])
.val(value.name["2"]);
$("#mySelect").append(option);
});
I created an option (as per your request), and used some of the data to fill in the text and value for it. The same exact way can then be used to create a hidden field for the file.
http://jsfiddle.net/7cp2j/1/
i have this grid options:
$scope.ngOptions = {
data: 'data',
columnDefs: [
{field: 'Status', displayName: "Status", cellTemplate: selectTableTemplate, enableCellEdit: true},
{cellTemplate: '<button ng-click="update(col, row)">' + Save + '</button>', enableCellEdit: false }]
};
var selectTableTemplate = "<select ng-model='Status' ng-change='changeToFirst(Status, row)'>" +
'<option value="1" class="ng-binding" ng-selected="COL_FIELD == 1">' + 1 + "</option>" +
'<option value="2" class="ng-binding" ng-selected="COL_FIELD == 2">' + 2 + "</option>"</select>";
EDIT:
how in ng-change function changeToFirst i get the clicked element and select the first option selected?
i do this like this:
row.elm.children().find('select').find('[value=1]').prop('selected', true);
but i sure that not the right way
You don't need to write your handler function to update values in your data. Angular ng-model will make it for you instead. Assuming that you have "Status" field in your data objects:
$scope.checkStatusChange = function (entity){
console.log(entity.Status);
};
var selectTableTemplate = '<select ng-model="row.entity.Status" ng-change="checkStatusChange(row.entity)">' +
'<option value="1" ng-selected="row.entity.Status == 1">1</option>' +
'<option value="2" ng-selected="row.entity.Status == 2">2</option>' +
'</select>';
Reference "row.entity" is a link to data belonging to current row. So you don't need to work directly with "select" element, data binding will do all the magic. Function "checkStatusChange" is provided for demo purposes.