how to use arrays within select dropdown select - javascript

I am trying to populate a dropdown select with an array using jQuery.
Here is my code:
<div class="form-group row">
<label class="col-xl-3 col-lg-3 col-form-label">Numbers</label>
<div class="col-lg-9 col-xl-6">
<div class="form-inline">
<select name="sabb" class="req form-control form-control-lg form-control-solid" id="age-range-2" autocomplete="off" required />
</select>
<label class="col-xl-1 col-lg-1 col-form-label">to</label>
<select name="eabb" class="req form-control form-control-lg form-control-solid" id="second-2" autocomplete="off" required />
</select>
</div>
</div>
</div>
My accompanying jQuery is as follows:
$(function() {
var $select = $("#age-range-2");
for (i = 18; i <= 60; i++) {
$select.append($('<option></option>').val(i).html(i))
}
$("#age-range-2").change(function() {
var val = parseInt($("#age-range-2").val());
$("#second-2").html("");
for (i = val + 1; i <= 60; i++) {
$("#second-2").append("<option value='" + i + "'>" + i + "</option>");
}
});
});
I am trying to add an array that includes numbers and letters instead of a for loop which should be something like this: var numbers = [1K, 2K, 3K, 4K, 5K];
Here is a visual:

I think this what you need:
for (i = 1; i <= 50; i++) {
var o = new Option( i + "K", i);
$(o).html( i + "K");
$("#age-range-2").append(o);
}
for (i = 18; i <= 60; i++) {
var o = new Option( i + "K", i);
$(o).html( i + "K");
$("#second-2").append(o);
}
You can see result in JSFiddle here
Edited:
If you need predefined array:
var numbers = [1,4,8,14,20,50,100];
$.each(numbers, function( index, value ) {
var o = new Option( value + "K", value);
$(o).html( value + "K");
$("#age-range-2").append(o);
});

Related

using .on to listen for event not working

