Alan Coromano
Alan Coromano

Reputation: 26008

Unable to return value from a function

I want to return value from the function which contains an anonymous function.

function getSingleCheckedItemId() {
    return $(".data-table-chk-item").each(function() {
      if ($(this).is(":checked")) {
          var value = $(this).attr("value");
          return value;
      }
    });
  }

In this case it returns me the array of all checkboxes. If I remove the first return, it won't return a value but undefined.

So how do I return the value from getSingleCheckedItemId()?

Upvotes: 1

Views: 113

Answers (3)

HeremansY
HeremansY

Reputation: 43

I would do it like this

function getSingleCheckedItemId() {
    var ret;
    $(".data-table-chk-item").each(function() {
        if ($(this).is(":checked")) {
            ret = $(this).attr("value");
        }
    });
    return ret;
}

Upvotes: 1

Fabrício Matté
Fabrício Matté

Reputation: 70139

.each always returns the jQuery object containing all elements that you iterated over so:

function getSingleCheckedItemId() {
    var ret;
    $(".data-table-chk-item").each(function() {
      if ($(this).is(":checked")) {
          ret = $(this).attr("value");
          return false; //breaks out of .each
      }
    });
    return ret;
}

Also, this.value is usually a better option than $(this).attr('value') in case you're dealing with form inputs - seems like you have radio/checkbox inputs due to their checked property. Also, this.checked returns a boolean so there's no need for $(this).is(':checked') either.


I believe your logic can be simplified to:

function getSingleCheckedItemId() {
    return $(".data-table-chk-item:checked").val();
}

This way .val() will return the value of the first :checked item or undefined if no elements are matched by the selector, which does the same as the loop above.

Upvotes: 5

oriolparra
oriolparra

Reputation: 222

You can do it:

function getSingelCheckedItemId() {
    var elements = $(".data-table-chk-item:checked");
    return (elements.length > 0) ? $(elements[0]).val() : undefined;
}

Upvotes: 2

Related Questions