Populate the dropdownlist from a specfic year to current year - javascript

I'm creating a dropdownlist of year.
How can I automatically populate the dropdownlist?
For example, I will be adding a dropdown value 1980, can I use jQuery to populate it to the current year, so I will not need to type all the year?

You can use a for loop between 1980 and the current year, which you can retrieve through the getFullYear() property of a Date object. Try this:
var html = '';
for (var i = 1980; i <= new Date().getFullYear(); i++) {
html += '<option value="' + i + '">' + i + '</option>';
}
$('#mySelect').html(html);
Working example
If you'd prefer to start with the current year and work down, you can use a negative iteration, like this:
for (var i = new Date().getFullYear(); i >= 1980; i--) {
html += '<option value="' + i + '">' + i + '</option>';
}

It's simple using a for loop and adding to string like:
var nowY = new Date().getFullYear(),
options = "";
for(var Y=nowY; Y>=1980; Y--) {
options += "<option>"+ Y +"</option>";
}
$("#years").append( options );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="years"></select>
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getFullYear
http://api.jquery.com/append/

You can use a for loop (http://www.w3schools.com/js/js_loop_for.asp)
function fillDates(startDate){
yr = new Date().getFullYear();
options = "";
for(var i=startDate, i<=yr, i++){
options += ("<option value = "+i+">"+i+"</option");
}
$("select").append(options);
}
fillDates(1908);

chong there are lots of answers, i am little bit let to update my answer to jsFiddle.
fiddle : https://jsfiddle.net/eua98tqa/8/
HTML:
<html>
<head>
</head>
<body>
<select>
</select>
</body>
</html>
jQuery:
var fromYear = 1980;
var currentYear = new Date().getFullYear();
for (var i = fromYear; i <= currentYear; i++) {
$("select").append('<option value="' + i + '">' + i + '</option>');
}

I have more than one year dorpdowns, for which I wanted to compute year list from one specific year till current year. Commenting my final solution, may be somebody can find this useful:
function populateYearList(minYear, currentYear, selectElement){
var max = currentYear, min = minYear;
for (var i = min; i<=max; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
selectElement.append(opt);
}
//selecting current year by default and adding "selected" attribute to it
$(selectElement).val(max)
.find("option[value=" + max +"]")
.attr("selected","selected");
}
calling on page load
var selectElement = $('.select-class');
populateYearList('2015', currentYear, selectElement);

please refer code below
<input type="text" id="inputyear">
<select id="selectyear">
</select>
<input type="button" value="Generate" onclick="FillYears()">
<script type="text/javascript">
function FillYears(){
for(var i=parseInt($("#inputyear").val());i<=(new Date().getFullYear());i++)
{
$("#selectyear").append($("<option>"+i+"</option>"));
}
}
</script>

Related

How to add a year in select tag using javascript

I need to add the year 2015 to present year in a select tag in html using javascript. I have a code below but it does not display or return the expected value and the select tag is also empty. how can i achieved that?
HTML:
<div class="cell colspan3">
<div class="input-control select full-size">
<h5>Year:</h5>
<select id="cboYear">
<option value="0" selected disabled hidden>Select Year</option>
</select>
</div>
</div>
JAVASCRIPT:
function Years() {
var today = new Date(),
yyyy = today.getFullYear()
for (var i = 0; i < 10; i++, yyyy++) {
for (var x = 1; x > i; x++) {
$('#cboYear').append('<option value ="' + x + '">' + yyyy + '</option>')
}
}
}
.add() method
get reference to <select> tag | .querySelector(selector);
create an <option> tag | .createElement("option");
add text | option.text property
set value | option.value property
then add <option> to <select> | select.add(option) method
repeat process through a for loop
Demo
function setOpt(selector, text, value) {
var node = document.querySelector(selector);
var opt = document.createElement("option");
opt.text = text;
opt.value = value;
node.add(opt);
return false;
}
function T(t) {
var now = new Date();
var time;
switch (t.toLowerCase()) {
case 'm':
time = now.getMonth() + 1;
break;
case 'd':
time = now.getDate();
break;
case 'y':
time = now.getFullYear();
break;
default:
break;
}
return time;
}
for (let i = 2015; i <= T('y'); i++) {
setOpt('#cboYear', i, i);
}
<div class="cell colspan3">
<div class="input-control select full-size">
<h5>Year:</h5>
<select id="cboYear">
<option value="0" selected disabled hidden>Select Year</option>
</select>
</div>
</div>
Assuming that you are using jquery in your web app, I made a little modification in your posted code. Here is the code for appending years 2015 to present using loops in javascript.
<script type="text/javascript">
$(document).ready(function(){
Years(); // this will run the function Years() after the DOM (document object model) has been loaded.
});
function Years() {
// get the current date and put in today variable
var today = new Date();
// get the year and put it in yyyy variable
yyyy = today.getFullYear();
// appending from year 2015 up to present in the select tag
for (var index = 2015; index <= yyyy; index++) {
$('#cboYear').append('<option value ="' + index + '">' + index + '</option>')
}
}
</script>
Hope it's help you:
HTML
<div class="cell colspan3">
<div class="input-control select full-size">
<h5>Year:</h5>
<select id="cboYear"></select>
</div>
</div>
Script code
function Years() {
var today = new Date();
var yyyy = today.getFullYear();
var content = '<option value="-1">Select Year</option>';
for (var x = 1; x <= 10; x++, yyyy++) {
content += '<option value="' + x + '">' + yyyy + '</option>';
}
$('#cboYear').append(content);
}
Don't forget to add jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Where to place my code to select first option of <select> with jQuery?

I need to select first option of select with jQuery. My code is a bit complex and can't figure out how to make it work. Thanks
Html:
'sortingHtml': '<select id="bc-sf-filter-top-sorting-select">{{sortingItems}}</select>'
Javascript:
BCSfFilter.prototype.buildFilterSorting = function() {
if (bcSfFilterTemplate.hasOwnProperty('sortingHtml')) {
jQ(this.selector.topSorting).html('');
var sortingArr = this.getSortingList();
if (sortingArr) {
// Build content
var sortingItemsHtml = '';
for (var k in sortingArr) {
sortingItemsHtml += '<option value="' + k +'">' + sortingArr[k] + '</option>';
}
sortingItemsHtml = '<option disabled="disabled" selected>Sort by</option>' + sortingItemsHtml
var html = bcSfFilterTemplate.sortingHtml.replace(/{{sortingItems}}/g, sortingItemsHtml);
jQ(this.selector.topSorting).html(html);
// Set current value
jQ(this.selector.topSorting + ' select').val(this.queryParams.sort);
}
}
};
Code to select the first option:
$("#bc-sf-filter-top-sorting-select").val($("#bc-sf-filter-top-sorting-select option:first").val());
$("#bc-sf-filter-top-sorting-select option:first").prop("selected", true);

How to display select option from dynamic data drop down list

My concept is to perform credit card validation.. In credit card year the data should be generated dynamically depending upon the current year.. it should show only upcoming years.
Eg. We are in 2016.. So that the dropdown data will be display like 2016 to 2040.. the dropdown data is dynamic.. i have achieved it as well.. But, Here my problem is to display "select Option"
I want to show select option first for performing validation.. Give me some idea to do that..
Here is my sample code..
<select id="ccyear" name="ccyear"></select><br>
<span>
<script>
var start =new Date().getFullYear();
var end = new Date().getFullYear() + 24;
var options = "";
for(var year = start ; year <=end; year++)
{
options += "<option>"+ year +"</option>";
}
document.getElementById("ccyear").innerHTML = options;
</script>
</span>
try to this...
<select id="ccyear" name="ccyear"></select><br>
<span>
<script>
var start =new Date().getFullYear();
var end = new Date().getFullYear() + 24;
var options = "";
var i = 0;
for(var year = start ; year <=end; year++)
{
if (i == 0){
options += "<option selected>Select option</option>";
i++;
} else {
options += "<option value="+ year+">"+ year +"</option>";
}
}
document.getElementById("ccyear").innerHTML = options;
</script>
</span>
Change this var options = ""; line to var options = "<option>Select Option</option>";
<select id="ccyear" name="ccyear"></select><br>
<span>
<script>
var start =new Date().getFullYear();
var end = new Date().getFullYear() + 24;
var options = "<option>Select Option</option>";
for(var year = start ; year <=end; year++)
{
options += "<option>"+ year +"</option>";
}
document.getElementById("ccyear").innerHTML = options;
</script>
</span>
Change this:
var options = "";
to this:
var options = "<option>Select Option</option>";
Here is the JSFiddle demo
I think this is useful for you
<select id="ccyear" name="ccyear">
<option value=''> Select Project </option>
</select><br>
<script>
var start =new Date().getFullYear();
var end = new Date().getFullYear() + 24;
var options = "";
for(var year = start ; year <=end; year++)
{
options += "<option>"+ year +"</option>";
}
document.getElementById("ccyear").innerHTML = "<option value=''> Select Option </option>"+options;
</script>
You can just use the append function of jQuery to do that.
Also I would suggest providing a value attribute to each option element.
Your code would look like this.
var start = new Date().getFullYear();
var end = start + 24;
for (var year = start; year <= end; year++) {
console.log("loop");
$("#ccyear").append('<option value="' + year + '">' + year + '</option>');
}
You can check out the code here
https://jsfiddle.net/arijitkanrar/pfgwa2n2/
onchange event is easy to get value of user select
<select id="ccyear" name="ccyear" onchange="test()"></select><br>
<span>
<script>
( function (){
var start =new Date().getFullYear();
var end = new Date().getFullYear() + 24;
var options = "";
for(var year = start ; year <=end; year++)
{
options += "<option>"+ year +"</option>";
}
document.getElementById("ccyear").innerHTML = "<option>Select option</option>"+options;
console.log( document.getElementById("ccyear").value);
})()
function test(){
console.log( document.getElementById("ccyear").value);
}
</script>
</span>
If you'r working with php then why don't try to make with php script
try this php code -
<?php
date_default_timezone_set('Asia/Kolkata');
$current_year = date('Y');
$end_year = date('Y', strtotime('+24 year'));
$select = '<select id="ccyear" name="ccyear">';
for($i = $current_year; $i <= $end_year; $i++)
$select .= '<option value="'.$i.'">'.$i.'</option>';
$select .= '</select>';
echo $select;
?>

Can't get values from input via JavaScript

I'm simply trying to take inputs from html input fields.
The problem is, my function always evaluate the inputs to 0.
What should I do my code to work as I expected (to take inputs from fields and pass them to my javascript functions). If there is alike answered questions asked before, please refer.
Please do not propose jQuery solutions - I can't follow its full of parantheses syntax.
P.S. Zeros on ternary, are just for avoiding NaNs. Nothing else.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<strong>Data</strong>
<hr>Price:
<input type="text" id="price" value="0">
<br>Prepay:
<input type="text" id="prepay" value="0">
<br>Percent:
<input type="text" id="percent" value="0">
<br>Month:
<input type="text" id="month" value="0" onchange="refactorTable('payment-plan')">
<br>
<hr>
<strong>Table</strong>
<table id="payment-plan" border="1">
<thead>
<tr>
<td>Month</td>
<td>Amount</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript">
var Sum = parseInt(document.getElementById('price').value);
var PrePayment = parseInt(document.getElementById('prepay').value);
var Percent = parseInt(document.getElementById('percent').value);
var Month = parseInt(document.getElementById('month').value);
//console.log(Sum +" -- "+ PrePayment +" -- "+ Percent +" -- "+ Month);
function monthlyPaymentPlan(Sum, PrePayment, Percent, Month) {
var BigJohn = Sum - PrePayment;
//console.log(BigJohn);
var monthly = Math.ceil((BigJohn + BigJohn * Percent) / Month);
return Month > 0 ? monthly : 0;
}
function lastMonth(Sum, PrePayment, Percent, Month) {
return Month > 0 ? Sum - monthlyPaymentPlan(Sum, PrePayment, Percent, Month) * (Month - 1) : 0;
}
function refactorTable(tbl_id) {
var table = document.getElementById(tbl_id).getElementsByTagName('tbody')[0];
table.innerHTML = "";
var i = 0;
var rows = document.getElementById('month').value;
rows = parseInt(rows);
for (i = 0; i < rows - 1; i++) {
table.insertRow(-1).innerHTML = "<td>" + (i + 1) + "</td><td>" + monthlyPaymentPlan(Sum, PrePayment, Percent, Month) + "</td>";
}
table.insertRow(-1).innerHTML = "<td>" + rows + "</td><td>" + lastMonth(Sum, PrePayment, Percent, Month) + "</td>";
}
</script>
</body>
</html>
You are getting the values when the page renders, instead of when the function is supposed to run. Place your assignments inside a function and call the function.
// Define the variables globally so they can be used in any function
var Sum;
var PrePayment;
var Percent;
var Month;
// Call this function to set the values of the global variables.
function getValues() {
Sum = parseInt(document.getElementById('price').value);
PrePayment = parseInt(document.getElementById('prepay').value);
Percent = parseInt(document.getElementById('percent').value);
Month = parseInt(document.getElementById('month').value);
}
// Call the getValues function first to set the values and then continue on
// with your function calculations.
function refactorTable(tbl_id) {
getValues();
// Do the rest...
}
You need to get the values at the time the function is called. Right now you're getting the values on page load (which is 0).
function refactorTable(tbl_id) {
var Sum = parseInt(document.getElementById('price').value);
var PrePayment = parseInt(document.getElementById('prepay').value);
var Percent = parseInt(document.getElementById('percent').value);
var Month = parseInt(document.getElementById('month').value);
var table = document.getElementById(tbl_id).getElementsByTagName('tbody')[0];
table.innerHTML = "";
var i=0;
var rows = document.getElementById('month').value;
rows = parseInt(rows);
for(i=0; i<rows-1; i++) {
table.insertRow(-1).innerHTML = "<td>" + (i+1) + "</td><td>" + monthlyPaymentPlan(Sum, PrePayment, Percent, Month) + "</td>";
}
table.insertRow(-1).innerHTML = "<td>" + rows + "</td><td>" + lastMonth(Sum, PrePayment, Percent, Month) + "</td>";
}
You have need to update input variable value on change of id="month" so you can get updated value.
var Sum = '';
var PrePayment = '';
var Percent = '';
var Month = '';
function inputsval() {
Sum = parseInt(document.getElementById('price').value);
PrePayment = parseInt(document.getElementById('prepay').value);
Percent = parseInt(document.getElementById('percent').value);
Month = parseInt(document.getElementById('month').value);
}
function refactorTable(tbl_id) {
inputsval();
//Your other code.....
}
var Sum = parseInt(document.getElementById('price').value);
This is not defining a function, or a macro. This is a one-time calculation of a number, and it seems this is going to happen when the page starts up. So, it won't ever change from its first value (0).
You should probably move these declarations inside of refactorTable. Thankfully, you already have them set up to be passed as arguments.

Jquery / Javascript - most efficient way to build a select menu?

I'm using jquery and trying to tune my select menu builder to run much quicker.
I was using each and append, however I've since switched to a standard for loop and currently trying to convert my options from using append to concatenated string appended to my select option using .html(). I seem to be at a loss trying to convert my var option object back to an html string. Could someone please tell me what I might be doing wrong.
$.selectMenuBuilder = function(json) {
var myselect = $("#myselect");
var list = "<option value=\"\">> Select Account Number</option>";
var l= json.funding.length;
for(var i=0;i<l; i++) {
var funding = json.funding[i];
var option = $("<option value=\"" + funding.id + "\">" + funding.accountNumber + "</option>")
if(someLogic) {
option.attr("selected", "selected");
}
//Having trouble here converting option object back to html.
list += option.html();
}
list += "<option value=\"addnew\">+ New Account Number</option>";
myselect .html(list);
}
You can totally do away with using jQuery for creating the option elements (unless theres some other untold reason you're using it).
i.e. Instead of
var option = $("<option value=\"" + funding.id + "\">" + funding.accountNumber + "</option>")
if(someLogic) option.attr("selected", "selected");
You can do:
list += "<option value=\"" + funding.id + "\" "+ (someLogic?'selected':'') +">" + funding.accountNumber + "</option>"
Secondly, $(option).html() will return the innerHTML of the option element, not including the option tag name. For doing this in a cross-browser fashion, you can wrap the option in an outer element and use its innerHTML instead.
i.e.
$(option).wrap('<select/>').parent().html() will give you what you want.
If you want to keep the for loop but want something that looks a bit cleaner, try this:
function menuBuilder( json ) {
var list = [],
$select = $('#myselect'),
i = 0,
l = json.funding.length,
funding;
for ( ; i < l; i++ ) {
funding = json.funding[ i ];
list.push(
'<option '+ somelogic ? 'selected' : ''+' value='+ funding.id +'>'+
funding.accountNumber +
'</option>'
);
}
$select.append(
'<option>Select Account Number</option>'+
list.join('') +
'<option value="addnew">New Account Number</option>'
);
}
You can create elements more efficiently like this:
$.selectMenuBuilder = function (json) {
var myselect = $("#myselect");
var l = json.funding.length;
for (var i = 0; i < l; i++) {
var funding = json.funding[i];
var opt = $("<option/>", {
value: funding.id,
html: funding.accountNumber,
selected: somelogic ? true : false //Pre-select option
});
myselect.append(opt);
}
}
efficiency with pure JavaScript
example jsfiddle
selectMenuBuilder = function(json) {
var myselect = document.getElementById("myselect"),
listItem = document.createElement("option"),
l = json.funding.length,
someLogic = false; // placeholder
listItem.innerText = "> Select Account Number";
myselect.appendChild(listItem);
for (var i = 0; i < l; i++) {
var funding = json.funding[i];
var listItem = document.createElement("option");
if (someLogic) {
listItem.setAttribute("checked", "checked");
}
listItem.setAttribute("value", funding.id);
listItem.innerText = funding.accountNumber;
myselect.appendChild(listItem);
}
listItem = document.createElement("option")
listItem.setAttribute("value", "addnew");
listItem.innerText = "+ New Account Number";
myselect.appendChild(listItem);
}

Categories