I have a select box. Currently, this select box make an ajax call on change.
Now, I want to make call only when a condition is met.
So, here is my code:
$('#buildingSelect').on('change', function(){
var result = checkDirtyStatus();
//this checkDirtyStatus alert message if there is some changes on the form.
//if cancel return false, if confirm return true.
if(result === false) {
return;
}
//make ajax call
});
This prevents from making ajax call, however, this change the selected option of the select i.e, if option1 is selected at the begining and if I try to select next option then it will change the selected option to option2 then only check the status.
On searching on the internet, I got the option of focusin.
$('#buildingSelect').on('focusin', function(){
// console.log("Saving value " + $(this).val());
var result = checkDirtyStatus();
if(result === false) {
return;
}
}).on('change', function(){
g_building_id = $(this).val();
getAmenitiesDetails(g_building_id);
});
However, using this focusin options makes the alert box to appear everytime no matter either I click cancel or ok. This might be because, it call focusin again whenevr I click Ok or Cancel.
What would be the best option to check this status, and if result is false, I don't want to change the selected option as well.
Update
Answer from marked as duplicate not preventing from changing the selected option. Its making ajax call on click i.e. before checking condition.
CodePen Link
function checkDirtyStatus(){
dirtyStatus = true;
if(dirtyStatus === true){
if (confirm("Changes you made may not be saved.")) {
return true;
}else{
return false;
}
}
}
Finally, by mixing the link from Rory and idea of organizing code from some. I have find a solution for my problem. So, if anyone got stuck on the similar problem here is my solution.
$(function(){
var lastSel;
$('#buildingSelect').on('focusin', function(){
lastSel = $("#buildingSelect option:selected");
}).on('change', function(){
if(!checkDirtyStatus()) {
lastSel.prop("selected", true);
return;
}else{
//made ajax call
//$.ajax({})
}
});
});
function checkDirtyStatus(){
let dirtyStatus = getDirtyStatus();
if(dirtyStatus){
return confirm("Changes you made may not be saved.");
}
return true;
}
Let us look at your function:
function checkDirtyStatus(){
dirtyStatus = true; // I assume this is only for testing
if(dirtyStatus === true){ // This can be simplified.
if (confirm("Changes you made may not be saved.")) {
return true;
}else{
return false;
}
}
}
confirm returns a Boolean that is either true or false, so you can simplify your function like this:
function checkDirtyStatus(){
dirtyStatus = true;
if(dirtyStatus){
return confirm("Changes you made may not be saved.");
}
// Notice that you do not return anything here. That means that
// the function will return undefined.
}
Your other function can be simplified like this:
$('#buildingSelect').on('change', function(){
if(!checkDirtyStatus()){
// Here you probably want to set the value of the select-element to the
// last valid state. I don't know if you have saved it somewhere.
return;
}
//make ajax call
});
I played with your codepen and you have some errors in your selectors. As I get confused by your explanation I will try to explain what you could update and how to use it in your code and I hope this is what you need to solve your problem.
First I would change your js to this:
var lastSel = $("#buildingSelect").val();
$("#buildingSelect").on("change", function(){
if ($(this).val()==="2") {
$(this).val(lastSel);
return false;
}
});
The proper way to get the value of a select box in jquery is with the .val(). In your case you selected the entire selected option element.
I store this value in the lastSel variable. Then in the change function the new value of the select list is $(this).val(). I check against this value and if it equals 2 I revert it to the value stored in the lastSel variable with this $(this).val(lastSel).
Keep in mind that the value of a select list is always a string, if you want to check against a number you must first cast it to a numeric value e.g. by using parseInt.
If you want to use the checkDirtyStatus for the check then you should only call this function in the change and pass as parameters the lastSel and the newSel like this:
$("#buildingSelect").on("change", function(){
checkDirtyStatus(lastSel, $(this).val());
});
Then you can transfer the logic from the change function into the checkDirtyStatus function and do your checks there. In this case if you wish to revert the select value instead of $(this).val(lastSel) you will do a $("#buildingSelect").val(lastSel).
I hope this helps.
Related
I have a popup on my page that has a typeahead input on it. Right now you can type garbage and click submit and it lets you. I'm trying to write code that will throw an error on the popup if you type something that isn't included in the typeahead options and it won't let you submit it until you fix it. Here is my code, it is for making a school schedule that has classes in the typeahead dropdown.
var schedule = schedule.content.get();
var validClasses = Fp.filter(schedule.classes, function (class) { return !class.passed; }),
inputClasses = $('.optimizeViaClasses input.className').map(function () { return $(this).val(); }),
isErrorForValidClasses = Fp.all(inputClasses, function (inputClass) { return Fp.contains(validClasses, inputClass); });
if(validClasses !== inputClasses){
$errorMessage.text('Your selection does not match the class(es) in the current schedule!');
$errorMessage.show();
}
Right now if you enter garbage in the input field, this will throw an error but still let the user submit. How can I stop the user from submitting until the input is correct?
Here is my button:
$submitBtn.on('click', function(event){
if(inputParameters() !== false){
$myPopUp= $modal.find('#myData').detach()[0];
}
event.preventDefault();
});
and I checked the output of inputClasses in the Google developer console, it outputs the class and a prevObject. I just need the class...
Let javascript return either True or false and if the popup comes out return false other wise true.
For instance if it get into if return false other wise true.
since you modified your code i suppose you might want to try this instead:
http://api.jquery.com/event.stoppropagation/
also you might want to be doing something along the lines of this if stoppropagation does not result in the desired effect:
$("#formid").on("submit",function(e){
// declare isValid outside of this and set it in your validation function or call it inside this and check for that.
if(isValid) {
e.stopPropagation();
}
});
at least that's how i went about solving such issues usually. i hope it helps.
got it. the error i had was throwing an error.
var schedule = schedule.content.get(),
validClasses = Fp.filter(schedule.classes, function (class) { return !class.passed; }),
inputClasses = $('.optimizeViaClasses input.className').map(function () { return $(this).val(); }),
actualValidClasses = Fp.pluck(validClasses, 'className');
$.each(inputClasses , function(index, value){
if($.inArray(value, actualValidClasses ) === -1){
$errorMessage.text('Your selection does not match the class(es) in the current schedule!');
$errorMessage.show();
error = true;
return false;
}
});
I am still confused about this. Started learning JQuery about a week now and this is what I have:
var IsValidUserName = false;
$(document).ready(function () {
$('#txtUserName').blur(function () {
if ($('#txtUserName').val().match(isNumberLetter) &&
($('#txtUserName').val().length >= 8)) {
$('#userNameError').removeClass("error").addClass("default");
$('#txtUserName').removeClass("alert");
$('#txtUserName + label').removeAttr("id", "lblUserName");
IsValidUserName = true;
}
else {
$('#userNameError').removeClass("default").addClass("error");
$('#txtUserName').addClass("alert");
$('#txtUserName + label').attr("id", "lblUserName");
}
});
});
Lets say I have another function like above, lets say FirstName:
How do I call this on the submit event? The code works as I need it to when the user leaves a field. Not sure how I can also call this code and also use the variable above to prevent submit if the data entered is invalid.
I need to call the validation above if the user clicks the submit button and stop the submission if the IsValidUserName variable is false.
Somethings just need a little push.
Thanks my friends.
Guy
You could always extract it into a function instead of an anonymous function and pass the reference to the object you want to check. This would give you the added benefit of reusing it for other elements.
function validate(ele) {
var valid;
if (ele.val().match(isNumberLetter)) && (ele.val().length >= 8)) {
valid = true;
// update user here.
} else {
valid = false;
// update user here.
}
return valid;
}
$(function(){
$('#firstName').blur(function(){ validate($(this)); });
$('#lastName').blur(function(){ validate($(this)); });
$("yourFrom").submit(function(){
var firstNameIsValid = validate($('#firstName'));
var lastNameIsValid = validate($('#lastName'));
if (!nameIsValid) && (!lastNameIsValid) {
return false;
// User has already been updated
}
});
});
Also, since you are already heavily using javascript for your validation (hope this is convenience and not the only security), you can also disable the submit button entirely until the form meets the proper requirements.
I am having the following JQuery function that is working properly:
$(function () {
$('#accmenu').change(function() {
$(".insightsgraphs div").hide();
$(".insightsoptions input").removeClass("green");
$("#newLikes").one('click', function () {
$.ajax({type:'GET', url: 'newLikes.php', data:$('#ChartsForm').serialize(), success:
function(response) {
var json = response.replace(/"/g,'');
json = "[" + json + "]";
json = json.replace(/'/g,'"');
var myData = JSON.parse(json);
var myChart = new JSChart('dailyNewLikes', 'line');
myChart.setDataArray(myData);
myChart.setAxisNameX('');
myChart.setAxisNameY('');
myChart.setAxisValuesColorX('#FFFFFF');
myChart.setSize(470, 235);
myChart.setTitle('Daily New Likes');
myChart.draw();
}});
return false;
});
$("#unlikes").one('click', function () {
$.ajax({type:'GET', url: 'unlikes.php', data:$('#ChartsForm').serialize(), success:
function(response) {
$("#dailyUnlikes").html(response);
}});
return false;
});
});
$("#newLikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyNewLikes').toggle();
return false;
});
$("#unlikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyUnlikes').toggle();
return false;
});
});
but I want to create a condition: if one of the following two date inputs:
var since = $('#dateoptions input[name="since_date"]').val();
var until = $('#dateoptions input[name="until_date"]').val();
is empty I want to receive an alert and the .one() function to be executed only when the conditions are met. For example when I click on one of the button without the date inputs in place I want to receive an alert like alert("One of the date or both missing") for example and after I choose the dates and press the button again to execute the .one() function like in the above example. I hope I make myself clear enough. I know that I can use something like:
if (until == "" || since == "") {
alert("One of the date or both missing")
} else {}
but my tries so far was no success. Probably I didn't place the condition where it should... Also it is possible also with an alert the inputs to be focused, highlighted or something similar?
EDIT:
Here's a fiddle with it:
http://jsfiddle.net/DanielaVaduva/ueA7R/6/
I replace the ajax call with something else without to modify the flow.
Try checking your values with:
if (until.trim().length === 0 || since.trim().length === 0) {
//TODO here
}
I suggest you that check your name attribute in your inputs and check that it's the same that you use when you are retrieving the values of the inputs.
If it still not working, try some 'debugging' like:
console.log(since);
And check if it is getting your value properly.
UPDATE
I don't know if you wanted this (demo). If your dates are empty, it will not work. AJAX call will not work on JsFiddle, because you are using a .serialize() and it sends the information via URL, as a GET type and you need to send it as POST. It doesn't matter. If you already prepared your server to recieve a GET method, it will work.
Also, I must add that if you want to change color ONLY if the AJAX was success, you must add your change color function as I used on the demo and if you want to check your date every time you want to send information to server, change .one() function into .on() function and remove the function after the AJAX success with:
$('#myimage').click(function() { return false; }); // Adds another click event
$('#myimage').off('click');
$('#myimage').on('click.mynamespace', function() { /* Do stuff */ });
$('#myimage').off('click.mynamespace');
(More info about removing a function here);
I hope this will help you atleast on the way you want to do. Leave a comment if it is not what you wanted.
I'm not sure if I understood the issue exactly but.. you can check this >>
Fiddle Demo
HTML
Add IDs to the date fields like
<input id="until" type="date" name="until_date" value="Until date">
<input id="since" type="date" name="since_date" value="Since date">
And just for highlighting the required dates >>
CSS
.req{
border:2px red solid;
}
.required{
color:red;
font-size: 0.8em;
font-style:italic;
}
jQuery
$(function () {
//removing the highlighting class on change
$('#until').change(function() {
$(this).removeClass('req').next('.required').remove();
});
$('#since').change(function() {
$(this).removeClass('req').next('.required').remove();
});
$('#accmenu').change(function() {
var dSince= $('#since').val();
var dUntil= $('#until').val();
if(dSince=='' || dUntil==''){
alert('You MUST select Both dates!');
$(this).val(0); // Set the menu to the default
//Adding the Highlight and focus
if(dSince==''){
$('#since').addClass('req').after('<span class="required">- required *</span>').focus();}
if(dUntil==''){
$('#until').addClass('req').after('<span class="required">- required *</span>').focus();}
}else{
$(".insightsgraphs div").hide();
$(".insightsoptions input").removeClass("green");
$("#newLikes").one('click', function () {
$("#dailyNewLikes").html('</p>Test daily new likes</p>');
return false;
});
$("#unlikes").one('click', function () {
$("#dailyUnlikes").html('</p>Test daily unlikes</p>');
return false;
});
} //End of the if statement
});
$("#newLikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyNewLikes').toggle();
return false;
});
$("#unlikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyUnlikes').toggle();
return false;
});
});
Thus whenever an option from the accmenu gets selected, it will check for the values of the two DATEs, if both or any is blank, it won't execute the function.
I have an input, when the user enters something, my script sends the info over to a php script, which returns whether or not the entered text can be used.
If the text can not be used, it disables the submit button and adds a class to the reult text.
The problem have is strange, the ajax works, the result is returned, but the button disabling and adding of the class doesn't happen unless you focus and blur the input a second time.
Here is my code:
$('#alias').blur(function() {
if ($('#alias').val()) {
var aliascheck = $('#alias').val();
$(".aliascheck").load('checkalias.php?alias='+aliascheck);
var result = $('.aliascheck').text();
if (result.indexOf("Taken") != -1) {
$('#shorten').attr("disabled","disabled");
$('.aliascheck').addClass('error');
} else {
$('#shorten').removeAttr("disabled");
$('.aliascheck').removeClass('error');
}
}
});
The code is live here: http://markhenderson.ws/dev/tmtmu/
To replicate the "taken" event, enter "taken" as the alias. Any thing else will return available.
Does anyone know why this is happening?
Thanks
You need to put the code after the .load call into a callback function of the async call.
Something like:
$('#alias').blur(function() {
if ($('#alias').val()) {
var aliascheck = $('#alias').val();
$(".aliascheck").load('checkalias.php?alias='+aliascheck, function() {
var result = $('.aliascheck').text();
if (result.indexOf("Taken") != -1) {
$('#shorten').attr("disabled","disabled");
$('.aliascheck').addClass('error');
} else {
$('#shorten').removeAttr("disabled");
$('.aliascheck').removeClass('error');
}
});
}
});
I have a bunch of controls:
When a user clicks the Generate button, a function uses all of the values from the other controls to generate a string which is then put in the Tag text box.
All of the other controls can have a value of null or empty string. The requirement is that if ANY of the controls have no user entered value then the Generate button is disabled. Once ALL the controls have a valid value, then the Generate button is enabled.
What is the best way to perform this using Javascript/jQuery?
This can be further optimized, but should get you started:
var pass = true;
$('select, input').each(function(){
if ( ! ( $(this).val() || $(this).find(':selected').val() ) ) {
$(this).focus();
pass = false;
return false;
}
});
if (pass) {
// run your generate function
}
http://jsfiddle.net/ZUg4Z/
Note: Don't use this: if ( ! ( $(this).val() || $(this).find(':selected').val() ) ).
It's just for illustration purposes.
This code assumes that all the form fields have a default value of the empty string.
$('selector_for_the_parent_form')
.bind('focus blur click change', function(e){
var
$generate = $('selector_for_the_generate_button');
$generate.removeAttr('disabled');
$(this)
.find('input[type=text], select')
.each(function(index, elem){
if (!$(elem).val()) {
$generate.attr('disabled', 'disabled');
}
});
});
Basically, whenever an event bubbles up to the form that might have affected whether the generate button ought to be displayed, test whether any inputs have empty values. If any do, then disable the button.
Disclaimer: I have not tested the code above, just wrote it in one pass.
If you want the Generate button to be enabled as soon as the user presses a key, then you probably want to capture the keypress event on each input and the change event on each select box. The handlers could all point to one method that enables/disables the Generate button.
function updateGenerateButton() {
if (isAnyInputEmpty()) {
$("#generateButton").attr("disabled", "disabled");
} else {
$("#generateButton").removeAttr("disabled");
}
}
function isAnyInputEmpty() {
var isEmpty = false;
$("#input1, #input2, #select1, #select2").each(function() {
if ($(this).val().length <= 0) {
isEmpty = true;
}
});
return isEmpty;
}
$("#input1, #input2").keypress(updateGenerateButton);
$("#select1, #select2").change(updateGenerateButton);
The above assumes that your input tags have "id" attributes like input1 and select2.