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/
Related
How can I make the option selected according to the value I get from value[0] in the loop?
$.each(data, function(key, value) {
$("#cektubuh").append(
`<tr>
<td>
<select name="duration_type[]" class="form-control" required>
// here I want to add the selected option according to $ {value [0]}
<option value="Semester">Semester</option>
<option value="Month">Month</option>
</select>
</td>
</tr>`
});
});
As you have not provided an example of the data, there is no way to know what values are being used here or how they compare. Here is a basic example based on what you have provided.
$.each(data, function(k, v) {
var row = $("<tr>").appendTo($("#cektubuh"));
var cell = $("<td>").appendTo(row);
var sel = $("<select>", {
name: "duration_type[]",
class: "form-control"
}).prop("required", true).appendTo(cell);
$("<option>", {
value: v[0]
}).html(v[0]).prop("selected", true).appendTo(sel);
$("<option>", {
value: "Semester"
}).html("Semester").appendTo(sel);
$("<option>", {
value: "Month"
}).html("Month").appendTo(sel);
});
If it's more complex or has multiple elements, please provide an example of the structure so that a more complete answer can be shown.
if you have value which belongs to options list and you want to show as selected option
just do this.
var value = 'some value';
$('name="duration_type[]"').val(value);
it will show that value as selected.
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 select name slc_pc and i want to append option by jquery code.
I try these script. But it's not working.
$("select[name='slc_pc']").append(new Option("Hello", "Hello", true, true).attr("abc",brand,"123",model));
There are some mistakes in your code. First of all, to set multiple attributes, you need to pass them as an object. Second, the property name and value for the data attributes are incorrect. brand & model should be property and abc & 123 should be their values respectively.
new Option will create an option element which does not have attr method on it. You may use jQuery to create a new element.
Here's the correct way
$('select[name="slc_pc"]')
.append($('<option />') // Create new <option> element
.val('Hello') // Set value as "Hello"
.text('Hello') // Set textContent as "Hello"
.prop('selected', true) // Mark it selected
.data({ // Set multiple data-* attributes
brand: 'abc',
model: '123'
})
);
If you add an ID "slc-pc" to your select element, it's like this in it's basic form:
$('#slc_pc').append($("<option></option>").attr({"value": key, "abc": brand, "123": model }).text(value));
try this one
you have add ) after (new Option("Hello", "Hello", true, true) that and remove ) from last
$("select[name='slc_pc']").append(new Option("Hello", "Hello", true, true)).attr("abc", "brand", "123", "model");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name='slc_pc'>
<option>select</option>
</select>
$(function(){
var brand = 'test';
var model = '123';
var brand1 = 'abc';
var model1 = '456';
$(".slc_pc").append("<option value='hello' data-brand='" +brand+ "' data-model='" +model+ "'>hello</option><option value='hello1' data-brand='" +brand1+ "' data-model='" +model1+ "'>hello1</option>");
})
$(document).on("change",".slc_pc", function(){
var option = $("option:selected", this);
alert("value : "+ $(this).val() + ", brand : "+$(option).data('brand') + ", model : " + $(option).data('model'));
})
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<select class='slc_pc' name='slc_pc'>
<option value=''>--select--</option>
</select>
it can be done by something like this.
I have some JavaScript Arrays that are used to generate HTML selection fileds and then to also make the option a user has selected as the selected opton in the generated Selection list.
I have a working example for a basic JavaScript array. I need help with a more complex JS array though.
function buildFormSelection(optionArray, selectedOption){
var optionsHtml = '';
for(var i = 0; i < optionArray.length; i++){
optionsHtml += "<option value='" + optionArray[i] + "' "
+ (selectedOption == optionArray[i] ? "selected='selected'" : "")
+ ">" + optionArray[i] + "</option>";
}
return optionsHtml;
};
var typesArray = ['Other', 'SugarCRM', 'Magento', 'Design'];
console.log(buildFormSelection(typesArray, 'SugarCRM'));
This generates this HTML output...
<option value='Other'>Other</option>
<option value='SugarCRM' selected='selected'>SugarCRM</option>
<option value='Magento'>Magento</option>
<option value='Design'>Design</option>
Here is a JSFiddle to show it working. http://jsfiddle.net/jasondavis/4twd8oz1/
My issue is I now need to have the same functionality on a more complex array like this one below. It has an ID and a Name Value...
var milestonesArray = [
['1','Milestone 1'],
['2','milestone 2'],
]
Using similar code as my function above, I need to pull in a user's selected value from a database for example if they have saved the value of 2 then it should select selection option of 2 and show the text milestone 2 from a selection that looks like this...
<option value='1'>milestone 1</option>
<option value='2' selected='selected'>milestone 2</option>
I am not sure how to properly build a JavaScript array that can handle a key and value like this and make my function work with the milestone array.
Any help please?
What you need to do just add another array index to your function like so:
function buildFormSelection(optionArray, selectedOption){
var optionsHtml = '';
for(var i = 0; i < optionArray.length; i++){
optionsHtml += "<option value='" + optionArray[i][0] + "' "
+ (selectedOption == optionArray[i][0] ? "selected='selected'" : "")
+ ">" + optionArray[i][1] + "</option>";
}
return optionsHtml;
};
Where optionArray[i][0] is the value and optionArray[i][1] is the text.
JSFiddle
Answers with lots of code is usually frowned on but this is a trivial solution as #imtheman pointed out in his answer. But not everything needs to be so concise.
function makeOptionElement(value, title, selected) {
var option = document.createElement('option');
option.value = value;
if (selected) {
option.setAttribute('selected', 'selected');
}
option.innerHTML = title;
return option;
}
function dataToOptions(data, selectedIndex) {
var selectList = document.createElement('select');
data.forEach(function(item, index) {
var isSelected = (index === selectedIndex);
var option = makeOptionElement(item[0], item[1], isSelected);
selectList.appendChild(option);
});
return selectList;
}
Essentially, each time you call the array with your variables to be printed, you are calling the contents of the array in the position specified between the [ ]. It may be another array. That you can access as you would any other array. So, it would be:external_array[extrenal_array_index][internal_array_index]
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.