How do I get the values of classes in jQuery?

console.log($('.package_ids').val());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="package_ids[]" name="package_ids[]" value="6" />
<input type="hidden" class="package_ids[]" name="package_ids[]" value="775" />
<input type="hidden" class="package_ids[]" name="package_ids[]" value="7207" />

I’m getting the right results when submitting this as a form. But when I get the value using jQuery I’m getting undefined.

I’m hoping to get something like an array [6, 775, 7207].

46 thoughts on “How do I get the values of classes in jQuery?”

  1. package_ids[] cannot be a class name. To get the expected array, you can use .map as follows:

    const arr = $('.package_ids').map((i,elem) => +$(elem).val()).get();
    console.log(arr);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <input type="hidden" class="package_ids" name="package_ids[]" value="6"/>
    <input type="hidden" class="package_ids" name="package_ids[]" value="775"/>
    <input type="hidden" class="package_ids" name="package_ids[]" value="7207"/>
    Reply
  2. You could select the items with their name property, e.g.:

    let values = [];
    $('[name="package_ids[]"]').each(function (i, v) {
      values.push($(v).val());
    });
    console.log(values);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="hidden" class="package_ids[]" name="package_ids[]" value="6" />
    <input type="hidden" class="package_ids[]" name="package_ids[]" value="775" />
    <input type="hidden" class="package_ids[]" name="package_ids[]" value="7207" />
    Reply
  3. You can do it like this:

    var results = $('input[name="package_ids[]"]').map(function(index, element){
        return $(element).val();
    }).get(); // ["6", "775", "7207"]
    
    Reply

Leave a Comment