Programmatically trigger jquery dropdown change event as soon as the page loads - javascript

I have 2 dropdownlist that will fire an event if both of them are changed.
(meaning, any changes on the indices will fire a json request that is based on the dropdownlist's current value and append them to my table).
My question is that,as soon as the page loaded, are there any ways to pre-select their indices and fire the event at the same time? I am planning to set them based on the current term and school year.
Here is my jquery code:
$schoolyear = $('select#schoolyear');
$schoolterm = $('select#schoolterm')
$tbl = $('#classview');
$schoolyear.change(function () {
getCL();
});
$schoolterm.change(function () {
getCL();
});
function getCL() {
$.getJSON('#Url.Action("getClassList","Enrollment")', { term: $schoolterm.val(), year: $schoolyear.val() }, function (e) {
$tbl.find('tbody').remove();
if (e.length > 0) {
$(e).each(function (index, e) {
$tbl.append('<tr><td>' + e.subj + '</td><td>' + e.days + '</td><td>' + e.cstart + '</td><td>' + e.cend + '</td><td>' + e.professor + '</td><td>' + e.units + '</td><td>' + e.status +
'</td>' + '<td>' + '<form action="/Enrollment/dropClass" method="post">' + '<input type="hidden" name="test" value="'+e.id+'"/>' +
' Delete ' + '</form></td></tr>')
});
}
else {
$tbl.append('<tr><td colspan="8">No match found</td></tr>');
}
//compute t
});
}

Can trigger the change on one of them while setting value
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var term = Math.ceil(month/4);// needs verification on how term is set
$schoolyear
.change(getCL)
.val(year);//set year value
$schoolterm
.change(getCL)
// trigger change after setting value, will call getCL()
.val(term).change();

Try just adding getCL() at the bottom of your script.
$schoolyear = $('select#schoolyear');
$schoolterm = $('select#schoolterm')
$tbl = $('#classview');
$schoolyear.change(function () {
getCL();
});
$schoolterm.change(function () {
getCL();
});
function getCL() {
$.getJSON('#Url.Action("getClassList","Enrollment")', { term: $schoolterm.val(), year: $schoolyear.val() }, function (e) {
$tbl.find('tbody').remove();
if (e.length > 0) {
$(e).each(function (index, e) {
$tbl.append('<tr><td>' + e.subj + '</td><td>' + e.days + '</td><td>' + e.cstart + '</td><td>' + e.cend + '</td><td>' + e.professor + '</td><td>' + e.units + '</td><td>' + e.status +
'</td>' + '<td>' + '<form action="/Enrollment/dropClass" method="post">' + '<input type="hidden" name="test" value="'+e.id+'"/>' +
' Delete ' + '</form></td></tr>')
});
}
else {
$tbl.append('<tr><td colspan="8">No match found</td></tr>');
}
//compute t
});
}
getCL(); //this will run once when page is loaded.
To answer your other question, you can set a default pre-selected option in the dropdown by adding selected to your dropdown. For example:
<select>
<option value="2012">2012</option>
<option value="2013" selected>2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
</select>

Related

How to dropdown bind according to this record

I have two loops:
table loop: fills the table rows
dropdown loop: fills the dropdowns with typeid.data[i].TypeId, add a select in the last dropdown
My dropdown does not fill according to its record and I don't understand why.
var QuestionId = data[i].QuestionOid;
var fkid = data[i].FkSource;
var selectdata = data[i];
var selectinnerhtml = "<span><select id = \"answer" + QuestionId + "\" name = \"answer" + QuestionId + "\" class=\"answer" + QuestionId + " form-control input-small\" > </select></span>";
$.ajax({
type: "GET",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: '/MYaPI/EmployeeDetails/' + data[i].TypeId,
success: function(datasa) {
var optionhtmls = '<option value="' +
0 + '">' + "--Select--" + '</option>';
$(".answer" + QuestionId).append(optionhtmls);
$.each(datasa, function(j) {
var optionhtmls = '<option value="' +
datasa[j].Oid + '">' + datasa[j].Title + '</option>';
$(".answer" + QuestionId).append(optionhtmls);
});
}
});
var newRows2select = "<tr class='rows'><a href = '' >" +
" <td QuestionCategoryTitle = " + selectdata.QuestionCategoryTitle + " QuestionHeader = " + selectdata.QuestionHeader + " ContentTypeId=" + selectdata.FkSource + " QuestionTypeId=" + selectdata.FkQuestionType + " QuestionOID=" + selectdata.QuestionOid + " CategoryOID=" + selectdata.FkQuestionCategory + " class=\"question-block\"><small style=\"color:slateblue;font-weight: bolder;display:none\">CATEGORY: " + selectdata.QuestionCategoryTitle + ",</small>" +
" <i class=\"deleteRow fas fa-trash float-right\"></i> " +
"<p> " + selectdata.QuestionHeader + "</p>" + selectinnerhtml + " </td></a> \"</tr>";
$("#table23").append(newRows2select);
I don't know the jQuery way, however it is easily achievable with plain JavaScript
var select = document.createElement("select");
var selectinnerhtml = document.createElement("span");
selectinnerhtml.appendChild(select);
$.each(datasa, function(j) {
//create a new option element
var option = document.createElement("option");
//set the value attribute
option.setAttribute("value", datasa[j].oid);
//fill the HTML tag
option.value = datasa[j].Title
//add the option to the select dropdown
select.add(option);
});

Rebuild actual FullCalendar eventClick Function

I have a fullcalendar calendar where the click-events having sweet-alert 2 popups in the functions. The pop up boxes have multiple drop downs that are built using sweet-alert HTML functionality. Here's an example of the code,
eventClick: function (calEvent, jsEvent, view, date) {
var clickValue = calEvent.description;
if (clickValue != 'OWEDVALUE') {
var btn = "button";
drop = drop.replace("select-style-purple", "select-style-green");
options = options.replace("select-style-purple", "select-style-green");
var title = calEvent.title.replace("\n", "<br />");
swal({
title: moment(calEvent.start).format("MM/DD/YYYY"),
type: 'info',
inputClass: 'select-style-green',
inputValue: calEvent.teachNum,
html: title + '<br />' +
'Notes: ' + calEvent.description + '<br /><br />Select A New Teacher: <br /><br />' + options + '<p></p>Select A New Service: <br /><br />' + drop +
'<br /><br /><div style="border:2px solid green;" >Update Hours: ' +
'<input type="text" autofocus id="newHours" style="display:block !important;" class="sweet-alert-input"/>' +
'<input type="hidden" id="oldHours" value="' + calEvent.hours + '" /></div>' +
'<button type="' + btn + '" id="btnA" value="' + calEvent.id + '" style="background-color: #D46752 !important;" class="sweet-alert2-button">Delete Record</button> ' +
'<button type="' + btn + '" id="btnB" value="' + calEvent.id + '" class="sweet-alert2-button">Update Record</button> ' +
'<button type="' + btn + '" id="btnC" style="background-color: #B9B9B9 !important;" class="sweet-alert2-button">Cancel</button>',
showConfirmButton: false
});
$(this).css('border-color', 'red');
}
This is an example of one of the drop down boxes built in a javascript var.
options = '<select id="teacherDrop" class="select-style-green">';
for (var i = 0; i < record_array.length; i++) {
options += '<option value="' + record_array[i].teachNum + '" ';
if (record_array[i].teachName == data[0].teacher)
options = options + ' selected="selected" >' + record_array[i].teachName + 'TEST</option>';
else
options = options + '>' + record_array[i].teachName + 'TEST</option>';
}options += '</select>';
What I would like to do is to rebuild the drop downs(updating the selected value) after every click-event ajax call, so I need to rebuild the actual eventClick functions not the eventSources. I have tried multiple things to no avail.
Here is the function that gets called when one of the submit buttons gets pressed from the Sweet-Alert.
$(document).on('click', "#btnB", function () {
if ($.isNumeric($("#newHours").val())) {
var qString;
qString = "id=" + this.value;
qString += "&teacherId=" + $("#teacherDrop").val();
qString += "&hours=" + $("#newHours").val();
qString += "&service=" + $("#serviceDrop").val();
$.ajax({
type: "POST",
url: "_data_ManageHomebound_Students.aspx?qt=updateStudentRecord",
data: qString,
async: false,
success: function (data) {
data = JSON.parse(data);
swal.close();
$('#calendar').fullCalendar('removeEvents', data[0].id);
$("#calendar").fullCalendar('renderEvent', {
title: "Service Type: " + data[0].serviceType + "\nTeacher: " + data[0].teacher + "\nHours: " + $("#newHours").val(),
id: data[0].id,
start: data[0].start,
end: data[0].start,
allDay: data[0].allDay,
description: data[0].description,
teacher: data[0].teacher,
homeBoundPaidID: data[0].homeBoundPaidID,
teachNum: data[0].teachNum,
serviceType: data[0].serviceType,
color: 'green',
textColor: 'black'
}, false);
$('#ant').addClass('animated zoomInDown').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
$(this).removeClass('animated zoomInDown');
});
//Here I'm going to rebuild the service type drop down and try to recreate all click events.
var options;
options = '<select id="teacherDrop" class="select-style-green">';
for (var i = 0; i < record_array.length; i++) {
options += '<option value="' + record_array[i].teachNum + '" ';
if (record_array[i].teachName == data[0].teacher)
options = options + ' selected="selected" >' + record_array[i].teachName + 'REBUILT</option>';
else
options = options + '>' + record_array[i].teachName + 'REBUILT</option>';
}
options += '</select>';
var temp = $("#hoursGiven").val();
if ($("#newHours").val() >= $("#oldHours").val()) {
temp = parseFloat(temp) + (parseFloat($("#newHours").val()) - parseFloat($("#oldHours").val()));
} else {
temp = parseFloat(temp) - (parseFloat($("#oldHours").val()) - parseFloat($("#newHours").val()));
}
$("#hoursGiven").val("");
$("#hoursGiven").val(temp);
$("#hoursOwed").val(parseFloat($("#totHoursNeeded").val()) - parseFloat(temp))
}
});
} else {
sweetAlert({
title: "Oops!",
text: "Please Make Sure Pay Rate is Numeric. \nPlease fix form and try again.",
type: "error"
});
return false;
}
});
So after the Ajax is successful I rebuild the options var that holds the drop down information for Sweet-Alert. This is the point where I need all of the click-events to be rebuilt to use the updated code(options var). The purpose of this is I'm trying to get the drop downs to have a pre-selected value of the most recently used item(teacher, etc...).

