Return val() of selector from lodash filter method Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Return val() of selector from lodash filter method without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have the following code:

_.filter($('.date-field'), function(n) { return n.val() });

where n is supposed to be the selected elements:

<input class="date-field" id="return-date" placeholder="return date" type="text" value="xyz">

I want to get the value of each element with class .date-field but when I do n.val(). It returns error:

Uncaught TypeError: n.val() is not a function

What should I do?

Answer

_.filter is used for filtering a collection of N elements to another collection of N or less elements.

If you want to transform each item in a collection, you should use _.map:

var results = _.map($('.item'), function(item) {
  return item.value;
});
$('.result').text(JSON.stringify(results));
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="text" class="item" value="1"/>
  <input type="text" class="item" value="2"/>
  <input type="text" class="item" value="3"/>
</form>
<div class="result"></div>

jQuery also has a map function which you can use instead of lodash, if you like.

We are here to answer your question about Return val() of selector from lodash filter method - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji