When I add jquery validate function my other functions stop working - javascript

I have a form where I have several javascript/jquery functions that are working fine. As soon as I add a validate function they all stop working. I am using the plugin from http://jqueryvalidation.org/ and have all my functions in one js file. Again all these functions work fine until I add the validation function. Here is the js file.
$(function(){
$(".timeinput").timepicker({
step: 5
});
});
$(function(){
$(".datepick").datepicker({
changeYear: true,
changeMonth: true
});
});
$(function(){
$("#incimechtype").change(function(){
var dropdown = $(this).val();
$.ajax({
url:"getinjuryjson.php",
dataType: "json"
}).done( function(data){
$("#incimech").find("option").remove();
if(dropdown !== ""){
$("#incimech").append($('<option/>'));
}
switch(dropdown){
case "Mechanism":
$.each(data, function(key,value){
if(value.injmech==='Mechanism'){
$("#incimech").append($('<option/>',{
value: value.injmechid,
text: value.injmechdescrip
}));
}
});
break;
case "Other":
$.each(data, function(key,value){
if(value.injmech==='Other'){
$("#incimech").append($('<option/>',{
value: value.injmechid,
text: value.injmechdescrip
}));
}
});
break;
case "Object":
$.each(data, function(key,value){
if(value.injmech==='Object'){
$("#incimech").append($('<option/>',{
value: value.injmechid,
text: value.injmechdescrip
}));
}
});
break;
}
}
)
}
)
}
);
$("#referto").change(function(){
var rechange = false;
$('#referto option:selected').each(function(){
if($(this).text()=="Other"){
rechange =true;
}
});
if(rechange){
var textarea = "<textarea name='referother' id='referother' />";
$("#referto").after(textarea);
}
else
{
$("#referother").remove();
}
});
$(function(){
$("#classcase").change(function(){
var dropdown = $(this).val();
$.ajax({
url:"getoshaclassson.php",
dataType: "json"
}).done( function(data){
$("#otherrecord").find("option").remove();
if(dropdown !== ""){
$("#otherrecord").append($('<option/>'));
}
if(dropdown ==="Other Recordable"){
$.each(data, function(key,value){
if(value.oshaclassid > 3){
$("#otherrecord").append($('<option/>',{
value: value.oshaclassid,
text: value.oshaclass
}));
}
});
}
}
)
}
)
}
);
$(function(){
$("#addlostdays").click(function(){
$("#oshadataarea").find("label").remove();
$("#oshadataarea").find("input").remove();
$("#oshadataarea").find("textarea").remove();
$("#oshadataarea").find("br").remove();
$("#oshadataarea").append($('<label/>',{
text:"Begin Lost Date",
for: "newloststartdate",
class: "eighth"})).append($('<input/>',{
type: "text",
id: "newloststartdate",
name: "newloststartdate",
class:"datepick"
})).append($('<label/>',{
text:"End Lost Date",
for: "newlostenddate",
class: "eighth"})).append($('<input/>',{
type: "text",
id: "newlostenddate",
name: "newlostenddate",
class:"datepick"
}))
});
$('form').on('focus',".datepick", function(){
$(this).datepicker({
changeMonth: true,
changeYear: true
});
});
});
$(function(){
$("#addjobtrans").click(function(){
$("#oshadataarea").find("label").remove();
$("#oshadataarea").find("input").remove();
$("#oshadataarea").find("textarea").remove();
$("#oshadataarea").find("br").remove();
$("#oshadataarea").append($('<label/>',{
text:"Begin Light Duty",
for: "newlightstartdate",
class: "eighth"})).append($('<input/>',{
type: "text",
id: "newlightstartdate",
name: "newlightstartdate",
class:"datepick"
})).append($('<label/>',{
text:"End Light Duty",
for: "newlightenddate",
class: "eighth"})).append($('<input/>',{
type: "text",
id: "newlightenddate",
name: "newlightenddate",
class:"datepick"
}))
});
$('form').on('focus',".datepick", function(){
$(this).datepicker({
changeMonth: true,
changeYear: true
});
});
});
$(function(){
$("#addemphealthcomments").click(function(){
$("#oshadataarea").find("label").remove();
$("#oshadataarea").find("input").remove();
$("#oshadataarea").find("textarea").remove();
$("#oshadataarea").find("br").remove();
$("#oshadataarea").append($('<label/>',{
text:"Employee Comment Date",
for: "newemplcomdate",
class: "eighth"})).append($('<input/>',{
type: "text",
id: "newemplcomdate",
name: "newemplcomdate",
class:"datepick"
})).append($('<br />')).append($('<label/>',{
text:"Employee Comments",
for: "newemplincidomments",
class: "eighth"})).append($('<textarea/>',{
cols: "50",
rows: "5",
id: "newemplincidomments",
name: "newemplincidomments"
}))
});
});
As soon as I add this below function every other function stops working.
$function(){
$("#incidentform").validate({
rules: {
incidate: "required"
},
messages: {
incidate: "Please enter the incident date."
}
})
}
I must be doing something wrong. I am pretty much a neophyte when it comes to jquery as I have only been using it for a month. Hope someone can help.