JQuery Mobile Select doesn't refresh

I have 2 select.
<select name="paketart" id="paketart">
<!--Via Jquery-->
</select>
<select name="terminart" id="terminart">
<!--Via Jquery-->
</select>
And the Javascript code.
$(document).ready(function() {
$("#kundenselectid").change(function() {
$('#terminart').empty();
$('#paketart').empty();
$.getJSON( "/Daten/GetPakete.php", {id : $('#kundenselectid').val()},function( data ) {
var first = true;
$.each( data, function( key, val ) {
if (first)
{
$('#paketart').append('<option value="' + val['geId'] + '" selected>' + val['paName'] + ' - ' + val['Rest'] + '</option>');
$.getJSON( "/Daten/GetTerminart.php", {id : $('#paketart').val()},function( data ) {
$.each( data, function( key2, val2 ) {
$('#terminart').append('<option value="' + val2['taId'] + '">' + val2['taName'] + ' - ' + val2['taDauer'] + '</option>');
});
});
} else {
$('#paketart').append('<option value="' + val['geId'] + '">' + val['paName'] + ' - ' + val['Rest'] + '</option>');
}
});
});
$('#terminart').selectmenu('refresh', true);
$('#paketart').selectmenu('refresh', true);
});
});
But the Problem is it doesn't select the first option.
The options are added but I cant select them.
Any suggestions?

