jQuery validate not working with jQuery multiselect - c#

I am using the jQuery validator to validate a jQuery multiselect dropdownlist but it does not validate, my functions are bellow:
These functions are created from my code behind and registered on the page with the ScriptManager.RegisterClientScriptBlock.
I put the following directly on the aspx page and it then validates the multiselect, but as soon as I do it from the code behind and register the script, all validators besides the multiselect works.
$.validator.addMethod('notNone', function(value, element) {
return (value != '-1');
}, 'Please select an option.');
var $callback = $("#callback");
$(document).ready(function () {
$("#<%=example.ClientID%>").multiselect(
{
show: "fade",
hide: "fade",
click: function (event, ui) {
$callback.text(ui.text + ' ' + (ui.checked ? 'checked' : 'unchecked'));
},
});
});
$("#form1").validate({
rules: {
<%=example.UniqueID %>: {
notNone: true,
},
<%=txtPassword.UniqueID %>: {
//minlength: 5,
//required: true
},
<%=TextIdea.UniqueID %>: {
//minlength: 5,
//required: true
},
<%=ddlTest.UniqueID %>: {
//notNone: true
},
redemption : {
redemption : false
},
redemption: {
redemptionEnd : false
},
},
ignore: ':hidden:not("#<%=example.ClientID %>")',
messages: {
<%=example.UniqueID %>:{
notNone: "Plaese select something",
},
<%=txtPassword.UniqueID %>:{
required: "Plaese enter your password",
minlength: "Password must be atleaet of 5 characters"
},
<%=TextIdea.UniqueID %>:{
required: "Plaese enter your Ideas",
minlength: "Password must be atleaet of 5 characters"
},
}
});
My markup:
<select id="example" name="example" runat="server">
</select>
Am I doing something wrong? Please help guys.
Thanks in advance.

Okay, after 2 days I finally figured out what was going on, turns out the controls that use the jQuery multiSelect, their UniqueID gets appended with _multiSelect and the ClientID gets appended with $multiSelect.
Added those strings when getting the Client/UniqueID and it works.

Related

how to add NOTEqual To rule in jQuery.validation