$(function(){
$("#incidentform").validate({
rules: {
incidate: "required"
},
messages: {
incidate: "Please enter the incident date."
}
})
});
Missing brackets around it.

Related

How to call HierarchicalDataSource.read() from kendoDropDownListchange event?

I am using the treeview and HierarchicalDataSource of KendoUI. Plus on the top I also had a kendoDropDownList. Basically each time user change the dropdownlist value it trigger change event and HierarchicalDataSource will read again. But seem my dropdown change event not working as i expected? I did not call HierarchicalDataSource.read(). Any idea what I doing wrong?
Dropdownlist
$("#dropdown").kendoDropDownList({
dataTextField: "functionName",
dataValueField: "hrsPositionID",
dataSource: {
transport:{
read: {
url: "./getDropdown.php",
type: "POST",
data: function() {
return {
method: "getDropdown",
}
}
},
},
},
change: function(e){
console.log(this.value());
$('#AccountingTree').data('kendoTreeView').HierarchicalDataSource.read(); //<-- not working
}
}).data('kendoDropDownList');
dropdownlist = $("#dropdown").data("kendoDropDownList");
HierarchicalDataSource & kendoTreeView
var serviceRoot = "./getyzdTreeView.php";
dataSource = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: serviceRoot,
dataType: "json",
type: "POST",
data: function(){
return {
positionID: dropdownlist.value() //read the value from dropdownlist
}
}
}
},
schema: {
model: {
id : "programID",
hasChildren: false,
children : "items"
}
},
filter: { field: "module", operator: "startswith", value: "Accounting" }
});
$("#AccountingTree").kendoTreeView({
check: onCheck,
checkboxes: { checkChildren: true } ,
dataSource: dataSource,
dataBound: function(){
this.expand('.k-item');
},
dataTextField: ["module","groupname","programName","checked"]
});
Found it. Basically I just call
change: function(e){
dataSource.read()
}

Form submit inside Ajax JQuery

I have to submit a form inside the Ajax.
I'm receiving 'form.submit is not a function' JQuery error.
$("#form").validate({
// Specify the validation rules
rules: {
type: "required",
groups: {
required: true
}
},
// Specify the validation error messages
messages: {
type: "Type is required",
groups: {
required: "Group is required"
}
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "check_exists.php",
data: {
groups: $( "#groups" ).val(),
type: $( "#type" ).val()
},
success: function(data) {
if(data == "true") {
form.submit(); // It shows form.submit is not a function
} else {
// Displays error
}
}
});
}
});
When I give the form.submit() function above the Ajax, It works!
Then how do I submit this form inside the Ajax success function?
Hey u can use the arrow function feature here
$("#form").validate({
// Specify the validation rules
rules: {
type: "required",
groups: {
required: true
}
},
// Specify the validation error messages
messages: {
type: "Type is required",
groups: {
required: "Group is required"
}
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "check_exists.php",
data: {
groups: $( "#groups" ).val(),
type: $( "#type" ).val()
},
success: (data) => {
if(data == "true") {
form.submit();
} else {
// Displays error
}
}
});
}
});
It will bind the context of the callback function to submitHandler function
try changing the scope of the form variable:
var form_to_be_submitted = null;
$("#form").validate({
// Specify the validation rules
rules: {
type: "required",
groups: {
required: true
}
},
// Specify the validation error messages
messages: {
type: "Type is required",
groups: {
required: "Group is required"
}
},
submitHandler: function(form) {
form_to_be_submitted = form;
$.ajax({
type: "POST",
url: "check_exists.php",
data: {
groups: $( "#groups" ).val(),
type: $( "#type" ).val()
},
success: function(data) {
if(data == "true") {
form_to_be_submitted.submit(); // It shows form.submit is not a function
} else {
// Displays error
}
}
});
}
});

