Iam using MVC4, initially my dropdown displays the list of data,
My javascript looks like,
$.each(data, function (value, key) {
var opt = "<option value=\"" + key + "\">" + value + "</option>";
$("#OwnerAgency").append(opt);
});
How do i set the selected default to be the blank option.
html:
<div class="SmallTopSpace">
<span class="LabelNormal">Primary Case Agency</span>
#Html.DropDownListFor(m => m.Agencies.AgencyKey, new SelectList(""), "", new { #class = "ImportDropDownMax", #id = "OwnerAgency", #onchange = "OwnerAgencyFunction();" })
</div>
before the $.each just append at that start of the data array another empty element .
or in your html do :
<select>
<option disabled selected></option>
</select>
Can't you just insert an empty option at the top in your view/html?
<select id="OwnerAgency">
<option></option>
</select>
Or you can add it in javascript.
var emptyOption = true;
$.each(data, function (value, key) {
var opt;
if (emptyOption) {
opt = "<option></optino>";
$("#OwnerAgency").append(opt);
emptyOption = false;
}
opt = "<option value=\"" + key + "\">" + value + "</option>";
$("#OwnerAgency").append(opt);
});
<select id="mySelect">
</select>
script:
var myOptions = {
val1 : 'text1',
val2 : 'text2'
};
var mySelect = $('#mySelect');
$.each(myOptions, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
mySelect.append('<option value=' + myOptions.length + ' selected>default</option>');
set your default select before or after select list generation http://jsfiddle.net/3ns3fj3t/
in your case:
$.each(data, function (value, key) {
var opt = "<option value=\"" + key + "\">" + value + "</option>";
$("#OwnerAgency").append(opt);
});
$("#OwnerAgency").append('<option value=' + data.length + ' selected>default</option>');
You could do it in your C# ViewModel by adding an empty element to SelectList object:
var selectList = new SelectList(....);
selectList.Items.Insert(0, new ListItem(String.Empty, String.Empty));
selectList.SelectedIndex = 0;
Related
var regionOption = document.querySelector("#municipality");
var districtOption = document.querySelector("#districtName");
var provOption = document.querySelector("#region");
createOption(provOption, Object.keys(regions));
provOption.addEventListener('change', function() {
createOption(regionOption, regions[provOption.value]);
});
regionOption.addEventListener('change', function() {
createOption(districtOption, districts[regionOption.value]);
});
function createOption(dropDown, options) {
dropDown.innerHTML = '';
options.forEach(function(value) {
dropDown.innerHTML += '<option name="' + value + '">' + value + '</option>';
});
};
CSS:
<select id="region" style="width: 125px;"></select>
<select id="municipality" style="width: 125px;"></select>
<select id="districtName" style="width: 125px;"></select>
So, I'm populating options for an empty select and I was wondering how to get the value of the selected option. I basically want to check if (select value = 'A' && another selecte value = 'B') { do something}
Set the value attribute on each <option>:
<option value="' + value + '">
Then, simply check the value property on the <select>.
if (document.getElementById("region").value === 'A') {
// ...
}
I am trying to get a value from a dropdown list. I have the dropdown list and I have the value that I want but I don't know how to link them to each other. So the value of the category should go in the dropdown list and then the image value from that string should be the outcome.
This is the JSON file array called ill.json
...
[{"id":"7","category":"Lente collectie 2021","image":"Teddy_bears_10.png"},{"id":"11","category":"Lente collectie 2021","image":"Individual_floral_elements_01.png"}
...
The category value goes into the dropdown list and then the outcome should be the image value:
This is my dropdown
...
const req = new XMLHttpRequest();
req.open('GET', 'ill.json', true);
req.send();
req.onload = function() {
const json = JSON.parse(req.responseText);
let dropdown = "";
let html = "";
//FILLING DROPDOWN WITH CATEGORYs
var result = json.reduce(function (r, a) {
r[a.category] = r[a.category] || [];
r[a.category].push(a);
return r;
}, Object.create(null));
let keys = Object.keys(result)
keys.forEach((key) => {
dropdown += "<select id='select'>"
dropdown += "<option value='" + key + "'>"
dropdown += key
dropdown += "</option>"
dropdown += "</select"
})
document.getElementsByClassName('dropdown')[0].innerHTML = dropdown;
...
And this is how I got the images
...
//get all images
json.forEach(function(val) {
html += "<div class='illustratie-item'>";
html += "<img class='dt-filelist-image' src='" + val.image + "'/>"
html += "</div><br>";
});
document.getElementsByClassName('illustratie-wrapper')[0].innerHTML = html;
...
If I get that right, it should be as easy as this:
var categorySelect = document.querySelector('.dropdown');
categorySelect.addEventListener('change', function(evt) {
var item = json.find(function(item) {
return item.id === evt.target.value;
});
console.log(item.image); // there's your image
});
Check the below snippet.
var images = [{"id":"7","category":"Lente collectie 2020","image":"Teddy_bears_10.png"},{"id":"11","category":"Lente collectie 2021","image":"Individual_floral_elements_01.png"}];
var dropdown = '';
dropdown += '<select id="select">';
Object.keys(images).forEach(function(key) {
dropdown += '<option value="' + images[key].id + '">';
dropdown += images[key].category;
dropdown += '</option>';
});
dropdown += '</select>';
document.getElementsByClassName('dropdown')[0].innerHTML = dropdown;
var categorySelect = document.querySelector('#select');
categorySelect.addEventListener('change', function(evt) {
var item = images.find(function(item) {
return item.id === evt.target.value;
});
console.log( item.image );
});
<div class="dropdown"></div>
Suppose I have this HTML
<form action="#" action="get">
<select name="college" id="college" onchange="selection('college', 'course')">
<option value="">Select an Option</option>
<option value="amity">Amity University</option>
<option value="indraprastha">Indraprasth University</option>
</select>
<br>
<select name="course" id="course" onchange="selection('course', 'stream')" >
<option value="">Select an Option</option>
</select>
<br>
<select name="stream" id="stream">
<option value="">Select an Option</option>
</select>
</form>
I have this JSON,
{
"amity":{
"course":[
{
"name":"B.Tech",
"value":"btech",
"stream":[
{
"name":"Computer Science",
"value":"cse"
},
{
"name":"Information Technology",
"value":"cse"
},
{
"name":"Aerospace Engg.",
"value":"cse"
}
]
},
{
"name":"M.Tech",
"value":"mtech",
"stream":[
{
"name":"Networking",
"value":"net"
},
{
"name":"telecommunications",
"value":"tc"
}
]
}
]
}
}
The Javascript is,
function selection(s1, s2) {
var first = document.getElementById(s1),
second = document.getElementById(s2);
var college = $('#college').val(),
cr = $('#course').val(),
st = $('#stream').val(),
se = $('#sem').val();
$.getJSON("json/select.json", function(data) {
switch(s1) {
case 'college':
$.each(data[college].course, function(key, value) {
second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
}); break;
case 'course':
$.each(data[college].course[].stream, function(key, value) {
second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
}); break;
}
});
}
I am making a dynamic drop-down menu where the next drop down values are fetched from JSON object file, using the reference of previous values. As suggested from my this question (link), I am able to get the value of course (second drop-down) using the course array in the object.
Now, since the values in the second select menu(course) are filled dynamically, I can't figure out how to take the corresponding course array element to fill the next select menu options for stream array.
Since the course property in JSON is an array, I don't know which index element element is chosen from second menu (See the switch case for 'course', the data[college].course[] index is empty). The hardcoded [0] works, but that's not dynamic then.
How to access the stream array using the values of course grabbed from second menu.
I hope I am clear. Thanks in advance!
Just iterate through array of courses to get the stream dynamically:
for (var i = 0; i < data[college].course.length; i++) {
currentStream = data[college].course[i].stream;
}
I.e. using your code:
for (var i = 0; i < data[college].course.length; i++) {
$.each(data[college].course[i].stream, function(key, value) {
second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
});
}
Finding the current stream for your selected course:
// assuming cr = "btech"
for (var i = 0; i < data[college].course.length; i++) {
if (data[college].course[i].value == cr) {
currentStream = data[college].course[i].stream;
break;
}
}
$.each(currentStream, function(key, value) {
second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
});
function selection(s1, s2) {
var first = document.getElementById(s1),
second = document.getElementById(s2);
var college = $('#college').val(),
cr = $('#course').val(),
st = $('#stream').val(),
se = $('#sem').val();
$.getJSON("json/select.json", function(data) {
switch(s1) {
case 'college':
$.each(data[college].course, function(key, value) {
second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
}); break;
case 'course':
var course = data[college].course;
for(var i = 0;i<course.length;i++){
if(course[i].name === cr){ //cr is selected option
$.each(course[i].stream, function(key, value) {
second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
}
}
}); break;
}
});
}
$.each(data.aaData, function(i, obj) {
var opt_data = "<option value=" + obj.value + ">" + obj.text + "</option>";
$(opt_data).appendTo('#reqtype');
});
alert($('#reqtype :selected').text());
var numberOfOptions = $('select#reqtype option').length
alert(numberOfOptions);
After appending the option values to 'reqtype' selectcombobox through jquery, i tried to alert the number of option values and selectedvalue. Its showing the correct number. But in select combobox is not listing the values.still its empty.
I tried with different jqueries, its values are showing properly through jquery. But its not displaying the select options in HTML view.select combobox is empty only.
Here is what you should try:
var opt_data = '';
$.each(data.aaData, function(i, obj) {
opt_data += "<option value=" + obj.value + ">" + obj.text + "</option>";
});
$('#reqtype').html(opt_data);
alert($('#reqtype :selected').text());
I use to populate Dropdown using javascript:
function populateDDL(ddl_id) {
var option_str = "";
var x;
for(x in datalist){
option_str += " <asp:ListItem Value='" + datalist[x] + "' Text='" + datalist[x] + "'></asp:ListItem>"
}
var country_div = document.getElementById(ddl_id);
country_div.innerHTML = option_str;
}
This is sure the datalist is not empty and also Dropdown list populated perfectly..but dnt know why after clicking on my page add button I am not getting the selected value.
Thanks
You should use client side select list control rather than server control to whome you are trying to fill at client side. Its surprised ...
But you should use select control
function populateDDL(ddl_id) {
var option_str = "<select id='ddl_id'>";
var x;
for(x in datalist){
option_str += " <option value='" + datalist[x] + "'>" + datalist[x] + "</option>";
}
option_str += "</select>";
var country_div = document.getElementById(ddl_id);
country_div.innerHTML = option_str;
}