I am trying to use .on to listen for an event.
html:
<div class="form-group" id="group_names">
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name ="name1"><br>
</div>
JS:
for (n = 1; n < inputLength+3 ; ++n) {
var test2 = document.getElementById(dude+n);
$(test2).on('change', '#group_names', forFunction);
}
The change to the input field is not being recognized.
Additionally, I am hoping .on will recognize changes made to new html i am injecting using the following function:
var dude = "name";
function forFunction() {
for (m = 1; m < inputLength + 1; ++m) {
var test = document.getElementById(dude + m)
if (test.value != "") {
var txt = "<input type=\"text\" class=\"form-control name\" placeholder=" + dude + (m + 1) + " id=" + dude + (m + 1) + " name=" + dude + (m + 1) + "><br>";
document.getElementById('group_names').insertAdjacentHTML('beforeend', txt);
//function updateHTML(txt)
}
}
}
I am not sure if my syntax for .on is correct. I am trying to use "#group_names" as the selector, but not sure if I am doing it right.
Thanks
You probably want to use event delegation on the parent div instead.
$('#group_names').on('change', 'input.form-control.name', forFunction);
Consider the following jQuery code.
$(function() {
var inputFields = $("input[id*='name']");
function forFunction(evt) {
console.log(evt.type);
inputFields.each(function(i, el) {
var n = i + 1;
if ($(el).val() != "") {
console.log("Value Detected");
$("<input>", {
type: "text",
class: "form-control name",
placeholder: "group" + n,
id: "group" + n,
name: "group" + n
}).insertBefore("#group_names");
}
});
}
inputFields.on("change", forFunction);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group" id="group_names">
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name="name1"><br>
</div>
This should work for all of the Input items.

JavaScript class did not function in asp.net

I have created a javascript function in my aspx page..
below are the sample code,
<script type="text/javascript">
$(document).ready(function () {
console.log("ready!");
var output = [];
var yr = 1950;
for (var i = 0; i <= 70; i++) {
if (i == 0) {
output[i] = '<option value="0" selected="selected"> Choose Year</option>';
}
else {
output[i] = '<option value="' + (parseInt(1950) + parseInt(i - 1)) + '">' + (parseInt(1950) + parseInt(i - 1)) + '</option>';
}
}
$('#yearid').get(0).innerHTML = output.join('');
});
$("#yearid").change(function () {
var select = $("#yearid option:selected").val();
$("#yearval").val(select);
});
</script>
I would like this function execute in the property such as
<div class="col-md-4 form-group">
<span>Year : </span>
<select id="yearid" class="form-control" runat="server">
</select>
<input id="yearval" type="hidden" runat="server"/>
</div>
As the code running, the javascript function above should be executed and display the " Choose Year" propery inside as shown above.
I try to run this code but nothing happens to the property. Any help would be appreciated. Thank u.
Your code seems to be working as below. However you may be missing the jQuery script so you can check if that exists.
$(document).ready(function () {
console.log("ready!");
var output = [];
var yr = 1950;
for (var i = 0; i <= 70; i++) {
if (i == 0) {
output[i] = '<option value="0" selected="selected"> Choose Year</option>';
}
else {
output[i] = '<option value="' + (parseInt(1950) + parseInt(i - 1)) + '">' + (parseInt(1950) + parseInt(i - 1)) + '</option>';
}
}
$('#yearid').get(0).innerHTML = output.join('');
});
$("#yearid").change(function () {
var select = $("#yearid option:selected").val();
$("#yearval").val(select);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-4 form-group">
<span>Year : </span>
<select id="yearid" class="form-control" runat="server">
</select>
<input id="yearval" type="hidden" runat="server"/>
</div>

Pure Javascript populate data to select options from JSON URL

I had a javascript function that pulls data from url, however im having "undefined" options when im trying to add it on the next select element.
Here is my code.
First Select element
<div class="col-sm-6">
<label class="font-bold no-margins">City/State *</label>
<select name="city_state" class="form-control required" id="city_state" onchange="populateSelect(this);">
<?php
echo '<option value="'.$city_state_data->id.'">'.$city_state_data->name.'</option>';
foreach ($city_states as $city_state) {
if($city_state_data->id != $city_state->id)
{
echo '<option value="'.$city_state->id.'">'.$city_state->name.'';
}
}
?>
</select>
</div>
Second Select element
<div class="col-sm-12 col-xs-12">
<div class="form-group has-feedback">
<label class="font-bold no-margins">Locale *</label>
<select name="locale" class="form-control required" id="locale">
<?php
echo '<option value="'.$locale_data->id.'">'.$locale_data->name.'</option>';
foreach ($locales as $locale) {
if($locale_data->id != $locale->id){
echo '<option value="'.$locale->id.'">'.$locale->name.'';
}
}
?>
</select>
</div>
Now my JS script
<script>
function populateSelect(item) {
// json url
//var url = 'citystate/' + item.value + '/locales/';
var url = '[{"id":33,"name":"Boni Avenue"},{"id":34,"name":"Shaw Boulevard"}]';
// empty select
document.getElementById('locale').options.length = 0;
var ele = document.getElementById('locale');
for (var i = 0; i < url.length; i++) {
// populate select element with json
ele.innerHTML = ele.innerHTML +
'<option value="' + url[i]['id'] + '">' + url[i]['name'] + '</option>';
}
}
</script>
Can you please help me how can i fix this undefined values in the select box.
Thank you.
You need to parse your JSON string if you want to access the data.
function populateSelect(item) {
var url = '[{"id":33,"name":"Boni Avenue"},{"id":34,"name":"Shaw Boulevard"}]';
var data = JSON.parse(url);
// empty select
document.getElementById('locale').options.length = 0;
var ele = document.getElementById('locale');
for (var i = 0; i < data.length; i++) {
// populate select element with json
ele.innerHTML = ele.innerHTML +
'<option value="' + data[i]['id'] + '">' + data[i]['name'] + '</option>';
}
}
Hope it helps!

Dynamically assign ID and attach data in JavaScript & jQuery using two nested for loops

I am having some trouble to get through this below jsfiddle task.
jsfiddle link
I want to do the same function using dynamic id.
I tried so many methods, but nothing works.
Please don't recommend to change the infrastructure. The page has been already designed the same kind of structure.
I need to achieve this same kind of function using two nested for loops with dynamic id.
HTML:
<div class="col-md-4" id="beforeDiv0">
<div class="col-md-2" style="padding-right: 0px; padding-top: 5px;">
<label for="Amount" style="font-weight:bold;">Amount:</label>
</div>
<div class="col-md-6">
<input class="form-control" type="number" id="textboxId0" value="1000" />
</div>
</div>
<br/><br/>
<div class="col-md-4" id="beforeDiv1">
<div class="col-md-2" style="padding-right: 0px; padding-top: 5px;">
<label for="Amount" style="font-weight:bold;">Amount:</label>
</div>
<div class="col-md-6">
<input class="form-control" type="number" id="textboxId1" value="1000" />
</div>
</div>
Javascript & jQuery:
$(document).ready(function(){
var newAmount = parseFloat(1000) + parseFloat(5);
for(var id=0; id<3; id++){
for (var i = 1; i < 3; i++) {
var html = '<tr style="height:50px;">';
html = html + '<td class="td-Amount" style="text-align: right; font-size: 15px; font-weight: bold;">';
html = html + 'Original: '+ '<span id="OrginalAmount' + i + '">' + 1000 + '</span><br/>' + 'New: <span id="Output' + id + "" + i + '">' + newAmount + '</span></td>';
html = html + '</tr>';
$(html).insertAfter("#beforeDiv" + id);
//var abc = id + "" + i;
//var xyz = '#textboxId' + id;
//var zyx = "Output"+id+""+i;
}
}
var myArr = new Array();
var myArr2 = new Array();
for(var id=0; id<3; id++){
var xyz = '#textboxId' + id;
myArr[id] = id;
for (var i = 1; i < 3; i++) {
myArr2[i] = i;
var calc = myArr[id] + "" + myArr2[i];
var zyx = "Output" + calc;
//below line is for dynamic id retrieval
/*
$(xyz).on("click change paste keyup", function() {
var x = parseFloat(1000);
var y = parseFloat($(this).val());
var AmtChange = x + y;
document.getElementById(zyx).innerHTML = AmtChange;
});
*/
$("#textboxId0").on("click change paste keyup", function() {
var x = parseFloat(1000);
var y = parseFloat($(this).val());
var AmtChange = x + y;
document.getElementById("Output01").innerHTML = AmtChange;
document.getElementById("Output02").innerHTML = AmtChange;
});
$("#textboxId1").on("click change paste keyup", function() {
var x = parseFloat(1000);
var y = parseFloat($(this).val());
var AmtChange = x + y;
document.getElementById("Output11").innerHTML = AmtChange;
document.getElementById("Output12").innerHTML = AmtChange;
});
}
}
});
I looked at your code, and considered your comments, and if I understand you correctly, then something like this is what you are after:
$('input[id^=textboxId]').on("click change paste keyup", function() {
var id = $(this).attr('id');
id = id.replace(/\D/g,'');
var x = parseFloat(1000);
var y = parseFloat($(this).val());
var AmtChange = x + y;
/**
* The following could not really be simplified, because
* there are no defining data- attributes, or anything
* to identify the table rows as belonging to the textbox.
* When I tried to simplify the selection of "output" spans,
* a span with id Output111 would have been matched by Output11
* and Output1.
*/
$('#beforeDiv' + id).nextUntil('br').each(function(i,el){
$('span[id^=Output]', this).text(AmtChange);
});
});
I tested this on Codepen: https://codepen.io/skunkbad/pen/ayeVLp

Jquery custom filters in HTML

I want create a custom filters using jquery.
I started here
var filters = {};
var data = [];
var filters = {};
filters.id = 0;
filters.title = "Users";
data[0] = filters;
var filters = {};
filters.id = 1;
filters.title = "Title";
data[1] = filters;
var filters = {};
filters.id = 2;
filters.title = "Start date";
data[2] = filters;
var filters = {};
filters.id = 3;
filters.title = "End date";
data[3] = filters;
var filters = {};
filters.id = 4;
filters.title = "Price";
data[4] = filters;
var filters = {};
filters.id = 5;
filters.title = "Category";
data[5] = filters;
var i = 0;
$.each(data, function(index, value) {
if (i < 2) {
$(".chooseFilter").append("<option data-filter-id=" + value.id + ">" + value.title + "</option>");
} else {
$(".chooseFilter").append("<option data-filter-id=" + value.id + " disabled>" + value.title + "</option>");
}
i++;
});
var dataHTMLFilters = [];
dataHTMLFilters[0] = '<input class="user" data-filterid="0" type="text" placeholder="Enter username">';
dataHTMLFilters[1] = '<input class="user" data-filterid="1" type="text" placeholder="Enter title">';
dataHTMLFilters[2] = '<input class="user" data-filterid="2" type="text" placeholder="Enter start date">';
dataHTMLFilters[3] = '<input class="user" data-filterid="3" type="text" placeholder="Enter end date">';
dataHTMLFilters[4] = '<input class="user" data-filterid="4" type="text" placeholder="Enter price">';
dataHTMLFilters[5] = '<input class="user" data-filterid="5" type="text" placeholder="Enter category">';
var limits = [];
limits[0] = 5;
limits[1] = 1;
limits[2] = 2;
limits[3] = 3;
limits[4] = 4;
limits[5] = 5;
$("body").on("change", ".chooseFilter", function() {
var filterId = $(this).find(":selected").attr("data-filter-id");
$(this).parent().prev().html(dataHTMLFilters[filterId]);
});
var buttons = '<div><button class="add">add</button><button class="remove">remove</button></div>';
$("body").on("click", ".add", function(e) {
e.preventDefault();
var filterID = $(this).parent().prev().find("option:selected").attr("data-filter-id");
$(".filters").append("<div class='filter'><div>" + $(".chooseFilter")[0].outerHTML + '</div>' + buttons + "</div>");
$(".filter").last().prepend("<div class='sibling'>" + dataHTMLFilters[$(".filter:last-child .chooseFilter option:not(:disabled)").attr("data-filter-id")] + "</div>");
if ($(".chooseFilter option[data-filter-id=" + filterID + "]:selected").length >= limits[filterID]) {
$(".chooseFilter option[data-filter-id=" + filterID + "]").prop("disabled", true);
var filterIdSelected = $(".chooseFilter option:not(:disabled)").first().attr("data-filter-id");
$(".chooseFilter").last().find("option[data-filter-id=" + filterIdSelected + "]").attr("selected", true);
console.log(dataHTMLFilters[filterIdSelected]);
$(".chooseFilter").last().parent().prev().html(dataHTMLFilters[filterIdSelected]);
}
});
$("body").on("click", ".remove", function(e) {
e.preventDefault();
$(this).parent().parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="filters">
<div class="filter">
<div class="sibling">
<input class="user" data-filterid="0" type="text" placeholder="Enter username">
</div>
<div>
<select class="chooseFilter" style="width: 100%;">
</select>
</div>
<div>
<button class="add ">add</button>
</div>
</div>
</div>
Filters must fulfill,comatibile with:
Take limits to attention in add, remove and change. If limit is equal to instance of length in HTML document filter must be disabled
Basic filters are users, title when filters is only one this two option must be not disabled rest must be disabled when event is add, remove or change
Any ideas how I could do that? I try various method but result always are the same , filters is not compatibile.
If you want some more information how it should work just say.
I see it like this when add,remove and change:
if(users.length >= limit){
//set all option in select where filter is user to disabled = true
}
if(title.length >= limit){
//set all option in select where filter is title to disabled = true
}
if(filters.length > 1){
//options in select set to disable=false
}
if(filters.length < 1){
//options in select set to disable=true and title, users set to false
}

Categories

Resources