Event to some dynamically generated checkbox issue

My english is not good but I need help please!!!
I am dynamically adding rows to a table, add textbox and checkbox's.
In the change function I want: When the first checkbox is marked the others are disabled and the texbox change their value
The updatebox function It works perfectly for each generated row, but change function only it works with the first.
function agregar() {
var fila = $('<tr></tr>');
var columna = $('<td></td>');
var input = $('<input type="text" />').attr({
name: 'idiomas_usu[]',
id: 'list1'
});
columna.append(input);
input = $('<input type="checkbox" />').attr({
name: 'dos',
class: 'cb2',
id: 'cb2'
});
columna.append(input);
input = $('<input type="text" />').attr({
name: 'idiomas_usu[]',
id: 'list2'
});
columna.append(input);
input = $('<input type="checkbox" />').attr({
name: 'dos',
class: 'cb2',
id: 'cb3'
});
columna.append(input);
input = $('<input type="text" />').attr({
name: 'idiomas_usu[]',
id: 'list3'
});
columna.append(input);
input = $('<input type="checkbox" />').attr({
name: 'dos',
class: 'cb2',
id: 'cb4'
});
columna.append(input);
input = $('<input type="text" />').attr({
name: 'idiomas_usu[]',
id: 'list4'
});
columna.append(input);
input = $('<input type="checkbox" />').attr({
name: 'dos',
class: 'cb2',
id: 'cb5'
});
columna.append(input);
fila.append(columna);
$('#tab_logic').append(fila);
}
function updateBox(event) {
var input = $(this).prev();
if (this.checked) {
input.val("1");
} else {
input.val("");
}
}
function change(event) {
var $this = $(this);
if ($this.is("#cb2")) {
if ($("#cb2:checked").length > 0) {
$("#cb3").prop({
disabled: true,
checked: false
});
$("#cb4").prop({
disabled: true,
checked: false
});
$("#cb5").prop({
disabled: true,
checked: false
});
$("#list2").prop({
disabled: true,
value: ''
});
$("#list3").prop({
disabled: true,
value: ''
});
$("#list4").prop({
disabled: true,
value: ''
});
} else {
$("#cb3").prop("disabled", false);
$("#cb4").prop("disabled", false);
$("#cb5").prop("disabled", false);
}
}
}
$('#boton').click(agregar);
$('#tab_logic').on('click', '.cb2', updateBox);
$('#tab_logic').on('click', '.cb2', change);
Here's the code running: JSfiddle
Please help me!!!!
You have all the same IDs so its grabbing the first occurrence. One option is to give your rows an ID and use that in your jQuery selector to target the correct items, like this: https://jsfiddle.net/rko41z88/8/
Below is a snippet of the fiddle, go to the fiddle to see the whole thing in action.
Give your rows an ID in your agregar() function like this...
window.myRowCnt = window.myRowCnt+1;
var fila = $('<tr id="row'+window.myRowCnt+'"></tr>');
Then use that row ID to target the correct items like this...
function change(event){
var $this = $(this);
var rowId = $this.closest('tr')[0].id;
if ($this.is("#cb2")) {
if ($("#"+rowId+" #cb2:checked").length > 0) {
$("#"+rowId+" #cb3").prop({ disabled: true, checked: false });
$("#"+rowId+" #cb4").prop({ disabled: true, checked: false });
$("#"+rowId+" #cb5").prop({ disabled: true, checked: false });
$("#"+rowId+" #list2").prop({ disabled: true, value: '' });
$("#"+rowId+" #list3").prop({ disabled: true, value: '' });
$("#"+rowId+" #list4").prop({ disabled: true, value: '' });
} else {
$("#"+rowId+" #cb3").prop("disabled", false);
$("#"+rowId+" #cb4").prop("disabled", false);
$("#"+rowId+" #cb5").prop("disabled", false);
}
}
}
This might not be the best answer for you, but I recommend to use React.js framework. It's best for dynamic web applications.

