How to alert once in a JavaScript loop - javascript

code : In the below code shown, the alert message keeps on looping till the end of the statement.I need a alert statement to alert only once.How to achieve this?
Here it is checking the output of a checkbox if its not selected it shows undefined
for(j=1;j<=numOflimit;j++)
{
var select = $("input[name=select+j]:checked").val();
//alert (select);
//$check='undefined';
if(select==undefined)
{
alert ("Please select atleast one product");
}
else
{
var postData = $("form").serialize();//"product_name="+product_name+"&barcode="+barcode+"&Quantity"+Quantity;
$.ajax
({
type: 'POST',
url: 'http://localhost/example/index.php/castoutput',
data: postData,
success: function(html) {
// alert(html);
$('#cast2').html(html);
}
});
}
}

You could make a variable which is either true or false, if the alert has been triggered once put it on false & check with an if, if its true or false.
if (showAlert==true)
{
alert ("Please select atleast one product");
showAlert = false;
}

You're using a string instead of a concatenation here:
$("input[name=select+j]:checked").val();
You need to place j outside of the quotes:
$("input[name=select"+j+"]:checked").val();
Otherwise it is always undefined.
Just curious, by the way, why do you need to loop here anyway?

There is absolutely no reason what-so-ever to loop over input elements to determine if any of them are checked. Since you're already using the :checked selector, simply check the length of the matched set of elements - it's very simple:
var $checked = $("input[type='checkbox']:checked");
// If none of the checkboxes are checked, alert to the user
if ( !$checked.length ) {
alert("Please select atleast one product");
} else {
// do ajax post stuff here.
}

try this
if(typeof(select)=='undefined')
and if you will need to alert once - use yours j counter
if (j==1) {alert('')}

As far as I can tell, you don't want to do the else statement either, so there's no use of letting the for loop run. Simply use:
if(select==undefined)
{
alert ("Please select atleast one product");
j = numOflimit+1;
}

did you try just having it exit the for loop to another function that throws an error if it equals undefined since it looks like your just trying to submit the form. So just make it exit on undefined to a function that throws an alert saying whatever you like.

Related

jQuery check if exists using empty element

Is it possible to check if an element exists in jQuery using the length function, even though the element is empty?
I have an empty div <div id="myDiv"></div> that gets populated by AJAX when the user scrolls to a certain point on the screen, but when I try targeting the div before that point I'm getting nothing. The code I'm using is…
if( jQuery('#myDiv').length) {
alert('#myDiv exists!');
} else {
alert('#myDiv doesn\'t exist!');
}
but I'm wondering if the reason it isn't selecting the div is because it's empty. Does that matter when using the length function?
.length is not a method. It is a property, so remove the () after it.
if( jQuery('#myDiv').length ) {
// If the div exists do this
} else {
// If it doesn't do this
}
length is a `property` and not a `function`. It should be
if( jQuery('#myDiv').length) {
alert('#myDiv exists!');
} else {
alert('#myDiv doesn\'t exist!');
}
It should be the below codes assuming you want to check whether the div is empty or not
if( jQuery('#myDiv').html().length > 0){
// If the div is empty do this
}
else{
// If its not empty do this
}
Check the jQuery DOCS
EDIT:
Check if you have used the if condition inside document ready. Check out the fiddle
jQuery('#myDiv').html().length > 0
Here is the Fiddle Link

Swapping classes when input is not valid, jquery

Im only starting to learn jquery, trying to validate my html forms.
I want inputs to be red when there is no string so I set all inputs under class= "valid" to start and when empty field being submitted I want jquery to swap valid class to not_valid.
I manage to do that part but I need those classes back to normal when form is re-submitted.
Can anyone please help me? thx
$('.submit_signup').click(function(){
var abort = false;
$('not_valid').remove();
$(':input[required]').each(function(){
if($(this).val()===''){
$(this).removeClass('valid').addClass('not_valid');
abort = true;
}
});
if(abort){
return false;
}else{
return true;
}
});
Unless I misunderstand, you can just add an else to your if, and replace not-valid with valid if the field isn't empty.
Pretty simple!
$('.submit_signup').click(function(){
var abort = false;
// do not forget the dot for classes
$('.not_valid').removeClass('not_valid');
// check inputs
$(':input[required]').each(function(){
if($(this).val()===''){
$(this).removeClass('valid').addClass('not_valid');
abort = true;
}
});
// ! means not
return !abort;
});

javascript onChange computation - show only one alert

I didnt know how to properly name my question, but here goes.
In my html i have a "form" but not
<form></form>
.It is just a couple of selects, radio buttons and text inputs.
I enter, check and select values and according to these values, some computation is done. This "form" is computing on every keydown, blur, change. So when I change one value it will immediately recalculate the results with new value.
I would like to alert the user, when he didnt fill any of the necessary inputs. Here is how it works now (this is in a separate .js file)
function calculator() {
// Here is code that gathers the data from html
// and here are also some computations (many if-s)
// The code is too long to be putted here
}
$(function () {
$('select, input').on('keydown blur change', calculator);
});
I tried to put a if statement inside of my calculator function:
function calculator() {
// Here is code that gathers the data from html
// and here are also some computations (many if-s)
// The code is too long to be putted here
if (val1 == '' && sadzba == '' && viem == '' && ...) {
alert('You have to fill all necessary fields!')
}
}
This obviously caused, that the alert was popped every time I enter / choose new value, because at the beginning all variables are empty / with no value.
So how can I achieve, this situation: User fills in the "form" except of (for example)one value and only then will the alert pop up.
Than you.
I suggest to do the check on submit and return false if one of the fields is empty, preventing the form to be submitted.
$('form').on('submit', function () {
if (val1 == '' || sadzba == '' || viem == '') {
alert('You have to fill all necessary fields!');
return false;
} else { return true; }
});
Use a different event handler for the onblur event since that's when the cursor has left the input box. (It also prevents the event handler from firing all the time. That's a pretty expensive process and it can slow your page down)
$('select, input').on('blur', didTheyLeaveTheFieldEmpty);
Hope I understood you right, you can try this:
function calculator(event) {
if ( $(event.target).val().length == 0 ) {
alert('fill the field');
}
}
$('select, input').on('keyup', calculator);
even if you don't want a form with a submit buton you can create a button
and trigger your code on it's click
<input type="button" class="calculate">
$(function () {
$('.calculate').on('click', calculator);
});

