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...");
}
}
Related
I have a jquery:Datatable with a custom Save button like below:
...,
{
text: 'Save',
action: function (e, dt, node, config) {
var json = JSON.stringify(dt.rows().data().toArray());
var dat = $('#MainContent_ddlDate').val();
var cols = ""
dt.columns().header().each(function (e, i) {
var col = jQuery(e).html();
cols += col + ",";
});
$.ajax({
type: "POST",
url: 'Ranking.aspx/SaveRanks',
data: JSON.stringify({ 'tbldata': json, 'cols':cols, 'surveydate': dat }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
window.location.reload();
},
error: function (e) {
Console.log(e);
}
});
}
}
Note that in this datatable, all the columns and rows are created in the back-end dynamically based on some values in SQL DB.
My problem is, when I change a value in a cell and click the save button, it always gets the original value instead of the updated one. I could not find out how to fix this issue.
There is no page refresh occurring, it never hits page_load when "save" is clicked..
Any help would be appreciated.
Regards.
In your success function include this line:
$('#my-datatable').DataTable().ajax.reload();
This reloads the existing table.
I have a function that will refresh the page based on the number chosen:
prodName="doesn't matter, not directly $.ajax related"
function searchProduct() {
var prodName = $("#admin-search-product").val().trim();
var pagenumb = 1;
$(".page-item").click(function() {
pagenumb = $(this).children('.page-link').attr('value');
});
alert(pagenumb);
if (prodName == "") {
$.ajax({
type: "POST",
url: "admin_search_product.php",
data: {
search_prod: 0,
},
success: function(respond) {
$("#admin_content").html(respond).show();
$("#admin-search-product").focus().val('').val(prodName);
}
});
} else {
$.ajax({
type: "POST",
url: "admin_search_product.php",
data: {
search_prod: 1,
searchName: prodName,
pagenumb: pagenumb
},
success: function(respond) {
$("#admin_content").html(respond).show();
$("#admin-search-product").focus().val('').val(prodName);
}
});
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="admin-search-product">
<div class="page-item">
<input class="page-link">
</div>
<button onclick="searchProduct()">clickme</button>
Everything works well, except the problem is that the pagenumb variable stays on "1" even though the code "pagenumb = $(this).children('.page-link').attr('value');" can retrieve the value of the page clicked, tested with alert() function and it can return the value of "2" if put within the click function.
However if I test the alert() function outside the click function, it shows that the pagenumb variable stayed the same. I don't know why it doesnt want to change the received value even though I'm able to receive it.
You should bind the event handler once when the page is ready, not every time you searchProducts().
You want the change event, not click. pagenumb should be updated when the input's value changes. Click will only try to update the value when you focus the input box, which is not what you want.
prodName = "doesn't matter, not directly $.ajax related"
var pagenumb = 1;
// you should bind this event handler _once_ when the _page is ready_
// you want the change event, not click. update pagenumb whenever value _changes_
$(".page-item").change(function() {
// coerce to number using + operator
pagenumb = +$(this).children('.page-link').val();
});
function searchProduct() {
var prodName = $("#admin-search-product").val().trim();
alert(pagenumb);
if (prodName == "") {
$.ajax({
type: "POST",
url: "admin_search_product.php",
data: {
search_prod: 0,
},
success: function(respond) {
$("#admin_content").html(respond).show();
$("#admin-search-product").focus().val('').val(prodName);
}
});
} else {
$.ajax({
type: "POST",
url: "admin_search_product.php",
data: {
search_prod: 1,
searchName: prodName,
pagenumb: pagenumb
},
success: function(respond) {
$("#admin_content").html(respond).show();
$("#admin-search-product").focus().val('').val(prodName);
}
});
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="admin-search-product">
<div class="page-item">
<input class="page-link">
</div>
<button onclick="searchProduct()">clickme</button>
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
I have a dropdownlist and when I selected a value from it I am checking the value from another table and according to returning value I change the visibility of a layout item. Now I need to set it Required if it is visible(If the value from ajax is 3 or 5). How can I do it? Here is my ajax that set visible or not.
Edit: I want to set liGid required when in if condition.
`$.ajax({
type: "POST",
url: "TestPage.aspx/GetCode",
data: '{"XKod":"' + s.GetValue().toString() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if (msg.d.GrupKodu == 3 || msg.d.GrupKodu == 5) {
fytbTab0.GetItemByName('liGid').SetVisible(true);
}
else {
fytbTab0.GetItemByName('liGid').SetVisible(false);
}
}
});`
Add the line
fytbTab0.GetItemByName('liGid').required = true;
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");
}
}
});
}
}