Kendo Scheduler, programmatically set values not updating dataModel

Kendo Scheduler via javascript
Custom Edit Template
Edit Event -> programmatically setting a value on custom template controls
Value shows in control, not included in dataModel
I am implementing a Kendo Scheduler via javascript. I am using a custom edit template because there are several editable fields which are not native to the scheduler. One such field uses a kendo dropdownlist. I have subscribed to the edit event and in this event I get a handle on the dropdown and set its value. The UI element correctly shows the value I have set but when I save the scheduler the dropdownlist value is not included in the JSONified dataModel which I pass off to a CRUD handler. If I manually select an option from the dropdownlist it is included. I called the change event of the dropdownlist for giggles after the programmatic setting of its value. Still nothing. I tried this with textboxes, multiselections, numerictextboxes... they all fail to register their programmatically set values with the model.
Ideas? Thanks.
$(function () {
$("#scheduler").kendoScheduler({
date: new Date("2015/4/14"),
views: [
"day",
{ type: "workWeek", selected: true, showWorkHours: true },
"week",
"month"
],
allDayEventTemplate: $("#allDay-template").html(),
eventTemplate: $("#event-template").html(),
edit: function (e) {
var location = e.container.find("[id=location]");
location.kendoComboBox({
dataTextField: "text",
dataValueField: "value",
dataSource: GetLocations,
filter: "contains",
suggest: true
});
var taskReminder = e.container.find("[id=AddTaskReminder]");
taskReminder.kendoNumericTextBox({
placeholder: "None",
format: "n0",
min: "0",
decimals: "0",
step: 15
});
var wnd = $(e.container).data("kendoWindow");
wnd.setOptions({
width: 800,
height: 600
});
var clientID = $("#clientID");
var ClientID = e.container.find("[id=ClientID]").data("kendoDropDownList");
if (clientID.val() != "All") {
ClientID.enable(false);
}
var Priority = $(e.container.find('[data-bind="value: Priority"]')).data("kendoDropDownList");
if (e.event.isNew()) {
if (clientID.val() != "All") {
ClientID.value(clientID.val());
e.container.find("[id=ClientID]").change();
}
var workerID = $("#workerID");
var WorkerID = e.container.find("[id=workers]").data("kendoMultiSelect");
if (workerID.val() != null) {
WorkerID.value(workerID.val());
e.container.find("[id=workers]").change();
}
Priority.value(2);
(e.container.find('[data-bind="value: Priority"]')).change();
}
var taskName = e.container.find("[id=taskName]");
taskName.kendoComboBox({
dataSource: GetTaskTypes,
dataTextField: "text",
dataValueField: "value",
filter: "contains",
suggest: true
});
var isAllDay = $(e.container.find('[id=isAllDay]'));
var StartDateTime = $(e.container.find('[id=startdatetime]')).data("kendoDateTimePicker");
var EndDateTime = $(e.container.find('[id=enddatetime]')).data("kendoDateTimePicker");
var DueDateFirm = $(e.container.find('[id=DueDateFirm]'));
var Reminder = $(e.container.find('[id=AddTaskReminder]')).data("kendoNumericTextBox")
var TaskComment = $(e.container.find('[id=TaskComment]'));
taskName.change(function () {
$("#TaskTypeName").val($(e.container.find("[id=taskName]")).data("kendoComboBox").text());
if ($(e.container.find("[id=taskName]")).data("kendoComboBox").select() != "-1") {
if (confirm("Apply task type defaults (overriding previous values)?")) {
$.ajax({
type: "GET",
cache: false,
url: "/home/schedule/remotetasks.asp?Action=GetDefaultTaskTypeValues&DefaultTask=" + $(taskName).val(),
success: function (data) {
DS = JSON.parse(data);
Priority.value(DS[0].Priority);
if (DS[0].AllDayEvent == "True") {
isAllDay.prop("checked", true);
}
else {
isAllDay.prop("checked", false);
if (DS[0].DefaultStartTime != "") {
var d = new Date(StartDateTime.value());
d.setHours(DS[0].DefaultStartHour);
d.setMinutes(DS[0].DefaultStartMinute);
StartDateTime.value(d);
}
if (DS[0].DefaultEndTime != "") {
var d = new Date(EndDateTime.value());
d.setHours(DS[0].DefaultEndHour);
d.setMinutes(DS[0].DefaultEndMinute);
EndDateTime.value(d);
}
}
isAllDay.change();
Reminder.value(DS[0].DefaultReminderMinutes);
TaskComment.val(DS[0].TaskComment);
}
});
}
}
});
},
save: function (e) {
if (e.container != null) {
// AssignedTaskName req val
// Dates req val
var isAllDay = e.container.find("[id=isAllDay]");
var startdatetime = e.container.find("[id=startdatetime]");
var startdate = e.container.find("[id=startdate]");
var enddatetime = e.container.find("[id=enddatetime]");
var startdatereq = e.container.find("[id=startdatereq]");
var enddatereq = e.container.find("[id=enddatereq]");
var isAllDay = $(startdate).is(":visible");
if (isAllDay) {
if ($(startdate).val() == "") {
//alert('invalid startdate');
e.preventDefault();
if ($(startdatereq).hasClass('hidden'))
startdatereq.removeClass('hidden');
}
else {
//alert('valid startdate');
if (!$(startdatereq).hasClass('hidden'))
startdatereq.addClass('hidden');
}
}
else {
if ($(startdatetime).val() == "") {
//alert('invalid startdatetime');
e.preventDefault();
if ($(startdatereq).hasClass('hidden'))
startdatereq.removeClass('hidden');
}
else {
//alert('valid startdatetime');
if (!$(startdatereq).hasClass('hidden'))
startdatereq.addClass('hidden');
}
if ($(enddatetime).val() == "") {
//alert('invalid enddatetime');
e.preventDefault();
if ($(enddatereq).hasClass('hidden'))
enddatereq.removeClass('hidden');
}
else {
//alert('valid enddatetime');
if (!$(enddatereq).hasClass('hidden'))
enddatereq.addClass('hidden');
}
}
}
},
editable: {
template: kendo.template($("#customEditorTemplate").html())
},
moveEnd: function (e) {
if (!confirm("Are you sure you want to update this event?")) {
e.preventDefault();
}
},
resizeEnd: function (e) {
if (!confirm("Are you sure you want to update this event?")) {
e.preventDefault();
}
},
dataSource: {
batch: true,
sync: function () {
this.read();
},
transport: {
create: {
url: "/home/schedule/remotemanagecalendar.asp?Action=create",
dataType: "json"
},
read: {
url: "/home/schedule/remotemanagecalendar.asp?Action=read",
dataType: "json"
},
update: {
url: "/home/schedule/remotemanagecalendar.asp?Action=update",
dataType: "json"
},
destroy: {
url: "/home/schedule/remotemanagecalendar.asp?Action=destroy",
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation === "read") {
var scheduler = $("#scheduler").data("kendoScheduler");
var result = {
start: scheduler.view().startDate(),
end: scheduler.view().endDate(),
clientid: $("#clientID").val(),
workerid: $("#workerID").val(),
taskstatus: $("#taskStatus").val()
}
return { models: kendo.stringify(result) };
}
else if (operation === "create" && options.models) {
return { models: kendo.stringify(options.models) + "||" + $("#TaskTypeName").val() };
}
else if (operation === "update" && options.models) {
return { models: kendo.stringify(options.models) + "||" + $("#TaskTypeName").val() };
}
else if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
schema: {
model: {
id: "id",
fields: {
id: { from: "AssignedTaskID", type: "number" },
taskTypeID: { from: "TaskTypeID", type: "int" },
title: { from: "AssignedTaskName", type: "string" },
start: { from: "StartDateTime", type: "date", validation: { required: true } },
end: { from: "EndDateTime", type: "date" },
isAllDay: { from: "isAllDay", type: "boolean" },
dueDateFirm: { from: "DueDateFirm", type: "boolean" },
reminderMinutes: { from: "ReminderMinutes", type: "int" },
ClientID: { from: "ClientID", type: "int" },
Priority: { from: "Priority", type: "int" },
workers: { from: "Workers", nullable: true },
TaskComment: { from: "TaskComment", type: "string" },
locationid: { from: "LocationID", type: "string" }
}
}
}
}
});
});
var GetTaskTypes = new kendo.data.DataSource({
transport: {
read: {
url: "/home/schedule/remotetasks.asp?Action=GetAddTaskTypes",
dataType: "json"
}
}
});
var GetClientIDs = new kendo.data.DataSource({
transport: {
read: {
url: "/home/schedule/remotetasks.asp?Action=GetAddClients",
dataType: "json"
}
}
});
var GetPriorities = new kendo.data.DataSource({
transport: {
read: {
url: "/home/schedule/remotemanagecalendar.asp?Action=GetPriorities",
dataType: "json"
}
}
});
var GetAddWorkers = new kendo.data.DataSource({
transport: {
read: {
url: "/home/schedule/remotetasks.asp?Action=GetAddWorkers",
dataType: "json"
}
}
});
var GetLocations = new kendo.data.DataSource({
transport: {
read: {
url: "/home/schedule/remotemanagecalendar.asp?Action=GetLocations",
dataType: "json"
}
}
});
$("#AddTaskReminder").kendoNumericTextBox({
placeholder: "None",
format: "n0",
min: "0",
decimals: "0",
step: 15
});
I found the answer
edit: function(e) {
e.event.set('modelFieldName', 'value');
}
This sets it on the UI element as well as updates the dataModel. Hope it helps the next poor sap.

Kendoui Grid send dynamic variable in data source

I am trying to "filter" a grid based on an option selected from a select drop down.
How do I send the selected option value to the grid when the change event on the select dropdown fires?
My grid datasource is:
dataSourceParts = new kendo.data.DataSource({
serverPaging: false,
serverFiltering: false,
serverSorting: false,
transport: {
read: {
url: ROOT + 'shipment/partsSerialGrid',
dataType: 'json',
type: 'POST',
data: {
enquiryId: enquiryId
}
}
},
pageSize: 25,
error: function(e) {
alert(e.errorThrown + "\n" + e.status + "\n" + e.xhr.responseText);
},
schema: {
data: "data",
total: "rowcount",
model: {
id: 'id',
fields: {
quantity: {
type: 'number',
editable: false
},
idealForm: {
type: 'string',
editable: false
},
serial: {
type: 'string',
editable: true
}
}
}
}
})
My select event:
$('#fromNameSelect').change(function() {
var fromMode = $('#fromSelect').val();
if (fromMode == 2)
{
supplierId = $(this).val();
dataSourceParts.filter({
field: 'test', operator: 'eq', value: 'test' // THIS DOES NOTHING.
});
$('#shippingPartsGrid').data('kendoGrid').dataSource.read();
}
})
I cant confirm this. But since you set filter in dataSourceParts. Shouldn't you be using dataSourceParts.read() instead of $('#shippingPartsGrid').data('kendoGrid').dataSource.read();?
$('#fromNameSelect').change(function() {
var fromMode = $('#fromSelect').val();
if (fromMode == 2)
{
supplierId = $(this).val();
$('#shippingPartsGrid').data('kendoGrid').dataSource.filter({
field: 'test', operator: 'eq', value: 'test' // DO IT LIKE THIS
});
}
})

Categories