Getting duplicates in my datatable

I'm new to JavaScript.
I only have three entries in my database but when I run the code listed below I get six results. One entry shows up 3x while the other two entries show up 2x. What might I be doing wrong?
var tidyAppts='';
query.find({
success: function(results) {
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i];
//alert(object.id + ' - ' + object.get('ZipCode'));
tidyAppts+='<tr><td>'
+ object.get('Name') + '<td><td>'
+ object.get('Phone') + '<td><td>'
+ object.get('Address') + '<td><td>'
+ object.get('ZipCode') + '<td><td>'
+ object.get('Frequency') + '<td><td>'
+ object.get('TIDY') + '</td><td>'
+ object.get('FirstTIDYDay') + '</td><td>'
+ object.get('TIDYTime') + '</td><td>'
+ object.get('SecondTIDYDay') + '</td><td>'
+ object.get('SecondTIDYApptTime') + '</td><td>'
+ object.get('ThirdTIDYDay') + '</td><td>'
+ object.get('ThirdTIDYApptTime') + '</td></tr>';
(function($) {
$('#tidy-appt-table').append(tidyAppts);
})(jQuery);
}
},
When I used this code, only the first 4 objects for each entry is displayed in the table but I get the correct amount of records which is 3.
(function($) {
$('#tidy-appt-table').append('<tr><td>'
+ object.get('Name')
+ '</td><td>'
+ object.get('Phone')
+ '</td><td>'
+ object.get('Address')
+ '</td></td>'
+ object.get('ZipCode')
+ '</td></td>'
+ object.get('Frequency')
+ '</td></td>'
+ object.get('TIDY')
+ '</td><td>'
+ object.get('FirstTIDYDay')
+ '</td><td>'
+ object.get('TIDYTime')
+ '</td><td>'
+ object.get('SecondTIDYDay')
+ '</td></td>')
+ object.get('SecondTIDYApptTime')
+ '</td></td>'
+ object.get('ThirdTIDYDay')
+ '</td></td>'
+ object.get('ThirdTIDYApptTime')
+ '</td></tr>';
})(jQuery);
}
i figured it out I removed the plus sign from tidyAppts+='' and made it tidyAppts=

