I am working on javascript conditions.
If the field is empty I open an alert, else the function gets executed.
But I am trying to add another condition -- to verify the class of the field. If it is not in the page, or if it's empty, then directly execute the function/show an error.
How can I check with javascript if the class is in the page and if it's filled ?
$("#bouton").on("click", function(){
var warnning_message = 'warning message';
if(!$('.the-class').val()) {
alert(warnning_message);
}
else{
console.log('ok');
}
Seems hasclass will be useful
if($('.the-class').val()==='' && $('.the-class').hasClass('className')) {
alert(warnning_message);
}
You can check the existence of the class with $(".the-class").length > 0 code:
$("#botton").on( "click", function() {
var warnning_message = 'warning message';
if( $(".the-class").length > 0) {
alert(warnning_message);
}
else {
console.log('ok');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="botton" class="the-class">Click Here</div>
If you want to check whether an element with specific class exists or not use the following:
if ($(".the-class").length>0){
alert('Exists');
}
You could put ID to the field in order to select it and then do something like this:
if($( "#mydiv" ).hasClass( "the-class ))
console.log('has class');
else
console.log('no class');
Check the length of the array
if( $('.the-class').length == 0) {
alert(warnning_message);
}
else if (!$('.the-class').val()){
alert(warnning_message);
}
Related
Below is a sample structure from which i'm trying to get the specific value of custom attribute
<div id="123"></div>
<div id="456"></div>
<div context="james"></div>
Below is how i'm trying to fetch, but it always returns false.
if ( $('div').attr('context') == 'james' ) {
alert("yes");
} else {
alert("no");
}
The call to $('div').attr('context') will only grab the first div found in the DOM and check it's value. Since it doesn't have that attribute you get false. Instead you will want to iterate over all your div's and check each one. For example:
var found = false;
$('div').each(function( ) {
if($(this).attr('context') === 'james') found = true;
});
if(found) alert("yes");
else alert("no")
You could also use .filter:
if( $('div').filter(function(){ return $(this).attr('context') === 'james' }).length )
alert("yes");
else
alert("no");
Note: If you used data-context="james" you would use the .data() method rather than .attr().
Simply let jQuery do the filtering for you. Also, this can be done with plain old vanilla javascript pretty easily:
// Select by attribute
var theDiv = $("div[context='james']");
// If we have something here...
if(theDiv.length){
console.log(theDiv.text() );
} else {
console.log("Nope, not found.");
}
// We can use this same selector with plain javascript...
let theSameDiv = document.querySelector("div[context='james']");
// In this event, however, we access the text differently.
if(theSameDiv){
console.log("Found without jQuery!", theSameDiv.textContent);
} else {
console.log("Rats...");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="123">the first div</div>
<div id="456">div the second</div>
<div context="james">I'm 'Enry the Eighth, I Am!</div>
What i am trying to accomplish is to check weather a coupon code is applied on my application, and submit the form to apply the coupon if it has not been applied yet. However the console log continues to report null and not submit the form.
if(document.getElementById("#vapsummarycolcoupon").innerHTML== null) {
$( "#activatecoupon" ).submit();
} else {
return null;
}
}
When the form is submitted, the page will reload and have a new element with id="vapsummarycolcoupon" so to break from the page constantly submitting I have tried to check if the innerHTML != "$ 5.00" as well as == "undefined" and == null but with no luck. Something must be wrong, or there is a better way to accomplish this task. Thank you in advance.
By reversing the if statement, i was actually able to resolve the issue as well as check the length instead. Thanks for trying people, down voting cause you couldnt resolve the issue is sad.
$( window ).load(function() {
if($("#vapsummarycolcoupon").length > 0 ) {
return null;
} else{
$( "#activatecoupon" ).submit();
}
});
Try:
if($("#vapsummarycolcoupon").innerHTML== null) {
$( "#activatecoupon" ).submit();
} else {
return null;
}
Try this,
if (typeof(Storage) !== "undefined")
{
alert("Browser doesn't support Storage");
}
else
{
var X = document.getElementById("#vapsummarycolcoupon").innerHTML;
if(X == "")
{
if(sessionStorage.getItem("submit") != true)
{
sessionStorage.setItem("submit", true);
$( "#activatecoupon" ).submit();
}
else
{
console.log("Already Submitted");
}
}
else
{
return null;
}
}
I have a form with id commentform and if any logged in user visit the page a p tag gets generated under the form that with class logged-in-as. Now I am trying to check if that p exists and if not exists then do my validation which uses keyup(). Here is a small snippet...
$('form#commentform').keyup(function() {
if( ! $(this).has('p').hasClass('logged-in-as') ) {
....
} else {
......
}
}
});
Now the problem is that the if( ! $(this).has('p').hasClass('logged-in-as') ) is not returning me the expected result whether or not that specific p exists.
Can any of you guys tell me any other/better way to check this?
$('form#commentform').keyup(function() {
if($(this).find('p.logged-in-as').length == 1) {
....
} else {
......
}
}
});
You can do this to find it.
You can use
if ($('.logged-in-as', this).length)) {
But I would rather use a variable to store that state instead of relying on checking the presence of a raw tag : what if you change your HTML a little ?
Side note: Don't use overqualified selectors. $('#commentform') is faster and logically more consistent than $('form#commentform').
Check if an element witth class "xxx" exist
if( $( ".xxx" ).size() > 0 ) {
// EXISTS
}
Edit: forgot the dot ( ".xxx" )
My Scenerio:
I have a function:
The function Addprocedure() is called on onclick of Addprocedure button.
In this function i want to check if btnAddSelectedProcedures is clicked then do Something else do nothing
function Addprocedure(){
if()// Check if Button is clicked, button id = `btnAddSelectedProcedures`
{
//Do Something
}
else{
//Do nothing
}
}
Save the state of the button in a variable.
Define btnClicked globally as false. When btnAddSelectedProcedures is clicked, change btnClicked to true. When you call Addprocedure check if btnClicked variable is true and if so, that button has been clicked.
Example:
var btnClicked = false;
function Addprocedure() {
if (btnClicked) {
//Do something...
} else {
//Do something else...
}
}
$('BUTTON[name="btnAddSelectedProcedures"]').click(function() {
btnClicked = true;
});
$('BUTTON[name="Addprocedure"]').click(function() {
Addprocedure();
});
Try
$('#btnAddSelectedProcedures').click(function(){
$(this).data('clicked', true)
})
then
function Addprocedure(){
if($('#btnAddSelectedProcedures').data('clicked')){
//clicked
} else {
//not clicked
}
}
It is simple, check id
function Addprocedure(){
if(this.id === 'btnAddSelectedProcedures')// Check if Button is clicked, button id = `btnAddSelectedProcedures`
{
//Do Something
}
else{
//Do nothing
}
}
One possiblity,
You can declare a global variable and mark it as true when yourbtnAddSelectedProcedures clicked and use that to check in your Addprocedure() function.
var isButton1Clicked =false;
onButton1Click{
isButton1Clicked ==true
}
onButton2Click{
if(isButton1Clicked){
//procedd
}
}
I suggest to avoid using global var. Use a class instead ( or You can set data-* attribute as well )
$('#btnAddSelectedProcedures').on('click', function(){
//$(this).toggleClass('clicked');
if(! $(this).hasClass('clicked') ){ //allows you to set only once the class
$(this).addClass('clicked');
}
Addprocedure();
});
then
function Addprocedure(){
if( $("#btnAddSelectedProcedures").hasClass('clicked') ) //I guess you can call $(this) too
{
//Do Something
}
else{
//Do nothing
}
}
I used toggleClass because I think you want to check every time if the user clicked .
Use addClass in the other way.
<button id="1" onClick="Addprocedure(this.id)">B1</button>
and then
function Addprocedure(clicked_id)
{
alert(clicked_id);
}
I have a form which contains couple fields. Its very easy to validate this form. But when I'm using append or clone comand and add couple more fields in it dynamically I cannot validate the appended fields.
Here is the my code:
function addone(container, new_div) {
var to_copy = document.getElementById(new_div);
$(to_copy).clone(true).insertAfter(to_copy);
}
And because it doesn't matter which fields and I want all of them get field out I used class instead of id.
$(document).ready(function(){
$('#add_size').live('click', function(){
if($('.inp').val() == "") {
alert('Need to fill-out all fields')
}
else {
alert('Thanks')
}
})
})
Any idea? Thanks in advance.
$(document).ready(function(){
$('#add_size').live('click', function(){
if( ! checkvalid() ) {
alert('Need to fill-out all fields')
}
else {
alert('Thanks')
}
})
})
function checkvalid(){
var valid = true;
$('.inp').each(function(){
if (this.value == '') {
valid = false;
return;
}
})
return valid;
}
I see one thing that might cause you trouble...:
If you're only going to check fields for validity on submit, then I don't think you need the live handler. You're not adding fields with #add_size, you're adding .inp's. Just do your validations on click, and jQuery should find all the .inp class fields that are there at the time of the event:
$('#add_size').click(function(
$('.inp').each ...
)};
Or maybe I totally read the question wrong...