JavaScript greater than not working - javascript

I have a JavaScript snippet:
function verifyFrnds(){
var boxes=$(".matchFrnds:checked").length;
//alert(boxes); its value is 50 when you do alert
var call=1;
$(".matchFrnds").each(function(index){
if($(this).is(':checked')){
call++;
var sendData= $(this).val();
$.post('SOME PHP Page',{sendData:sendData},function(data){
//window.location.reload();
});
//alert(call); value is 1
// 1 >=50 should be false but all the time the condition gets true
if(call >= boxes)
{
window.location.reload();
}
}
});
}
The question is self explanatory. The conditions gets true even when it is not. Not sure if it is due to that it is not treating them as numbers and strings may be, but all the time the condition gets true.

I'm missing some context but try this:
function verifyFrnds() {
var boxes = $(".matchFrnds:checked").length;
$(".matchFrnds:checked").each(function(index) {
var sendData= $(this).val();
$.post('SOME PHP Page',{sendData:sendData},function(data){
//window.location.reload();
});
if(index >= boxes-1) {
window.location.reload();
return false;
}
});
}

use below code
if(parseInt(call) >= parseInt(boxes))
{
window.location.reload();
}

Doesn't window.location.reload() from your post callback resets your checkboxes thus none being checked ?
1 will always be greater than 0
Of course that this depends on how the form is initialized in HTML, but we don't know this from your example.
Maybe if you present to us a more detailed explanation of what you have and what you want to do, we can present you a better solution.

Related

Prevent Select from changing selected option if condition is not met

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.

Why javascript IF/ELSE doesn't work properly?

