For loop to change value of dropdown menu in jQuery - javascript

I currently have a drop down menu that lists all the years from 1970 to present. At the moment this is in some embedded JavaScript within the HTML. I'm trying to use an external file to perform the same function with jQuery, but I'm having difficulty.
This is the current method to display the drop down menu:
<h4 class="form_title">Time Span</h4></br>
<label for="select" class="col-lg-2 control-label">From:</label>
<div class="col-lg-3">
<select class="form-control" name="timeStart" id="select">
<option value="" selected disabled>Select</option>
<script type="text/javascript">
// get current year and then use loop to populate options
var year = new Date().getFullYear();
for(i = year; i >= 1970; i--) {
document.write('<option value="' + i + '">' + i + '</option>');
};
</script>
</select>
</div> <!-- col-lg-3 -->
This works fine but I want to separate the logic from the view. I have tried removing the script entirely from this file and then adding the following in my JavaScript file like so:
var year = new Date().getFullYear();
$("#select").change(function() {
console.log("Calling function successfully...");
for(i = year; i >= 1970; i--) {
document.write('<option value="' + i + '">' + i + '</option>');
}
});
I put the console.log in there to see if the function is even being called when I select the menu (which it isn't). I have been trying many variations on this but can't figure out what I'm doing wrong (probably several things). Should I be selecting the select tag or the option tag?

Move your code into ready and use append to add option to the select.
var year = new Date().getFullYear();
$(document).ready(function () {
console.log("Calling function successfully...");
var options = '';
for (i = year; i >= 1970; i--) {
options += '<option value="' + i + '">' + i + '</option>';
}
$('#select').append(options);
});

You need to append the options you want to render as children to the select element:
$(document).ready(function() {
console.log("Calling function successfully...");
var options = ''
for(i = year; i >= 1970; i--) {
options += '<option value="' + i + '">' + i + '</option>';
}
$("#select").append(options);
});

Since you're using JQuery, you'll need to make sure to wrap your code in $(document).ready(function() {});
If you don't, it'll just try and run immediately on load. Wrapping it in that will ensure that the select box is rendered before trying to run your code.
You can see an example of how this works here.
http://jsbin.com/rebahiwupi/1/edit
$(document).ready(function() {
var sel = $('select');
var start_year = 1970;
for(var i=start_year;i<=new Date().getFullYear();i++) {
sel.append('<option value="'+i+'">'+i+'</option>');
}
});

Another version that uses while loop.
var year = new Date().getFullYear(), $options = $();
while (year >= 1970) {
var option = year--;
$options = $options.add($('<option/>', { 'value': option, 'text': option }));
}
$('#select').append($options);

Related

laravel form "select field" is not working

Hello I have a problem with "select field" when submitting the form, it tells me that the field is required even though there is already a data selected for it.
error:
When I checked the network tab, headers it is showing blank, so there is no data being passed.
network screenshot
I have already declared the year id properly inside a JS. Here's my code:
$('#tax-form').on('submit', function (e) {
e.preventDefault();
let taxdeclarationnumber = $("#tax_declaration_number").val();
let currentrpt = $("#current_rpt").val();
let year = $("#year").val();
console.log('nani poku');
$.ajax({
url: "/tax-information",
type: "POST",
data: {
tax_declaration_number: taxdeclarationnumber,
current_rpt: currentrpt,
year: year,
},
my blade:
<div class="form-group">
<label for="">For the Year</label>
<select name="year" id="year" class="custom-select year-list" data-style="btn btn-secondary">
</select>
</div>
I'm using a separate JS for this select field, this is to generate a dynamic year list.
$(document).ready(function () {
var d = new Date();
for (var i = 0; i <= 30; i++) {
// var option = "<option value=" + parseInt(d.getFullYear() + i) + ">" + parseInt(d.getFullYear() + i) + "</option>"
var option = '<option value="' + parseInt(d.getFullYear() + i) + '">' + parseInt(d.getFullYear() + i) + "</option>"
$('[id*=year]').append(option);
}
});
What other steps I need to do here? I'm pretty sure there is no issue with my controller.

How to design UI for multiple selection in a drop down list?

I'm setting up a UI for my application. I would like to have some idea about your guy's experiences.
I need to have multiple selections from different sources.
Input (Sources): Companies, Department. Multiple companies, departments allowed.
Output: People who belong to selected items
For example, I can select company1, company2, and select department1, department2 from a dropdown list.
I select one by one property( Select company1, company2, then go to another dropdown to select department1,2...)
In the end, I have company1,2,3 checked, department 1,2,3 checked.
Then the result will tell me user1...n belong to the selected list above.
The problem is nothing if I have only a few company and department but if coming to be complicated if I have multiple (more than 6 companies and departments). I can't come up with any good UI design for this problem.
I expected the output of (selected(checked company1,2,3... + department1,2,3)) -> result person1,2,3 belong to checked items.
Try the following code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Select Company: </p>
<select name="companySelector" multiple>
</select>
<p>Select Department: </p>
<select name="departmentSelector" multiple>
</select>
<p>Persons: </p>
<ul id="persons">
</ul>
<script>
var companySelector = document.querySelector("[name='companySelector']");
var departmentSelector = document.querySelector("[name='departmentSelector']");
var persons = document.getElementById("persons");
var temp, temp2 = 0;
var database = {
company_1: {
c1_department1: ["c1d1person1", "c1d1person2", "c1d1person3", "c1d1person4"],
c1_department2: ["c1d2person1", "c1d2person2", "c1d2person3", "c1d2person4"],
c1_department3: ["c1d3person1", "c1d3person2", "c1d3person3", "c1d3person4"]
},
company_2: {
c2_department1: ["c2d1person1", "c2d1person2", "c2d1person3", "c2d1person4"],
c2_department2: ["c2d2person1", "c2d2person2", "c2d2person3", "c2d2person4"],
c2_department3: ["c2d3person1", "c2d3person2", "c2d3person3", "c2d3person4"]
},
company_3: {
c3_department1: ["c3d1person1", "c3d1person2", "c3d1person3", "c3d1person4"],
c3_department2: ["c3d2person1", "c3d2person2", "c3d2person3", "c3d2person4"],
c3_department3: ["c3d3person1", "c3d3person2", "c3d3person3", "c3d3person4"]
},
company_4: {
c4_department1: ["c4d1person1", "c4d1person2", "c4d1person3", "c4d1person4"],
c4_department2: ["c4d2person1", "c4d2person2", "c4d2person3", "c4d2person4"],
c4_department3: ["c4d3person1", "c4d3person2", "c4d3person3", "c4d3person4"]
},
company_5: {
c5_department1: ["c5d1person1", "c5d1person2", "c5d1person3", "c5d1person4"],
c5_department2: ["c5d2person1", "c5d2person2", "c5d2person3", "c5d2person4"],
c5_department3: ["c5d3person1", "c5d3person2", "c5d3person3", "c5d3person4"]
}
}
for (temp in database) {
companySelector.innerHTML += '<option value="' + temp + '">' + temp.replace(/_/g, " ") + '</option>';
}
companySelector.onchange = function() {
departmentSelector.innerHTML = "";
var selectedCompnies = document.querySelectorAll("[name='companySelector'] option:checked");
for (var i = 0; i < selectedCompnies.length; i++) {
for (temp2 in database[selectedCompnies[i].value]) {
departmentSelector.innerHTML += '<option value="' + temp2 + '" data-company="' + selectedCompnies[i].value + '">' + temp2.replace(/_/g, " ") + '</option>'
}
}
}
departmentSelector.onchange = function() {
persons.innerHTML = "";
var selectedDepartments = document.querySelectorAll("[name='departmentSelector'] option:checked");
for (var i = 0; i < selectedDepartments.length; i++) {
var temp3 = selectedDepartments[i].dataset.company;
var prsonsArray = database[temp3][selectedDepartments[i].value];
for (var x = 0; x < prsonsArray.length; x++) {
persons.innerHTML += "<li>" + prsonsArray[x] + "</li>";
}
}
}
</script>
</body>
</html>
DEMO

Using variable for an identifier name (using jquery selectors)

Believe me, I've been looking for examples online for hours. None of them seem to help.
I'm working on making a table. There are some columns with dropdown menu and I've assigned ID to each menu. Inside a loop, I'm trying to assign selected value for each dropdown menu.
var row$ = $('<tr/>');
function updateDataBodyGenerator(myList) {
for (var i = 0 ; i < myList.length ; i++) {
var row$ = $('<tr/>');
var colIndex = 0;
for (var key in myList[i]) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) { cellValue = ""; }
var severityDropDownMenu = "severityDropDownMenu" + i;
colIndex++;
switch (key) {
case "Test Case":
...
break;
case "Test Result":
...
break;
case "Severity":
var severitySting = '<td><select id="' + severityDropDownMenu + '" class="dropDownMenu">' +
'<option value="Red">Red</option>' +
'<option value="Green">Green</option>'+
'<option value="Yellow">Yellow</option>';
row$.append($(severitySting));
//failed
//$("#severityDropDownMenu" + i).val(cellValue);
//failed
//var selectorString = "#" + severityDropDownMenu.toString();
//$(selectorString).val("Green");
//failed
//$("#" + severityDropDownMenu).val(cellValue);
//failed
//var selectorString = '#' + severityDropDownMenu;
//$(selectorString).val(cellValue);
//works
//$('#severityDropDownMenu0').val(cellValue);
...
As you can see in the comments, I've tried several approaches and only 1 worked which was $('#severityDropDownMenu0').val(cellValue); but that will only change 1 dropdown menu.
I appreciate your time and assistance.
Currently you're trying to use the # selector to target the dropdown by ID.
The issue here (as mentioned in the comments) is that this selector will search the DOM for the element, however because you've never added this element to the DOM, it doesn't exist on the page; the selector will return nothing.
What you can do instead is actually turn your severitySting into a jQuery element to set its value. Whenever you do append it, the value will be properly set. Like so:
var $severity = $(severitySting); //This is the <td>
var $dropdown = $severity.find("select") //This is the <select>
$dropdown.val(cellValue); //Set dropdown value
Demo:
var severityDropDownMenu = "mytest";
var cellValue = "Yellow";
var severitySting = '<td><select id="' + severityDropDownMenu + '" class="dropDownMenu">' +
'<option value="Red">Red</option>' +
'<option value="Green">Green</option>' +
'<option value="Yellow">Yellow</option>';
var $severity = $(severitySting);
var $dropdown = $severity.find("select");
$dropdown.val(cellValue);
$("tr").append($severity);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr></tr>
</table>

How do i mark as selected a specific option from a select which his options are loaded depending of an input number?

take your time to read my explanation and ask me if i didn't explain myself well, thanks.
Don't mind how i print whith php, it it okay this way, this is a php setting.
i have in a template an input number that the client will fill with an amount of pallets, in the same template i have a table with as many tr as boxes the order has.
so, there are as many selects as tr, because it is used to assign the box to a pallet.
When the process is done i have the info in my database and if the client enters again he will need to have all the data in place, so the input number is filled and that fills all the selects with the amount of otions as the input, ok.
the fill process is made with jquery.
in the template, i have only this to make the select
<td><select class="pallets_assign" name="boxes[<?=$box;?>][which_pallet]"></select></td>
UPDATE:
to load the options in the selects i use this inside a document ready :
var someone = function() {
var something = function(from_pallets, to_pallets) {
var qty = $(from_pallets);
var select = $(to_pallets);
var update = function() {
select.empty();
for (var i = 1; i <= qty.val(); i++) {
select.append('<option value="' + i + '">' + i + '</option>');
}
};
qty.on('change', update);
update();
}
});
form the tamplate i call it like this:
var init = function() {
someone.something('#total_pallets', '.pallets_assign');
};
total_pallets is the id of the input number
My question is: how do i mark as selected the option which value i have stored in my database if i don't have the options created when the DOM is loaded but when that input number changed?
Thanks for your time.
Thanks to #AlonEitan to helping me find a way to solve this
in the template i had a script that did something like this:
var init = function() {
someone.something('#total_pallets', '.pallets_assign');
};
changed to:
var init = function() {
var option = [];
<? foreach ($products as $product) { ?>
<? for ($i = 1; $i <= count($product["boxes"]); $i++) { ?>
option.push(<?=(somechecks ? $product["boxes"][$i]["which_pallet"] : false);?>);
<? } ?>
<? } ?>
someone.something('#total_pallets', '.pallets_assign', option);
};
and in my js file i had this:
var someone = function() {
var something = function(from_pallets, to_pallets) {
var qty = $(from_pallets);
var select = $(to_pallets);
var update = function() {
select.empty();
for (var i = 1; i <= qty.val(); i++) {
select.append('<option value="' + i + '">' + i + '</option>');
}
};
qty.on('change', update);
update();
}
});
which is now:
var someone = function() {
var something = function(from_pallets, to_pallets, option) {
var qty = $(from_pallets);
var select = $(to_pallets);
var update = function() {
select.empty();
select.each(function(i) {
for (var j = 1; j <= qty.val(); j++) {
$(this).append('<option value="' + j + '"' + (j == option[i] ? ' selected="selected"' : '') + '>' + j + '</option>');
}
});
};
qty.on('change', update);
update();
}
});
It is a shame that in the beginning this got that many downvotes because i think is a cool way to solve this kind of issue and people will profit of this, but anyway.

How to clear a listbox value when another listbox value selected

I have created a depending on radio button click listbox will display now if user click a one radio button listbox will display and again user select other option but its not clear a previous value of listbox how to clear it by javascript????
<script language="JavaScript" type="text/javascript">
function fun(s)
{
if(s==B)
{
document.getElementById("maingroup").style.display='none';
document.getElementById("subgroup").style.display='';
document.getElementById("itemname").style.display='none';
}
if(s==C)
{
document.getElementById("maingroup").style.display='none';
document.getElementById("subgroup").style.display='none';
document.getElementById("itemname").style.display='';
}
</script>
Here is the example which i have tried JS FIDDLE
Try this:
var listBox = document.getElementById("listboxID");
listBox.innerHTML = "";
I think show/hide method is not good for programming.
I dont know whether it is useful or not but this might be helpful to you.
You can make it dynamic like
var mainGroup = ["aa","bb","cc"];
var subGourp = ["dd","ee","ff"];
var itemName = ["gg","ee","ff"];
var Country = ["jj","hh","ii"];
var Zone = ["kk","ll","mm"];
if(s == A)
{
var i=0;
var str = "";
for(i=0;i<mainGroup.length;i++)
{
str += "<option value='" + (i+1) + "'>" + mainGroup[i] + "</option>";
}
document.getElementById("maingroup").style.display='';
document.getElementById("maingroup").innerHTML = str;
}
else if(s == B)
{
var i=0;
var str = "";
for(i=0;i<subGourp.length;i++)
{
str += "<option value='" + (i+1) + "'>" + subGourp[i] + "</option>";
}
document.getElementById("maingroup").style.display='';
document.getElementById("maingroup").innerHTML = str;
}
This is my idea(not tested). Give every your listbox a class name like class='lst'. After that when you click on a radio button just use:
`document.getElementsByClassName('lst').style.display = 'none';`
and show current listbox.
`document.getElementsByClassName('currentListboxID').style.display = 'block';`
Here is DEMO

Categories

Resources