model validation summary errors alert box is disabled on .hide() - javascript

I have a postcode finder on my mvc web application form which is optional. If I dont get a post code match I appened the .validation-summary-errors with my own custom error message. Once the error has been corrected I remove all instances of class postcode in .validation-summary-errors and apply the hide method. The problem is when hiding the validation-summary-errors div disables the validation popup to show other form errors when submitting the form.
my javascript code
$("#AddressFinder").click(function () {
var postcode = $("#Address_Postcode").val();
$(".postcode-error").remove();
$(".validation-summary-errors").hide();
if (!postcode) {
$(".validation-summary-errors ul").append("<li class='postcode-error'>Please include a postcode to search.</li>");
$(".validation-summary-errors").show();
}
else {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/Postcode/GetAddress",
data: "{ 'postcode':'" + postcode + "' }",
success: function (data) {
if ($.isEmptyObject(data)) {
$(".validation-summary-errors").append("<li class='postcode-error'>There are no addresses matching your postcode</li>");
$(".validation-summary-errors").show();
}
else {
vm.addresses(data);
addressList.show();
}
}
});
}
});
how can i hide the valiidation-summary-errors div without it disabling when submitting the form to the controller?

Managed to fix my issue. Your not suppose to use hide() or show(). Just add or remove the validation-summary-validation.
$("#AddressFinder").click(function () {
var postcode = $("#Address_Postcode").val();
if (!postcode) {
$(".validation-summary-errors ul").append("<li class='postcode-error'>Please include a postcode to search.</li>");
$(".validation-summary-errors").removeClass("validation-summary-valid");
}
else {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/Postcode/GetAddress",
data: "{ 'postcode':'" + postcode + "' }",
success: function (data) {
if ($.isEmptyObject(data)) {
$(".validation-summary-errors").append("<li class='postcode-error'>There are no addresses matching your postcode</li>");
$(".validation-summary-errors").removeClass("validation-summary-valid");
}
else {
vm.addresses(data);
addressList.show();
$(".postcode-error").remove();
$(".validation-summary-errors").addClass("validation-summary-valid");
}
}
});
}
});
This way you still get the model validation messeges working when the form is submitted.

Related

Change ajax default alert box style

Is there a way I could change the default ajax alert box? I currently have the code below, that deletes a user and reloads the current page. It works, but I would like to add some styling to the alert box that it triggers before the user is actually deleted.
function deleteUser(id) {
var action = confirm("Are you sure you want to delete this student?");
if (action != false) {
$.ajax({
url: '{% url "student-delete" %}',
data: {
'id': id,
},
dataType: 'json',
success: function (data) {
if (data.deleted) {
$("#userTable #user-" + id).remove();
window.location.reload()
}
}
});
}
}
I tried changing the confirm to
function deleteUser(id) {
var action = bootstrap.confirm("Are you sure you want to delete this student?");
if (action != false) {
$.ajax({
url: '{% url "student-delete" %}',
data: {
'id': id,
},
dataType: 'json',
success: function (data) {
if (data.deleted) {
$("#userTable #user-" + id).remove();
window.location.reload()
}
}
});
}
}
This displayed nothing.
You cannot style the custom confirmation box. It varies from browser to browser. If you want something custom you can build out one yourself using HTML and CSS. For example attach click events for yes button and for a no button and based on that you can make the delete

How do I prevent reset the select box after ajax post action?

