I am new to JavaScript programming. My program gives me another dropdown
menu based on the selection of the first dropdown menu. I am trying figure out how I can add checkbox into my dropdown so that I can check different types of fruits or
vegetables.
<script>
window.onload = function() {
// provs is an object but you can think of it as a lookup table
var provs = {
'Vegetable': ['Broccoli', 'Cabbage','Carrot'],
'Fruit': ['Tomato', 'Apple','Orange']
},
// just grab references to the two drop-downs
food_select = document.querySelector('#food'),
type_select = document.querySelector('#type');
// populate the drop-down
setOptions(food_select, Object.keys(provs));
// populate the town drop-down
setOptions(type_select, provs[food_select.value]);
// attach a change event listener to the drop-down
food_select.addEventListener('change', function() {
// get the towns in the selected province
setOptions(type_select, provs[food_select.value]);
});
function setOptions(dropDown, options) {
// clear out any existing values
dropDown.innerHTML = '';
// insert the new options into the drop-down
options.forEach(function(value) {
dropDown.innerHTML += '<option name="' + value + '">' + value + '</option>';
});
}
};
</script>
<body>
<select id="food"></select><br><br><br>
<select id="type"></select>
<body>
Related
I have a ASP.Net MVC Kendo Grid with checkbox selection, as the documentation I added the checkbox using columns.Select().Width(50); as, then I want to fill an array of selected checkboxes inside of onChange function with javascript as:
Note: the stations array already have some values I.E [1,2,3], so I want to add new values in the next script
function onChange(e) {
const grid = $("#grid").data("kendoGrid");
var items = grid.items();
let ids = '';
grid.select().each(function() {
if (ids === '')
ids = grid.dataItem(this).StationId.toString();
else
ids = ids + ',' + grid.dataItem(this).StationId.toString();
stations.push(grid.dataItem(this).StationId);
})
}
The problem is on each check it is adding all existing checked checkboxes, I have no way to do something like if(checkbox is not checked) do a pop instead a push.
How can I check if clicked checkbox is checked or not in order to implement push or pop logic?
The select method will return all rows that are currently selected. If you need to figure out which is the checkbox that the user clicked last, you can probably toggle a class when the checkbox is checked/unchecked
function onChange(e) {
const grid = e.sender;
var items = grid.items();
let ids = '';
grid.select().each(function(idx,itm) {
$(itm).find("input").hasClass("checkedFlag") ?
kendoConsole.log(grid.dataItem(itm).ProductName + " was checked") :
kendoConsole.log(grid.dataItem(itm).ProductName + " was NOT checked");
})
var selected = $.map(this.select(), function(item) {
return $(item).text();
});
kendoConsole.log("Selected: " + selected.length + " item(s), [" + selected.join(", ") + "]");
}
function onDataBound(arg) {
$("input.k-select-checkbox").change(function(){
$(this).toggleClass("checkedFlag")
})
kendoConsole.log("Grid data bound");
}
If you are interested in only the Id's of the selected items then the Grid exposes a selectedKeyNames method, that you could use instead.
The change event of the Kendo grid will fire when the user selects or deselects a table row or cell in the grid (documentation), but it does not provide us with which rows are selected or deselected.
What you will need to do is store the selected items outside of the grid, compare it to the results of the select method in the change event, then store the updated results.
Something along these lines:
var selectedRecords = [];
function onChange(e) {
var updatedSelectedRecords = e.sender.select();
if (selectedRecords) {
var recordsSelected = updatedSelectedRecords.filter(record => !selectedRecords.includes(record)).map(record => record.StationId.toString());
stations.push(...recordsSelected);
var recordsDeselected = selectedRecords.filter(record => !updatedSelectedRecords.includes(record));
// do something with deselected records?
}
selectedRecords = updatedSelectedRecords;
}
I'm trying to keep a destination Option selected if it's already selected. If the user chooses a new client, each Select needs to change destination Options (there are often dozens of destinations per client), but keep the currently selected one if it's already in the list.
I've tried getting $.each() of the Selects, emptying them, and then $.append()ing them with the list of destinations, but it's only changing the second of three selects.
$('#client_id').on('change', function () { // Client is selected, load branch destinations
// AJAX server-side script with the client id to fetch client branches
$.post('/directtransit/getbranchlist', {'id': id}, function (data) {
// Change all of the line items' destination options based on client branches
$('select[id^="destination"]').each(function(){
var currentDestination = $(this).val(); // Get items currently selected destination
$(this).empty().append('<option></option>');
$.each(branches, function (k, v) { // Populate select options for each of the line items
var option = '<option value="' + v.id + '">' + v.name + '</option>';
// If the currently selected location is in the new option list...
// ... keep it selected
if (v.id === currentDestination) {
option = '<option value="' + v.id + '" selected>' + v.name + '</option>';
}
$(this).append(option);
});
});
});
});
Shouldn't it be changing all of them?
I want to repeatedly show drop downs in a table in order to take its value and update specific records.
I have able to make dynamic dropdown using this
function getEmployeeTaskStatusMain(){
var go_path = "Employee_Switch_Person.php?action=getEmployeeTaskStatusMain&vars=0";
$jq.get(go_path,
{
}, function(data)
{
if(JSON.parse(data).length == 0){
console.log(data);
return data;
}
else {
var dataToAppend;
dataToAppend = "<select name='EmployeeTaskStatus' class='EmployeeTaskStatus form-control'>"
dataToAppend += "<option value='0'>Select Status</option>";
//console.log(" " + data);
dataParse = JSON.parse(data);
for (var i = 0; i < dataParse.length; i++)
{
//console.log(dataParse[i]);
dataToAppend += "<option value=" + dataParse[i].TaskStatusMainId + ">" + dataParse[i].TaskStatusMain + "</option>";
}
dataToAppend +="</select>";
$jq(".taskStatusMain").html(dataToAppend);
//getEmployeeTaskStatusDetail(0);
return dataParse;
}
});
}
But do i need to repeat the above function for every table row in order to show the dropdown in each row with dynamic id(so that i can get it selected value)?
The table (is also making dynamically) where i have to show dropdown with each record and i want to take each dropdown selected value in order to update specfic record. what is the handy way?
Remember, There are two drop downs one dropwdown value updating on another dropdown value selection.
Why don't you return this data in the users array and render it in the HTML file inside the for loop for each user and loop through his status to render the drop down?
And then update that row using the on change event for the select tag
<tr>
<th>status></th>
</tr>
foreach($users as $user){
<tr>
<td>
<select>
foreach($user->status as $status-item){
<option>$status-item->name</option>
}
</select>
</td>
</tr>
}
I have a dropdown whose options get filled dynamically:
function populateDropdown(dropdownNum) {
// invokeWebService uses $.ajax
json = invokeWebService("GET", "/webservice/dropwdownOptions");
optionsHtml = "";
$.each(json, function(count, jsObj) {
optionValue = jsObj.name
optionsHtml+="<option>" + optionValue + "</option>";
});
var dropdownId = "#NRdropdown_" + dropdownNum;
$(dropdownId).html(optionsHtml);
}
function display(blockNum) {
var url = "/webservice/blocks" + blockNum;
var response = invokeWebService("GET", url);
var replacementHtml = "";
var currBlock = "blah";
$.each(response, function(i, block) {
currName = block.name;
var textfield = "<input type='text' id='blockValue" + block.id +
"'>";
var dropdownMenu = "<select id=\"NRdropdown_" + i +
"\"onClick=\"populateDropDown(" + i +
")\"><option>Existing Blocks</option>"
var submitButton = "<input type='submit' value='UPDATE' id='" +
block.id + "'><br><br>";
replacementHtml = currName + textfield + dropdownMenu + submitButton;
});
$("#main").html(replacementHtml);
}
The javascript function "populateDropdown(dropdownNum)":
Makes the ajax request
Parses the json response for the option values into an html string called optionsHtml
Replaces the inner html of the select element with the option values via:
var dropdownSelector = "#NRdropdown_" + dropdownNum;
$(dropdownSelector).html(optionsHtml)
1) When I click on the dropdown arrow, I STILL see "Existing Blocks".
2) After 1 sec I see the first dynamically generated option UNDERNEATH the "Existing Blocks" option, I don't see the other dynamically generated options.
3) Then I click outside the dropdown and see the dropdwon showing the first dynamically generated value.
4) Finally I click the dropdown arrow again and it works as it should with all the dynamically generated values.
How do I make it work so that:
When the page first loads, the dropdown shows "Existing Blocks".
Once I click the dropdown arrow, the dropdown should show all dynamically generated values without the "Existing Blocks" value.
Thanks!
the dropdown listener should be for onmousedown, not onclick
I have select boxes in which values are getting appended dynamically thru an array.
Now suppose if i have 4 values in my 1st select box, then i want only 3 values in the 2nd select box excluding the value that has already been selected in the 1st select box.
now there will be 3 values in 2nd select box and if i select a value then the 3rd select box will have only 2 values excluding the one already selected in 2nd select box and so on...
please help on how should i filter
Try this
HTML
<div class="result"></div>
JS
var array = ['first', 'second', 'third'];
var temp;
new_select();
function new_temp() {
temp = "";
temp += '<option value="null"></option>';
array.forEach(function (entry, index) {
temp += '<option value="' + index + '">' + entry + '</option>';
});
}
function new_select() {
if (array.length > 0) {
new_temp();
$('.result').append('<select class="mine_select">' + temp + '</select>');
$(".mine_select").change(function () {
array.splice($(this).val(), 1);
new_select();
});
}
}