JavaScript undefined? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
UPDATED CODE
CURRENT ERROR: Uncaught TypeError: Cannot read property 'id_cursa' of undefined
I really don't know which may be the problem ???
function locurilibere(data, callback) {
var URL = Path + 'rezervaribilete/locurilibere/' + data;
$.get(URL, function(obj) {
if (obj.raspuns === "nu") {
callback(true);
} else {
callback(false);
}
}, 'json');
}
function populateCurseDus(de_la, pana_la, data_plecarii) {
var data = de_la + "-" + pana_la + "-" + data_plecarii;
$.get(Path + 'rezervaribilete/listCurseDus/' + data, function(o) {
for (var i = 0; i < o.length; i++) {
var id_cursa = o[i].id_cursa;
var datalocuri = id_cursa + "-" + data_plecarii;
locurilibere(datalocuri, function(result){
if (result) {
$('#cursedus tbody').append('<tr style="background:red;"><td><input type="radio" name="id_cursadus" value="' + o[i].id_cursa + '" disabled></td><td>' + o[i].cod_cursa + '</td><td>' + o[i].de_la + '</td><td>' + o[i].pana_la + '</td><td>' + o[i].ora_plecare + '</td><td>' + o[i].ora_sosire + '</td><td>' + o[i].id_transportator + '</td><td>' + o[i].id_traseu + '</td></tr>');
} else {
$('#cursedus tbody').append('<tr><td><input type="radio" name="id_cursadus" value="' + o[i].id_cursa + '"></td><td>' + o[i].cod_cursa + '</td><td>' + o[i].de_la + '</td><td>' + o[i].pana_la + '</td><td>' + o[i].ora_plecare + '</td><td>' + o[i].ora_sosire + '</td><td>' + o[i].id_transportator + '</td><td>' + o[i].id_traseu + '</td></tr>');
}
});
}
}, 'json');
}
It will not work as expected because of asynchronous nature of ajax request, you a callback to fix it
function freeseats(data, callback) {
var URL = Path + 'bookings/freeseats/' + data;
$.get(URL, function(obj) {
if (obj.raspuns === "nu") {
// alert("no");
callback(true);
} else {
// alert("yes");
callback(false);
}
}, 'json');
}
// ********************************* second
// **************************************
function populateDepartures(from, to, departure) {
var data = from + "-" + to + "-" + departure;
$.get(Path + 'booking/listDepartures/' + data, function(o) {
$.each(o, function(index, item) {
var id_flight = item.id_flight;
var dataseats = id_flight + "-" + departureDate;
freeseats(dataseats, function(result) {
if (result) {
alert("no more seats");
$('#cursedus tbody')
.append('<tr style="background:red;"><td><input type="radio" name="id_cursadus" value="'
+ item.id_cursa
+ '" disabled></td><td>'
+ item.cod_cursa
+ '</td><td>'
+ item.de_la
+ '</td><td>'
+ item.pana_la
+ '</td><td>'
+ item.ora_plecare
+ '</td><td>'
+ item.ora_sosire
+ '</td><td>'
+ item.id_transportator
+ '</td><td>'
+ item.id_traseu + '</td></tr>');
} else {
alert("there are free seats");
$('#cursedus tbody')
.append('<tr><td><input type="radio" name="id_cursadus" value="'
+ item.id_cursa
+ '"></td><td>'
+ item.cod_cursa
+ '</td><td>'
+ item.de_la
+ '</td><td>'
+ item.pana_la
+ '</td><td>'
+ item.ora_plecare
+ '</td><td>'
+ item.ora_sosire
+ '</td><td>'
+ item.id_transportator
+ '</td><td>'
+ item.id_traseu + '</td></tr>');
}
});
});
}, 'json');
}
i think I have deciphered what you need. Please take a look at this jsFiddle Link and see if this serves your question.
Here's the code:
var boolFlag = false;
var firstFunc = function (){
if(boolFlag === false){
boolFlag = true;
return 'yes';
}else{
boolFlag = false;
return 'no';
}
};
var secondFunc = function () {
return firstFunc();
};
$('#myButton').click(function (){
if(secondFunc() == 'yes'){
console.log('hello world, you said: YES');
}else{
console.log('hello universe, you said: NO');
}
});

Categories