I'm new to JavaScript and I want to make username validation on registration form. I don't know what's wrong on my code but I think I have a problem with "IF ELSE" statement.
$(document).ready(function() {
$("#usernameErrorMsg").hide();
var usernameLength = $("#username").length;
$("#username").focusout(function() {
checkUser();
});
function checkUser() {
if (usernameLength < 5 || usernameLength > 20) {
$("#usernameErrorMsg").show();
} else {
$("#usernameErrorMsg").hide();
}
}
});
I expected that when I input more than 5 char until 20 char, the usernameErrorMsg will disappear. The actual result, no matter how many characters that I have input, the error message keeps coming up.
usernameLength is being computed only once, before checkUser() ever runs. You should re-calculate its value inside the callback each time; otherwise, changes to that value will not be visible inside the callback.
Furthermore, if you want to check the length of the test in the input, you need to check $("#username").val().length, not $("#username").length:
function checkUser(){
var usernameLength = $("#username").val().length;
if (usernameLength < 5 || usernameLength > 20){
$("#usernameErrorMsg").show();
} else {
$("#usernameErrorMsg").hide();
}
}
$("#username").length is not the length of the characters in the field. It's the amount of elements in the JQuery wrapped set returned from your query. Since only one element will have an id of username, the length is always 1 and your if condition will always be true.
What you'll have to do is get the length of the value in the field:
$("#username").val().length
You'll also want to move the line that gets the value into the focusout event handler so that you are always working with the most current data.
Lastly, it doesn't make much sense to have a function do nothing but call another function, so you can combine the checkUser function with the event callback and simplify the code.
$(document).ready(function() {
$("#usernameErrorMsg").hide();
var username = $("#username"); // Find the element just once
$("#username").focusout(function() {
// Each time the user leaves the field, get the current
// amount of characters in the input field
var usernameLength = username.val().length;
// See the difference between the length of the JQuery query and
// the length of the value of the first element in the results?
console.log(username.length, usernameLength);
if (usernameLength < 5 || usernameLength > 20) {
$("#usernameErrorMsg").show();
} else {
$("#usernameErrorMsg").hide();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Enter your name: <input id="username">
<span id="usernameErrorMsg">ERROR</span>
You need to get the length of input everytime the function checks it.
Currently you calculate the length only once.
$(document).ready(function(){
$("#usernameErrorMsg").hide();
$("#username").focusout(function(){
checkUser();
});
function checkUser(){
//calculate the length everytime in the function
var usernameLength = $("#username").val().length;
if(usernameLength < 5 || usernameLength > 20){
$("#usernameErrorMsg").show();
}
else{
$("#usernameErrorMsg").hide();
}
}
try this
$(document).ready(function(){
$("#usernameErrorMsg").hide();
$("#username").focusout(function(){
checkUser();
});
function checkUser(){
usernameLength = $("#username").length;
if(usernameLength < 5 || usernameLength > 20){
$("#usernameErrorMsg").show();
}
else{
$("#usernameErrorMsg").hide();
}
}
});

too much recursion error in jQuery when trigger the checkbox

I am trying to trigger the unchecked checkbox, so I tried lot with help of Google, still I can't find a solution,
Attempt 1:
jQuery(".checkbox").attr("checked", false).trigger("click");
When using attempt 1, no changes in my OP,
Attempt 2:
jQuery(".checkbox:checkbox").each(function() {
var code = jQuery(this).val();
var all_list = jQuery("#all_listings").val().split(",");
if (jQuery.inArray(code,all_list) >= 0) {
return false;
}
else {
jQuery(this).trigger("click");
}
});
using attempt 2 returns a error too much recursion
So how to avoid this error? or how to trigger the unchecked checkbox?
Thanks!
Solved:
problem solved with help of #praveen kumar and attempt 2 I changed the if else, now too much recursion solved.
jQuery(".checkbox:checkbox").each(function() {
var code = jQuery(this).val();
var all_list = jQuery("#all_listings").val().split(",");
if(jQuery.inArray(code,all_list) == -1){
jQuery(this).trigger("click");
}
}
You can completely change your Second Attempt to this way:
jQuery(".checkbox:checkbox:not(:checked)").trigger("click");
Hope this helps!
You need to use this way:
jQuery(".checkbox").filter(function () {
return (jQuery(this).prop("checked") == false);
}).trigger("click");
Or you can use:
jQuery(".checkbox").filter(function () {
return (this.checked == false);
}).trigger("click");
Or much simpler:
$('.checkbox:not(:checked)').trigger("click");

Unhide div using javascript object oriented

So i am having trouble unhiding a div, once it has been hidden.
The code:
First object
$('#filter_region').on('change', function(e) {
var temp_region_id = $('#filter_region').val();
filterRegionId($temp_region_id);
});
Seconds object:
function filterRegionId(temp_region_id)
{
if ($(temp_region_id) != 1) {
$('.showheadline').hide(); }
else { $('.showheadline').show(); }
}
Really what i want to do, is once the region is changed from the original, the div should be hidden - this works!
However, once the person goes back on the same region, the div is still hidden.
The filter_region echos from 1-8 depending on the region. I realise that i have set the region to 1, this is to test. However, even if the if-statement is set to 1, it still shows the divs when loaded, even if the region is 2-8. Hope this make any sense at all! Please feel free to ask if there are any questions regarding my explanation.
Best Regards,
Patrick
Try this, without the $(..) around the var
$('#filter_region').on('change', function(e) {
var temp_region_id = $('#filter_region').val();
filterRegionId(temp_region_id);
});
function filterRegionId(temp_region_id)
{
if (temp_region_id != 1) {
$('.showheadline').hide();
}
else {
$('.showheadline').show();
}
}
A text input's value attribute will always return a string. You need to parseInt the value to get an integer
var temp_region_id = parseInt($('#filter_region').val(),10);
and remove the $ from variable name filterRegionId($temp_region_id); and if ($(temp_region_id) != 1) {
$('#filter_region').on('change', function(e) {
var temp_region_id = parseInt($('#filter_region').val(),10);
///parse it to integer
filterRegionId(temp_region_id);
});
function filterRegionId(temp_region_id){
if (temp_region_id!= 1)
$('.showheadline').hide();
else
$('.showheadline').show();
}
The best solution is to rewrite you code a little.
Please add the filterRegion function on top and change the parametter name as follows
var temp_region_id = $('#filter_region').val();
filterRegionId(temp_region_id);
$('#filter_region').on('change', function(e) {
temp_region_id= $('#filter_region').val();
filterRegionId(temp_region_id);
});
function filterRegionId(temp_region_id)
{
if ($(temp_region_id) != 1) {
$('.showheadline').hide();
}
else {
$('.showheadline').show();
}
}

Using Blur and Submit events on the same form

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.

Categories