I want to make the option I selected fix to after AJAX POST.
Currently I am doing the work manually.
I put the value at OnChange in the HiddenField,
and after doing AJAX POST, re-insert the value selected in "ddlUserCont".
<select id="ddlUserCont" onchange="ddlUserCont_Onchange(this);"></select>
function ddlUserCont_Onchange(obj) {
document.getElementById("<%=hidSelddlUserCont.ClientID %>").value = obj.value;
}
-> After AJAX POST action..
function btnTest_Click() {
// ... Some logic
$.ajax({
type: "POST",
cache: false,
url: "../../WebServices/WebService.asmx/GetTest",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
OnSuccess_GetTest(data, sTestVal);
},
error: function (request, status, error) {
console.log("code:" + request.status + "\n" + "message:" + request.responseText + "\n" + "error:" + error);
}
});
}
function OnSuccess_GetTest(response, sTestVal) {
var items = response.d;
// ... Some logic
var sSelPageName = document.getElementById("<%=hidSelddlUserCont.ClientID %>").value;
document.getElementById("ddlUserCont_" + sSelPageName).selected = "true";
}
Do I use UpdatePanel ?
Why is it getting reset? is the page reloading? or is some other script resetting it?
function OnSuccess_GetTest(response, sTestVal) {
var items = response.d;
// ... Some logic
var sSelPageName = document.getElementById("<%=hidSelddlUserCont.ClientID %>").value; // get the value from the hidden field
document.getElementById("ddlUserCont).value = sSelPageName; // set it on the select options element
}
Just make sure that select has an option child element with value=<sSelPageName> at the time.

How to delay ajax call on keypress?

I have an input box where I'm doing an AJAX GET to check if the email is within my database. I'm simply checking for an email address and if it's within the database, we retrieve true/else false. So depending on the return I display either a tick or cross image.
$.ajax({
url: '/api/user/emailaddress/' + emailAddress,
type: 'GET',
dataType: 'json',
success: function(data) {
if (data===true) {
$(".email-address-validator").removeClass("success");
$(".email-address-validator").addClass("error");
}
}
});
Each time a key is pressed within the input box field, this gets called. The problem that I thought might prop up is if someone looks at this file and see's that I'm doing an AJAX GET request on the field that they might just keep pressing keys on that particular input box.
Q: How can I set a timeout on this, for around 5 seconds so a user doesn't just keep spamming the box?
You could set a flag to handle this scenario. Something like this is much better than a timer.
var waitingForResponse= false;
function isValidEmail () {
if (!waitingForResponse) {
waitingForResponse = true;
$.ajax({
url: '/api/user/emailaddress/' + emailAddress,
type: 'GET',
dataType: 'json',
success: function(data) {
waitingForResponse= false;
if (data===true) {
$(".email-address-validator").removeClass("success");
$(".email-address-validator").addClass("error");
}
}
});
}
}
This design pattern will prevent subsequent requests until the first response is received. If you need a further interval between requests than this suggestion, then you can wrap the waitingForResponse flag in a setTimeout function inside the success callback. Like so:
var waitingForResponse= false;
function isValidEmail () {
if (!waitingForResponse) {
waitingForResponse = true;
$.ajax({
url: '/api/user/emailaddress/' + emailAddress,
type: 'GET',
dataType: 'json',
success: function(data) {
setTimeout(function () {
waitingForResponse= false;
}, 5000);
if (data===true) {
$(".email-address-validator").removeClass("success");
$(".email-address-validator").addClass("error");
}
}
});
}
}

Having issues on if-else statement on the text changed event

I have a little bit issue here on my html text changed event in regards with my if-else statement. Here's the scenario, I have the html layout below which has a dropdown list of all locations. Now, if type in your location on the input text box which has id of "#searchloc" it will query as you typed in and rebind the record list on the "#dropdownlist" div element. So my problem is, I want to rebind the "#dropdownlist" div element back to its default which shows all locations once I clear back or empty the "#searchloc" input textbox but the "#dropdownlist" div element remained clear or empty. Below I tried to use if-else statement to do this but I notice that under the else{...} statement it won't fire the function or even the alert method. How do I handle this type of issue in jquery?
HTML Layout:
<input type="text" id="searchloc" class="searchloc" onchange = "QueryLocation();" onkeydown="this.onchange();" onkeyup="this.onchange();" onkeypress = "this.onchange();" oninput = "this.onchange();" placeholder="Search Location" />
<div id="dropdownlist" data-bind="foreach: PopulateAllLocation" >
<div id="alllocationdiv" > <label id="listlocation" class="listlocation" data-bind="text: CityTown"></label></div>
</div>
jQuery:
// Change the dropdownlist result as text input change
function QueryLocation() {
if ($("#searchloc").val() != null) {
var dataObject = {
CityTown: $("#searchloc").val()
};
$.ajax({
url: '/OnlineStore/SearchLocation',
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: dataObject,
dataType: 'json',
success: function (data) {
self.PopulateAllLocation(data);
},
error: function () {
console.log('err')
}
});
}
else {
// Under this else statement won't fire any of this function...???
DisplayLocations();
alert("Textbox is empty...");
}
}
When you check for a value of an empty textbox in Javascript its not null its "" i.e empty string instead. So in your if condition the value is never equal to null, that is the reason the else part is never executed.
function QueryLocation() {
if ($("#searchloc").val() != "") {
var dataObject = {
CityTown: $("#searchloc").val()
};
$.ajax({
url: '/OnlineStore/SearchLocation',
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: dataObject,
dataType: 'json',
success: function (data) {
self.PopulateAllLocation(data);
},
error: function () {
console.log('err')
}
});
}
else {
DisplayLocations();
alert("Textbox is empty...");
}
}

How to pass extra parameter in jquery post request from outside click event?

Hi i have jquery request like below ,
$('#filterForm').submit(function(e){
e.preventDefault();
var dataString = $('#filterForm').serialize();
var class2011 = document.getElementById("2011").className;
//var validate = validateFilter();
alert(dataString);
if(class2011=='yearOn')
{
dataString+='&year=2011';
document.getElementById("2011").className='yearOff';
}
else
{
document.getElementById("2011").className='yearOn';
}
alert (dataString);
$.ajax({
type: "POST",
url: "myServlet",
data: dataString,
success: function(data) {
/*var a = data;
alert(data);*/
}
});
and my Form is like ,
<form method="post" name="filterForm" id="filterForm">
<!-- some input elements -->
</form>
Well, I am triggering jquery submit on submit event of a form ,(it's working fine)
I want pass one extra parameter inside form which is not in above form content but it's outside in page
it's like below
[Check this image link for code preview][1]
So how can i trigger above event , on click of , element with class yearOn ( check above html snippet ) and class yearOff , with additional parameter of year set to either 2011 or 2010
$(document).ready(function () {
$('#filterForm').submit(function (e) {
e.preventDefault();
var dataString = $('#filterForm').serialize();
if ($("#2011").hasClass('yearOn')) {
dataString += '&year=2011';
$("#2011").removeClass('yearOn').addClass('yearOff');
}
else {
$("#2011").removeClass('yearOff').addClass('yearOn');
}
$.ajax({
url: "/myServlet",
type: "POST",
data: dataString,
success: function (data) {
/*var a = data;
alert(data);*/
}
});
});
});
1.) If you are using jQuery already, you can use the $.post() function provided by jquery. It will make your life easier in most cases.
2.) I have always had a successful post with extra parameters this way:
Build you extra parameters here
commands={
year:'2011'
};
Combine it with your form serialize
var dataString=$.param(commands)+'&'+$("#filterForm").serialize();
Perform your post here
$.post("myServlet",data,
function(data) {
/*var a = data;
alert(data);*/
}
);
OR use $.ajax if you really love it
$.ajax({
type: "POST",
url: "myServlet",
data: dataString,
success: function(data) {
/*var a = data;
alert(data);*/
}
In the end, here is the full code the way you are doing it now
$('#filterForm').submit(function(e){
e.preventDefault();
var class2011 = document.getElementById("2011").className;
//var validate = validateFilter();
alert(dataString);
if(class2011=='yearOn') {
dataString+='&year=2011';
document.getElementById("2011").className='yearOff';
} else {
document.getElementById("2011").className='yearOn';
}
commands={
year:'2011'
};
var dataString=$.param(commands)+'&'+$("#filterForm").serialize();
alert (dataString);
$.ajax({
type: "POST",
url: "myServlet",
data: dataString,
success: function(data) {
/*var a = data;
alert(data);*/
}
});

Categories