Create Dynamic PHP Variables (Echoed Out) from JavaScript For Loop - javascript

I am attempting to cut down on some Javascript functions. Right now my current design I dynamic create Year list using Javascript. Now that I have it update the current selected value from the value stored in the database I am wondering if I can duplicate this across all the Year list that I have created. There are 10 in total.
Current code:
for (a = 1; a <= 1; a++) {
console.log("STARTING");
// reference to a specific dropdown list
var ddYears = $("#ddYears" + a + "");
console.log(ddYears);
var theStartYear = "$we" + a + "startyear";
console.log(theStartYear);
var ddCurrentSelectedYear = '<?php echo ' + theStartYear + '; ?>'; // THIS IS THE LINE I'M HAVING TROUBLE WITH
console.log(ddCurrentSelectedYear);
var initialOption = $("<option/>");
if (ddCurrentSelectedYear == "") {
initialOption.html("Year");
initialOption.val("");
initialOption.attr('selected', 'selected');
}
ddYears.append(initialOption);
//Loop and add the Year values to DropDownList.
for (var i = currentYear; i >= 1920; i--) {
var option = $("<option />");
if (i == ddcurrentSelectedYear) {
option.attr('selected', 'selected');
}
option.html(i);
option.val(i);
ddYears.append(option);
}
}
I'm trying to "hardcode" the variable so when it iterates through it can pick up from my PHP that value that should already be stored in a variable. I can do it with one value but I would like it to do it for 10 values so I don't have to make 10 separate functions for 1 PHP call. As the 'A' increments the variable is named the same in the backend meaning that value could potentially exist. I am not very good with JavaScript so it may be that my syntax is wrong.
Again, I can't emphasis this enough based off what I have seen on stackoverflow when I do call that line (that has I'm having trouble with it) like shown below it will retrieve a value from my PHP.
var ddcurrentSelectedYear = '<?php echo $we1startyear; ?>';
Does anyone see any issues with my JavaScript syntax?
Edit 1: There seems to be some confusion as to what I'm doing so I am placing some code below this that I'm currently using and it works. You will see all that changes is instead of the for loop I'm accessing it as a hardcoded name. The number is the only thing changing in the html selector and the PHP outputted variable. That is the whole purpose of what I'm trying to achieve with the for loop is instead of writing this function 20+ times for a character change have a for loop do the heavy lifting for me.... (Let me reinstate my question - Is there any way to write one function for what I'm currently doing below?
$(function () {
var ddYears = $("#dd1Years");
var ddCurrentSelectedYear = '<?php echo $we1startyear; ?>';
// create intial blank option
var initialOption = $("<option />");
if (dd1currentSelectedYear == "") {
initialOption.attr('selected', 'selected');
}
initialOption.html("Year");
initialOption.val("");
ddYears.append(initialOption);
//Loop and add the Year values to DropDownList.
for (var i = currentYear; i >= 1920; i--) {
var option = $("<option />");
if (i == dd1currentSelectedYear) {
option.attr('selected', 'selected');
}
option.html(i);
option.val(i);
ddYears.append(option);
}
}
$(function () {
var ddYears = $("#dd2Years");
var ddCurrentSelectedYear = '<?php echo $we2startyear; ?>';
//Loop and add the Year values to DropDownList.
for (var i = currentYear; i >= 1920; i--) {
var option = $("<option />");
if (i == ddCurrentSelectedYear) {
option.attr('selected', 'selected');
}
option.html(i);
option.val(i);
ddYears.append(option);
}
}
$(function () {
var ddYears = $("#dd3Years");
var ddCurrentSelectedYear = '<?php echo $we3startyear; ?>';
//Loop and add the Year values to DropDownList.
for (var i = currentYear; i >= 1920; i--) {
var option = $("<option />");
if (i == ddCurrentSelectedYear) {
option.attr('selected', 'selected');
}
option.html(i);
option.val(i);
ddYears.append(option);
}
}

Related

Remove time from dynamically generated dropdown

I have a dropdown that has times within a start and end time. I also have times displayed on my page that are "booked". I am trying to create a function that see if any "booked" values match the dropdown values, and if so, remove them from the array. I am having trouble figuring out how to design my JavaScript function to do so and would greatly appreciate any help in this.
remove.js
$(function () {
var removeItem = document.getElementsByClassName('set');
$('#time').find('option[value=="' + removeItem + '"]').remove();
});
time.js
var start = document.getElementById('start').innerHTML.split('.').join('').toLocaleLowerCase();
var end = document.getElementById('end').innerHTML.split('.').join('').toLocaleLowerCase();
var time = document.getElementById('time');
time.disabled = true;
var slotTimes = [];
document.getElementById("length").onchange = function (evt) {
var timeDistance = evt.target.value;
var startMoment = moment(start, "h:mm a");
var endMoment = moment(end, "h:mm a");
slotTimes = [];
while (startMoment.isSameOrBefore(endMoment)) {
slotTimes.push(startMoment.format("h:mm a"));
startMoment = startMoment.add(timeDistance, 'minutes');
}
addDropdown();
disabled();
};
function disabled(option) {
if (option != "") {
time.disabled = false;
}
}
function addDropdown() {
var doc = '',
times = slotTimes,
i;
for (i = 0; i < times.length; i++) {
doc += "<option value='" + times[i] + "'>" + times[i] + "</option>";
}
document.getElementById('time').innerHTML = doc;
disabled();
}
First, you ought to be using jQuery!
$('#foo') is the same as document.getElementById('foo')
$('.bar') is the same as document.getElementByClassName('bar')
Now to address your question, you are trying to put an html element
ie document.getElementByClassName('set')
in place of a value. Try running console.log(removeItem) and you will see what I mean.
I think what you are trying to do is this:
$(document).ready(function() {
$('.set').each(function() { //loop over all elements with a class == 'set'
const removeItem = $(this).val(); //get value of each element
$('#time').find('option=[value=="' + removeItem + '"]').remove();
});
});
If you need any more help let me know.
Hope this helps!
Update
You should put the removeItem loop at the end of the addDropdown function:
function addDropdown() {
var doc = '',
times = slotTimes,
i;
for (i = 0; i < times.length; i++) {
doc += "<option value='" + times[i] + "'>" + times[i] + "</option>";
}
document.getElementById('time').innerHTML = doc;
disabled();
$('.set').each(function() { //loop over all elements with a class == 'set'
const removeItem = $(this).val(); //get value of each element
$('#time').find('option=[value=="' + removeItem + '"]').remove();
});
}
Update 2
I would recommend rewriting your code to use the selectpicker bootstrap package. It looks like most of the "features" you are trying to make have simple keywords that selectpicker uses.
For example, to disable an option from this dropdown:
<select class="selectpicker" id="toppings">
<option id="opt_1">Mustard</option>
<option id="opt_2">Ketchup</option>
<option id="opt_3">Relish</option>
</select>
You simply do:
$('#opt_2').prop('disabled', true);
If you need to reference specific specific options by their parent dropdown, you can use the children method:
$('#toppings').children('.someClass').prop('disabled', true);
This will change all options of the toppings dropdown that have a class="someClass" to disabled.
I'm sure there are several features of the selectpicker package that you will find useful later on too!
I'm not sure what the problem is with your code specifically, but it is looking more and more like the selectpicker package, which you can use for free.

Javascript only: Function renders a dropdown and table where the value from the dropdown is needed to filter the table

I created a function which renders a dropdown and a table. This dropdown gives me values which I use inside the function to filter the table. For some reason, it does not update when I reselect something on the dropdown.
No frameworks please thank you!
Here are some screenshots:
It does not update the columns showed because when I console.log() the values from the dropdown it does not update. It still says 1 5 but when I click the second one it should say 2 5.
I selected the second option on the dropdown. I have no idea how to do this. Sorry, I'm a beginner.
//function which we will use to hide and unhide rows
function toggleClass(element, className, toSet) {
element.classList[toSet ? 'add' : 'remove'](className);
}
//The table is already rendered and when the buttons on the screen are clicked, this pagination function is called
function columnPagination(input) {
var table = document.getElementById("tablePrint"),
dataRows = table.getElementsByTagName('tr'),
listHTML = "";
//get date labels for dropdown
var filterDateLabels = [];
var columns = table.getElementsByTagName('th');
for(var ii = 0; ii < columns.length; ii++){
if(ii%input==0){
filterDateLabels.push(columns[ii].innerHTML.slice(21,33));
}
if(ii%input==input-1){
filterDateLabels.push(columns[ii].innerHTML.slice(21,33));
}
}
//display dropdown with values which you will use to filter the table
listHTML += "<select id=\"pagenumber\")>";
for(var ii = 0; ii < filterDateLabels.length; ii++){
listHTML += "<option value = \"" + ii + "\">" + filterDateLabels[ii] + " - ";
if(filterDateLabels[ii+1]!= ""){
listHTML += filterDateLabels[ii+1] + "</option>";
ii++;
}
else{
listHTML+="LAST </select>";
}
}
document.getElementById('dates').innerHTML = listHTML;
var multiplier = document.getElementById('pagenumber').value;
multiplier = multiplier/2;
if(multiplier == 0){
multiplier = 1;
}
//hiding function which works but doesn't update when the dropdown is clicked
input = input*multiplier;
console.log(multiplier, input);
for (var i = 0; i < dataRows.length; i++) {
var cells = dataRows[i].children;
for (var cell = 0; cell < cells.length; cell++) {
toggleClass(cells[cell], 'hide', cell > input)
}
}
}
I ended up just using onchange="myFunction()".
http://www.w3schools.com/jsref/event_onchange.asp
Everything you need is up there if you encounter the same issue as I did. I was having trouble because I was editing the wrong file. #KevinKloet helped me realize that by pointing out another error. Thanks!

Loop through multiple select lists and count the number of times each option is selected

Part of a site I'm working on involves creating repeat instances of the same select - option. I would like to count the number of times each option has been selected, and then store that number as a variable, which can then be sent to php email function.
For example - if "Infallid" is selected 3 times - I get infallid = 3, and 0 for the others.
JS fiddle showing how it all works - https://jsfiddle.net/scx4shnd/2/
$("button").click(function(){
$("select[name='diskho'] > option:selected").each(function() {
alert(this.text + ' ' + this.value);
// should alert - "value 1 = x" , "value 2 = "y" ect" where x and y are different values (numbers)
});
$("select[name='spishall'] > option:selected").each(function() {
alert(this.text + ' ' + this.value);
});
});
You can use following logic to calculate the number of times an option has been selected:
$("button").click(function(){
var dishkoMap = {};
$("select[name='diskho'] > option:selected").each(function () {
var value = this.value;
if (dishkoMap[value]) { // if value already exists then increase it by 1
dishkoMap[value] += 1;
} else {
dishkoMap[value] = 1;
}
});
// dishkoMap is a dictionary object so you won't see anything in alert.
// open the browser console and you can see the counts corresponding
// to each selected option
console.log(dishkoMap);
});
Similarly, you can also write for Spishäll and Blandare.
I would suggest writing a function where you pass the name of the select and then return the countMap.
function getCountMap(name) {
var countMap = {};
$("select[name='" + name + "'] > option:selected").each(function () {
var value = this.value;
if (countMap[value]) { // if value already exists then increase it by 1
countMap[value] += 1;
} else {
countMap[value] = 1;
}
});
return countMap;
}
and then use it as:
var dishkoMap = getCountMap('dishko');
var spishallMap = getCountMap('spishall');
// etc.

How can I show only the row of a table that has the same value that was entered in a textbox with jquery

I have a table of rank where I type the ID of the rank and it shows me only the column line that has this line as my code:
$('button').click(function () {
var data = $("textarea").val();
var rank = $("#rank").val();
if(rank == ""){
alert("digit rank number");
}
else{
data = data.replace(/\s/, " #");
data = data.replace(/([0-9]\s)/g, "$1#");
var lines = data.split("#"),
output = [],
i;
for (i = 0; i < lines.length; i++)
output.push("<tr><td>" + lines[i].slice(0,-1).split(",").join("</td><td>") + "</td></tr>");
output = "<table>" + output.join("") + "</table>";
var valuefinal = $(output).find('tr').filter(function(){
return $(this).children('td').eq(1).text() == rank;
});
$('#fileDisplayArea').html(valuefinal);
}
});
I'm doing this filter in that part of the code
var valuefinal = $(output).find('tr').filter(function(){
return $(this).children('td').eq(1).text() == rank;
});
$('#fileDisplayArea').html(valuefinal);
DEMO CODE
(Forgive me if you did not understand something, my english sucks. I hope it is clear what I need.)
You need to change this -
return $(this).children('td').eq(1).text() == rank;
to this -
return $(this).children('td').eq(0).text() == rank;
.eq() is a zero-based array method.
http://jsfiddle.net/jayblanchard/qM6Fj/19/
http://api.jquery.com/eq/
You need to have a search feature for the contents you have displayed in the table is what i got.....
You can use jQuery DataTable for this purpose which does this job link .. scroll down to see the table show with sort, search etc features

How can I validate a survey based on form elements type?

I have a form that consist of different form elements (radio, text, select) and is dynamically created in PHP. However, I'm trying to validate this form in JQuery based on the question type. My questions are named q1, q2,.....
$(function(){
if ($('form').length > 0) {
$('form').submit(function(e){
var len = <?php echo $numRows; ?>; // refers to the number of rows in questions table of a database
for (var i = 1; i <= len; i++ ) {
var qNum = 'q'+i;
//document.write(qNum);
if (($('input[name=' + qNum + ']:checked').length == 0) )
{
if ($('input[type=Radio][name=' + qNum + ']')) {
alert("No Selection is made for "+ qNum);
return false;
}
}
}
}); // form submit function
}// form.length
})//function
The above code handles radio buttons efficiently. However, when it comes to non radio questions it still display an alert message to that non radio question. Anyway, of handling this differently based on the question type?
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function(){
if ($('form').length > 0) {
$('form').submit(function(e){
var answers = '';
//alert (qNum);
var i = 1;
var len = <?php echo $numRows; ?>;
$('input[type=Radio]:checked').each(function() {
if (answers !== '') {
answers += ',';
}
answers += $(this).val();
//alert(answers);
})
$('input[name=h2]').val(answers);
for (var i = 1; i <= len; i++ ) {
var qNum = 'q'+i;
//document.write(qNum);
if (($('input[name='+qNum+']:checked').length == 0) )
{
if ($('#'+qNum+'').is(':radio')) {
alert("No Selection is made for "+ qNum);
return false;
}
}
}
}); // form submit function
}// form.length
})//function

Categories

Resources