I want to know how i can add jquery validation for not equal values in two input textbox. I have tried this Example but its not working for me.
Jquery Code:
$.validator.addMethod("notEqual", function (value, element, param) {
return this.optional(element) || value != param;
}, "cannot be same as oldpassword");
$("#frmAddEdit").validate({
rules: {
"txtoldpassword": { required: true },
"txtnpassword": { required: true, notEqual:"#txtoldpassword" },
},
messages: {
"txtoldpassword": { required: "old Password is required" },
"txtnpassword": { required: "New Password is required" },
},
submitHandler: function (form) {
ChangeUserPassword();
return false;
}
});
When i put alert on validation method param shows the same value (i.e. #txtoldpassword) and when i put like this notEqual: $("#txtoldpassword").val() param becomes ""(blank)
Please help me on this.
I just changed the way of passing value of textbox for notEqual and it worked for me.
JQuery Code :
$("#frmAddEdit").validate({
rules: {
"txtoldpassword": { required: true, noSpace: true },
"txtnpassword": {
required: true, noSpace: true, notEqual: function () { return $("#txtoldpassword").val() },
}
},
messages: {
"txtoldpassword": { required: "old Password is required" },
"txtnpassword": { required: "New Password is required" },
},
submitHandler: function (form) {
ChangeUserPassword();
return false;
}
});

Postback on ajax request only smartphone and tablet

I wrote some code in a contact form in jquery to validate the form, and if the form is valid, send all data to another file that send email with all data, etc.
Now if i use that form on PC it works, but if I use the form on a tablet or a smartphone, both android and ios, my site does postback and the validate is ignored.
Here is the part of code that validates the form
$('#bottone_invia_messaggio').on("click", function () {
$("#formPrincipale").validate({
submitHandler: function () {
$('#bottone_invia_messaggio').val("Loading")
var urlContatti = "url of a site";
$.ajax({
type: "POST",
url: urlContatti,
success: function () {
$('#bottone_invia_messaggio').val("Messaggio inviato");
$('#bottone_invia_messaggio').addClass("btn-success");
$('#bottone_invia_messaggio').prop('disabled', true);
inviaContatto($("#Nome").val(), $("#Email").val(), $("#Telefono").val(), $("#Messaggio").val());
registraEmailDb($("#Email").val());
}
});
},
onkeyup: false,
onclick: false,
rules: {
ctl00$Nome: {
required: true,
minlength: 2
},
ctl00$Email: {
required: true,
email: true
},
ctl00$Telefono: {
required: true
},
ctl00$Messaggio: {
required: true,
minlength: 10
},
ctl00$Privacy: {
required: true
}
},
messages: {
ctl00$Nome: {
required: "Per favore inserisci il nome",
minlength: "Sembra troppo corto"
},
ctl00$Email: {
required: "Indicaci la tua email",
email: "Email non valida"
},
ctl00$Telefono: {
required: "Inserisci un numero di telefono"
},
ctl00$Messaggio: {
required: "",
minlength: "Il messaggio e' troppo corto"
},
ctl00$Privacy: {
required: "***"
}
},
errorPlacement: function (error, element) {
if (!$(element).parent().is("span")) error.insertBefore(element);
else error.insertAfter($(element).parent());
},
errorElement: "span",
highlight: function (element) {
$(element).parent().removeClass("valid").addClass("has-error");
$(element).removeClass("valid");
},
success: function (element) {
if (!($(element).parent().is("span") || $(element).is("span"))) $(element).parent().removeClass("has-error").addClass("valid");
console.log($(element).parent());
}
});
$("#formPrincipale").attr("novalidate", "");
});
Here is the part of html generated server-side by asp.net
<div id="Contatti" class="formContatti"><div class="row"><div class="col-lg-6"><div class="mb-1"><input name="ctl00$Nome" id="Nome" class="form-control" placeholder="Nome e Cognome*" type="text"></div><div class="mb-1"><input name="ctl00$Email" id="Email" class="form-control" placeholder="Indirizzo Email*" type="text"></div><div class="mb-1"><input name="ctl00$Telefono" id="Telefono" class="form-control" placeholder="Telefono*" type="text"></div></div><div class="col-lg-6"><textarea name="ctl00$Messaggio" rows="2" cols="20" id="Messaggio" class="form-control h-100" placeholder="Messaggio*"></textarea></div></div><div class="col-12 mt-1 text-left"><span><input id="Privacy" name="ctl00$Privacy" type="checkbox"><label for="Privacy">*Accetto i termini sulla <a class="no-decoration" href="/privacy-terms">privacy</a></label></span></div><div class="d-flex flex-row-reverse"><button id="bottone_invia_messaggio" class="btn coloreTasto mt-2">Invia il messaggio</button></div></div>
Sorry if I don't post all the code but there are a lot of sensitive data and is very long. Can anyone help me?
It's possible that what gets output as far as from a generation standpoint might be outputting a different name, which is a challenge with ASP.NET (since you have no control). If your JS code is defined within the ASPX, you can guarantee a match by use the <%= %> notation with a combination of the UniqueID of the control, as the following:
rules: {
<%= Nome.UniqueID %>: {
required: true,
minlength: 2
},
<%= Email.UniqueID %>: {
required: true,
email: true
},
...
The syntax
<%= Email.UniqueID %>
outputs a matching generated name, which may be a part of the problem. It may say (in visual studio) that there is a formatting error in the JS, but this shouldn't have any problem on execution since it will guarantee a matching name.

Setting form values when jQuery datatable row is clicked

I have a web form with a jQuery datatable in it. When a particular row is clicked I get the row data and need to set the values of the controls on the page.
I can get the row values, I set breakpoints and can see the row values fetched are correct but for some reason the control values don't get set (for example, a label's text). This is what I have (watered down version):
$(document).ready(function () {
var zTable = $("#fcTable").DataTable({
"bServerSide": true,
"bDestroy": true,
"sAjaxSource": "../fc.asmx/GetItems",
"bJQueryUI": true,
"fnServerParams": function (aoData) {
aoData.push({ "name": "FacilityID", "value": $('#<%= ddlFacility.ClientID %> option:selected').val() });
},
"fnServerData": function (sSource, aoData, fnCallback) {
$.ajax({
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"type": "GET",
"url": sSource,
"data": aoData,
"success":
function (msg) {
var json = jQuery.parseJSON(msg.d);
fnCallback(json);
$("#fcTable").show();
},
error: function (xhr, textStatus, error) {
if (typeof console == "object") {
alert(xhr.status + "," + xhr.responseText + "," + textStatus + "," + error);
}
}
});
}
});
$('#fcTable tbody').on('click', 'tr', function () {
var currentRowData = zTable.row(this).data();
processRow(currentRowData);
});
})
function processRow(row) {
debugger
$("#<%= rblResp.ClientID %> input[type=radio]").prop('checked', false);
$("#<%= cblResp.ClientID %> input[type=checkbox]").prop('checked', false);
var sQuestion = row[2];
// None of these sets the label's text
$('#<%= lblQuestion.ClientID %>').val(sQuestion);
$('#<%= lblQuestion.ClientID %>').innerHTML = sQuestion;
}
Update
I can get it to work using
$('#<%= lblQuestion.ClientID %>')[0].innerHTML = sQuestion;
i.e. adding an array index [0].
But is this the correct way of doing it?
The issue is that $('#<%= lblQuestion.ClientID %>') returns a jQuery object, and innerHTML is standard JavaScript, and won't work as wanted on a jQuery object.
The [0] on the end of the object gives you the DOM node (first property of the object), which is what innerHTML needs.
The correct way to do it in pure jQuery would be just:
$('#<%= lblQuestion.ClientID %>').html(sQuestion);
FYI, you can set ClientIDMode="Static" on the input, to avoid asp.Net overriding the ID you give it in your HTML, and so avoid all the <%=... stuff in your JavaScript, which works much better if you get to the point where you want to split the JavaScript out into its own file.

Jtable only displays when stepping through debugger

Hi I am struggling to display my jtable. It only displays when I step through the javascript with the debugger.
$("body").on("click", "#tabRole", function () {
document.getElementById("1").className = "inactive";
document.getElementById("2").className = "active";
$('#Admin-details').load('../Admin/ADRoleAdmin');
jTableRoles();
});
This method loads ADRoleAdmin as a partial view into a div. Then jTableRoles() should load the jtable into a div (jTableRoles) inside ADRoleAdmin:
var jTableRoles = function () {
$(function () {
debugger;
$('#jTableRoles').jtable({
paging: true,
pageSize: 20,
sorting: true,
title: 'Roles',
onRowEdit: function (event, data) {
UpdateRoleDetails(data.records.RoleId, data.records.RoleName);
},
actions: {
listAction: '../Admin/GetRoles',
updateAction: 'dummy'
},
toolbar: {
items: [{
icon: '../Content/images/Misc/Add icon.png',
text: 'Create New',
click: function () {
UpdateRoleDetails(0, '');
}
}]
},
fields: {
Id: {
key: true,
list: false
},
Name: {
title: 'Role name',
},
Description: {
title: 'Role description',
sorting: false
}
}
});
$('#jTableRoles').jtable('load');
});
}
Please tell me what I am doing wrong or what I can do different to make it work.
Looping through the steps takes extra time.
It looks like the load of ADRoleAdmin is not finished on the moment the jTable is loaded.
Try to start the jtable after a certain timeout to check.
Preferably load the ADRoleAdmin an on it's postback load the jTable

update Jquery Jtable plugin depending on a selected row in another Table

hello I have the following snippet of code.
Departments
<div>Users </div>
<div id="UserTableContainer"></div>
<script type="text/javascript">
var departmentChangeId = 1;
$(document).ready(function () {
$('#DepartmentTableContainer').jtable({
paging: true,
useBootstrap: true,
sorting: true,
selecting: true,
selectOnRowClick: true,
title: 'Departments',
actions: {
listAction: '/api/Department/GetDepartmentList',
createAction: '/api/Department/CreateDepartment',
updateAction: '/api/Department/EditDepartment',
deleteAction: '/api/Department/DeleteDepartment'
},
fields: {
ID: {
key: true,
list: false
},
TypeId: {
title: 'Department Type',
options: '/api/Department/GetDepartmentTypeList'
},
Label: {
title: 'Department'
},
},
//Register to selectionChanged event to hanlde events
selectionChanged: function () {
//Get all selected rows
var $selectedRows = $('#DepartmentTableContainer').jtable('selectedRows');
departmentChangeId = $selectedRows.data('record').ID;
//alert(departmentChangeId);
//
refresh();
}
}).jtable('load');
$('#UserTableContainer').jtable({
messages: ArabMessages, //Lozalize
paging: true,
useBootstrap: true,
sorting: true,
title: 'Employee',
actions: {
listAction: '/api/Users/GetEmployee?id=' + departmentChangeId,
updateAction: '/api/Users/EditEmployee'
},
fields: {
Id: {
key: true,
list: false
},
DepId: {
title: ' Department',
options: '/api/Department/GetDepartmentTypeList'
},
LastName: {
title: 'Name'
},
}
});
$('#UserTableContainer').jtable('load');
});
and these are the two version I use for the refresh function
first
function refresh() {
$('#UserTableContainer').jtable('reload');
}
the second
function refresh() {
$.post("/api/Users/GetEmployee", "id=" + departmentChangeId,
function (results) {
$('#UserTableContainer').jtable('reload');
}
, "json");
}
unfortunately both of them dont work
instead of when I use debugging mode I see that the /api/Users/GetEmployee is visited in both case
please try using below code in refresh function
$('#UserTableContainer').jtable('load');

Categories