how to call javascript function on asp dropdown list [duplicate] - javascript

I have an ASP drop down list called and I need to load numbers 1 to 20 with 1 being selected as default. How to do this with javascript? I have a sample code but the drop down is not loading. Am I missing something?
<script>
function quantitydropdown() {
var ddl = document.getElementById('quantitydropdownid').getElementsByTagName("select")[0];
for (var i = 1; i <= 100; i++) {
var theOption = new Option;
theOption.text = i;
theOption.value = i;
ddl.options[i] = theOption;
}
}
</script>
<select id="quantitydropdownid" onchange="javascript:quantitydropdown();" runat="server" style="width: 200px;"></select>

So, when the document is ready, we populate the drop down:
// Set up event handler for when document is ready
window.addEventListener("DOMContentLoaded", function(){
// Get reference to drop down
var ddl = document.getElementById('quantitydropdownid');
for (var i = 1; i < 21; i++) {
var theOption = document.createElement("option");
theOption.text = i;
theOption.value = i;
// If it is the first option, make it be selected
i === 1 ? theOption.selected = "selected" : "";
ddl.options[i] = theOption;
}
});
#quantitydropdownid { width:200px; }
<select id="quantitydropdownid" runat="server"></select>

Please try with this code
-----------------------------------------
JS Code
----------------
$(document).ready(function(){
quantitydropdown();
})
function quantitydropdown()
{
for (var i = 1; i <= 20; i++)
{
$("#quantitydropdownid").append( $("<option></option>")
.attr("value", i)
.text(i)
);
}
}
Css Code
-----------
#quantitydropdownid { width:200px; }
HTML Code
-----------
<select id="quantitydropdownid" runat="server"></select>

Related

HTML Datalist won't restrict to 5 or x items to be visible with a scroll

I tried to no avail to get HTML, CSS and Javascript to limit number of items in datalist, for whatever reason, it is isn't working. The list is populated by a loop on a array.
<datalist id="trainNoList">
<script>
if (markers)
{
var options = '';
var trainNoList = [];
for (var i = 0; i < markers.length; i++) {
var trainNo = markers[i][20];
trainNoList.push(trainNo);
options += "<option value='" + trainNoList[i] + "'></option>";
}
}
</script>
</datalist>
<!-- Use JavaScript to pan to the train when an option is selected -->
<script>
$("#trainNoInput").on("input", function() {
var selectedTrainNo = $(this).val();
// Check if the input is a range
var rangeCheck = selectedTrainNo.split("-");
if (rangeCheck.length === 2) {
vehiclestart = rangeCheck[0];
vehicleend = rangeCheck[1];
} else {
// Perform the same actions as in the original code
for (var i = 0; i < markers.length; i++) {
var trainNo = markers[i][20];
if (trainNo == selectedTrainNo) {
var lat = parseFloat(markers[i][2]);
var lng = parseFloat(markers[i][3]);
var setcontentforpopup = "Vehicle"+markers[i][0]+"";
vehiclestart = 1;
vehicleend = 99999999999999;
var popup = L.popup()
.setLatLng([lat, lng])
.setContent(setcontentforpopup)
.addTo(map);
map.flyTo([lat, lng], 16);
break;
}
}
}
});
$("#trainNoInput").on("focus", function() {
console.debug("The trainNoInput field has received a keyup event");
clearTimeout(ajaxtimeout);
});
$("#trainNoInput").on("blur", function() {
ajaxtimeout = setTimeout(foo, 10000);
console.debug("no");
});
$("#trainNoInput").on("keyup", function(event) {
if (event.keyCode === 13) {
markerLookup = {};
markerClusters.clearLayers();
foo();
}
});
</script>
enter image description here
The desire result is simple - limit number of items shown down to 5 or whatever set amount and add a scroll bar to scroll down to see the remainder of the records
enter image description here

How can i display JavaScript function return in textbox?

I have this JavaScript code how can i display the return value in a text box or in a label?
<script>
function getSelectedProjectID() {
var BalanceDue = #Model.BalanceDue;
return {
id: ProjectID
}
}
</script>
you can assign your label an id
<label id="labelId"></label>
, and then just return function content to this label textConent:
document.getElementById("labelId").textContent = getSelectedProjectID();
If you are using vanilla JS, you could do :
let labels = document.getElementsByTagName('label');
for (var i = 0; i < labels.length; i++) {
if (labels[i].htmlFor == 'currency') {
label.innerHTML = getSelectedProjectID().id;
}
}

Adding onClick function to select elements

I have a select tag of dynamically added elements. I need to add an event listener to each of the elements in the select tag except the first which:
adds the text of the element to a list,
makes the focus of the list the first element again, and
removes or hides the clicked element.
The first element is a 'none' element which doesn't need any event listener.
I've tried something like
for (var i = 0; i < array.length; i++)
{
var name = array[i];
var selectElement = document.getElementById(selectElementId);
addToSelectNode(document.getElementById(selectElementId), name);
var thisNode = selectElement.childNodes[i];
if (thisNode.value != "none")
{
thisNode.addEventListener("click", function(event)
{
appendNodeToList("artist-list", i);
selectElement.selectedIndex = 0;
selectElement.remove(selectElement.i);
selectElement.style.display = "none";
});
}
}
function addToSelectNode(element, optionText)
{
var newSelectElement = document.createElement("option");
newSelectElement.text = optionText;
element.add(newSelectElement);
}
function appendNodeToList(listId, text)
{
var newNode = document.createElement("LI");
var textNode = document.createTextNode(text);
newNode.appendChild(textNode);
document.getElementById(listId).appendChild(newNode);
}
Didn't work at all though
A few hours later I've solved my own question. The problem stemmed from trying to remove items in the select tag which just wasn't working - I'm nut sure if it's possible but making it disabled solved it. Anyway here's the result.
HTML:
<select id="artist-select-list">
<option value="none">none</option>
</select>
JavaScript:
window.onload = function()
{
var dropdown = document.getElementById("sampleDropdown");
var n = array.length;
// Loop to add to <select> dropdown
for (var i = 1; i <= n; i++)
{
addToSelectNode(dropdown, array[i - 1]);
}
// Loop to add id's to each element in the dropdown
for (var i = 0; i <= n; i++)
{
dropdown[i].id = "selectNum" + i;
}
// Loop to add event listener
for (var i = 0; i < dropdown.length; i++)
{
dropdown[i].addEventListener("click", function(event)
{
// Regardless of which option the user clicks move shown option to "none" (first index in dropdown)
dropdown.selectedIndex = 0;
if (event.target.id != "selectNum0")
{
// Disable once clicked
event.target.disabled = true;
// Do other things here in relation to event.target
}
});
}
}
var array =
[
"sampleText1", "sampleText2"
];
function addToSelectNode(element, optionText)
{
var newSelectElement = document.createElement("option");
newSelectElement.text = optionText;
element.add(newSelectElement);
}

Jquery code won't run loaded from footer, but run from console