Inline edit html table with ajax php checkbox & select

Final Edit: I abandoned trying to get checkboxes to work with this method. Instead, I'm just using a combo box with a 'Yes' and 'No'. Combos are working perfectly, thanks to some fantastic help from SE users :) It actually turns out to be better, IMO. Checkboxes with inline editing, the way I've implemented it could lead to accidentally checked or unchecked boxes. A combo is an extra 2 clicks but it's worth it to eliminate accidents. It also looks great because I'm just swapping a little red 'x' or green 'check' to indicate on and off. It looks really nice. Thanks again to everyone for your help!
I'm using the method from 9lessons.info to create a table with inline-editable rows. So far, it's working but not very well when it comes to selects and checkboxes. With selects, it does update the value, but when it hides the input (when clicking outside the tr) the value of the select shows (the fk id field), rather than the text in between opening and closing of the selected option tag (the name field). I can see in the jQuery where it shows the value, but how do I tell it to use the text from the option instead of the value?
the jQuery:
$(document).ready(function(){
$(".edit_tr").click(function(){
var ID=$(this).attr('id');
// hide
$("#name_"+ID).hide();
$("#position_"+ID).hide();
$("#parent_nav_"+ID).hide();
$("#is_disp_"+ID).hide();
// show
$("#name_input_"+ID).show();
$("#position_input_"+ID).show();
$("#parent_nav_input_"+ID).show();
$("#is_disp_input_"+ID).show();
}).change(function(){
var ID=$(this).attr('id');
var name=$("#name_input_"+ID).val();
var position=$("#position_input_"+ID).val();
var parent_nav = $("#parent_nav_input_"+ID).val();
var is_disp = $("#is_disp_"+ID).prop("checked") ? 1 : 0;
// data string
var dataString = 'id='+ ID +'&name='+name+'&position='+position+'&parent_nav='+parent_nav+'&is_disp='+is_disp;
if(name.length > 0 && position.length > 0 && parent_nav.length > 0) {
var parent_nav_txt = $("#parent_nav_input_"+ID+" option:selected").text();
$.ajax({
type: "POST",
url: "admin_nav_edit.php",
data: dataString,
cache: false,
success: function(html) {
$("#name_"+ID).html(name);
$("#position_"+ID).html(position);
$("#parent_nav_"+ID).html(parent_nav_txt);
$("#is_disp_"+ID).html(is_disp);
}
});
} else {
alert('Enter something.');
}
});
//edit input box click action
$(".editbox").mouseup(function(){
return false
});
//outsire click action
$(document).mouseup(function() {
$(".editbox").hide();
$(".text").show();
});
});
I know the 'is_disp' variables in script are not retrieving the right thing, but everything else works so I don't think I need to post the rest of my code, but I will if necessary.
So, what should I put to get it to recognize the checkbox is unchecked, and make sure a 0 gets sent to the db, or a 1 if checked? That's how I've been doing it
With the select, I'm not sure what do to, or how to target the value in between the select tags to show instead of the value="" value, while making sure the value="" value gets stored in the db.
Thanks very much for any help!
to get a select boxes option's text use the :selected selector along with .text()
var text = $("#selectID option:selected").text();
var value = $("#selectID option:selected").val();
for checkbox check the return of .prop("checked")
var check = $("#checkboxID").prop("checked") ? 1: 0;
EDIT:
var parent_nav_text = $("#parent_nav_input_"+ID+" option:selected").text();
Then in your ajax function
$.ajax({
type: "POST",
url: "admin_nav_edit.php",
data: dataString,
cache: false,
success: function(html) {
$("#name_"+ID).html(name);
$("#position_"+ID).html(position);
$("#parent_nav_"+ID).html(parent_nav_text);
$("#is_disp_"+ID).html(is_disp);
}
});
A call to .val() on a checkbox will always return the value it is set with in the DOM. You should instead do this:
var is_disp = $("#is_disp_input_"+ID).is(':checked');
the .is() jQuery function returns true if the element has the CSS selector, in this case :checked.
Also, on the server, you should check if the checkbox variable is true or false using if(!empty($_POST['myvar'])) {} instead of if(isset($_POST['myvar'])) {} because isset() will return true even if myvar is zero or false!

If is a checkbox Checked do

i have an issue.
I'm trying avoid the user leaves the page if theres any element checked.
For instance, i have several checkboxes with a class named "testCheckbox" and i tried that:
window.onbeforeunload = function(){
if($('.testCheckbox').attr('checked'))
return 'yes';
else
return 'no';}}
But it always is says 'yes' when the first checkbox (in order of appear) is checked, if i check the second or the third, etc, says 'no'.
You can use checked-selector along with with is
if ($('.testCheckbox').is(':checked'))
if ($('.testCheckbox:checked').length)
your probably wanting to do something like this
window.onbeforeunload = function()
{
var yesno = 'no';
$('.testCheckbox').each(function(index,value){
if($(value).attr('checked'))
{
yesno = 'yes';
return false;
}
});
return yesno;
}

Categories

Resources