Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to improve my codes to implement 'return false'?

I am trying to return false after a conditional statement fail.

I have

$('#btn').click(function() {
    $('.title').each(function() {
        if (id == $(this).attr('id')) {
            alert('The name already exists.')
            return false; //I hope my codes would stop here if condition is true
        }
    })
    // my codes still call the doSomething function even if the conditional         
    //statement is true
    doSomething();
})​

I want do call the doSomething function ONLY if id != $(this).attr('id).

The codes below gave me what I want but it seems ugly.

$('#btn').click(function() {
    var nameExist = false
    $('.title').each(function() {
        if (id == $(this).attr('id')) {
            alert('The name already exists.')
            nameExist = true;
            return false; //I hope my codes would stop here if condition is true
        }
    })
    if (!nameExist) {
        doSomething();
    }
})​

Anyone has a better approach for this? Thanks a lot!

like image 572
FlyingCat Avatar asked Jun 04 '26 18:06

FlyingCat


1 Answers

Switch to a basic for loop.

$('#btn').click(function() {
    var elements = $(".title");
    for (var i = 0; i < elements.length; i++) {
        if (id == elements[i].id) {
            alert('The name already exists.')
            return false; //I hope my codes would stop here if condition is true
        }
    }

    doSomething();
})​
like image 168
Kevin B Avatar answered Jun 06 '26 08:06

Kevin B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!