I'm trying to get a value and pass it to a hidden input in order to send form data via $_POST. I have a dropdown button and the following code in order to update the value when a user select an option:
jQuery(document).ready(function($) {
var espSeleccionada = $('button[data-id="select-especialidad"]');
espSeleccionada.on("click", function() {
var x = $(this).text();
$('#boton-prueba').text(x);
});
});
The code is supposed to pass the value from one button to another, as shown in here the example, but, when I load the code from WordPress header/footer/theme nothing happens. Instead, when I write it on the console it works fine. There are no JS errors in console.
Please note that I'm using .text() to test if the code works, but it would have .val() before going live.
This is the button HTML:
<button type="button" class="btn dropdown-toggle btn-default" data-toggle="dropdown" data-id="select-especialidad" title="Hacienda" aria-expanded="false"><span class="filter-option pull-left">Hacienda</span></button>
Here is an example: https://fiddle.jshell.net/t9mvoxj5/
EDIT TO INCLUDE THE FULL CODE:
( function( $ ) {
var num_cols = 3,
container = $('#menu-preparadores-de-oposiciones-en'),
listItem = 'li',
listClass = 'sub-list';
container.each(function() {
var items_per_col = new Array(),
items = $(this).find(listItem),
min_items_per_col = Math.floor(items.length / num_cols),
difference = items.length - (min_items_per_col * num_cols);
for (var i = 0; i < num_cols; i++) {
if (i < difference) {
items_per_col[i] = min_items_per_col + 1;
} else {
items_per_col[i] = min_items_per_col;
}
}
for (var i = 0; i < num_cols; i++) {
$(this).append($('<ul ></ul>').addClass(listClass));
for (var j = 0; j < items_per_col[i]; j++) {
var pointer = 0;
for (var k = 0; k < i; k++) {
pointer += items_per_col[k];
}
$(this).find('.' + listClass).last().append(items[j + pointer]);
}
}
});
if ($("body").hasClass("page-id-64")) {
$('.tab-content').addClass('col-sm-9');
$('#custom-tabs-0').tabCollapse();
}
} ) ( jQuery );
jQuery(document).ready(function($) {
var espSeleccionada = $('button[data-id="select-especialidad"]');
espSeleccionada.on("click", function() {
var x = $(this).text();
$('#boton-prueba').text(x);
});
});
Well, the code is fine, the problem is that the target button[data-id="select-especialidad"] is being used by bootstrap-select and even if bootstrap-select loads before my code, it takes a few seconds (or at least a bit) to process the information.
So the code should be wrapped after a function that checks that the event has been loaded. This is the final code:
$('#select-especialidad').on('loaded.bs.select', function (e) {
var y = $(this).val();
$('#select-especialidad-hidden').val(y);
var espSeleccionada = $('button[data-id="select-especialidad"] > span.filter-option.pull-left');
espSeleccionada.on("click", function() {
var x = $(this).text();
$('#select-especialidad-hidden').val(x);
});
});
loaded.bs.select here more info on the bootstrap-select events.

how to store value of multiselect listbox in javascript

I have one multiselect listbox in my HTMl.
I want to get values of selected items of listbox in javascript
My html code:
<select id="schools" size="5" multiple="multiple">
<option value="352">Byskovskolen</option>
<option value="355">Heldagsskolen Specialtilbud</option>
<option value="372">Plejecenter Solbakken</option>
</select>
My Javascript code:
function getData()
{
var allSchools = [];
var s = document.getElementById("schools");
alert("schools lenght " + s.options.length);
for (var i = 0; i < s.options.length; i++) {
if (s.options[i].selected == true) {
var schoolid = s.options[i].value;
alert(s.options[i].value);
allSchools.push(schoolid);
}
}
}
Values can be seen alerted with alert box but not getting stored in variable.
How can I store it in variable.
It works fine if you comment/uncomment the right lines. Try this:
function getData() {
var allSchools = [];
var s = document.getElementById("schools");
for (var i = 0; i < s.options.length; i++) {
if (s.options[i].selected == true) {
var schoolid = s.options[i].value;
allSchools.push(schoolid);
}
}
console.log(allSchools);
}
DEMO: http://jsfiddle.net/4qYht/1/
Uncommented one line (var schoolid) and added a print out for the allSchools variable.
function getData()
{
var allSchools = [];
var s = document.getElementById("schools");
alert("schools lenght " + s.options.length);
for (var i = 0; i < s.options.length; i++) {
if (s.options[i].selected == true) {
var schoolid = s.options[i].value;
allSchools.push(schoolid);
}
}
console.log(allSchools);
}
uncomment the schoolid assignment line
var schoolid = s.options[i].value;
allSchools.push(schoolid);
or
use allSchools.push(s.options[i].value); instead of allSchools.push(schoolid);
You have commented out the main line ,which would store the value in a variable.
// var schoolid = s.options[i].value;
apart from that rest of your code is perfect.
here is the corrected code :
function getData()
{
var allSchools = [];
var s = document.getElementById("schools");
alert("schools lenght " + s.options.length);
for (var i = 0; i < s.options.length; i++) {
if (s.options[i].selected == true) {
// var schoolid = s.options[i].value;
alert(s.options[i].value);
allSchools.push(schoolid);
}
}
}
Happy coding:)

Categories

Resources