James Parsons
James Parsons

Reputation: 925

How to find the closest div by ID and then find the ID's of all forms inside that div

I am looking to to find the closest div with an class of 'form_wrap' to the button when clicked and then find the ID's of all forms inside that div.

The forms sit as part of two Laravel foreach loops and have been given individual dynamic ID numbers. These ID numbers need to be collected and then submitted.

<div class="form_wrap">  
    @foreach ($workouts as $workout)
         <?php $formid="form_".$x."_".$f;?>
         {!! Form::open(array('route' => 'workoutshared.store', 'method' => 'POST', 'ID' => $formid)) !!}
         {{ csrf_field() }}
         {{ Form::hidden('user_id', Auth::user()->id)}}
         {{ Form::hidden('date', $entry)}}
         {{ Form::hidden('weight', $workout->weight)}}
         {{ Form::hidden('exercise', $workout->exercise)}}
         {{ Form::hidden('reps', $workout->reps)}}
         {{ Form::hidden('sets', $workout->sets)}}
         <button id="submit" class="btn btn-default">Share</button>               
         {{ Form::checkbox('share', null, array('class' => 'form-control', 'required' => ''))}}
         {!! Form::close() !!}     
         <tr>
               <th>{{$workout->exercise}}</th>
               <td>{{$workout->weight}}</td>
               <td>{{$workout->reps}}</td>
               <td>{{$workout->sets}}</td>
         </tr>
    <?php $f++; endforeach;?>
 </div>

Upvotes: 1

Views: 948

Answers (2)

random_user_name
random_user_name

Reputation: 26160

There are many details you've left out, so the answers may need to be modified to match.

For example - do you want to allow the form submission? Intercept it? Or do you care?

Another point is - what do you want to do with the ID's once you have them?

This code will do what you've asked. It uses event delegation, so you should be able to load it in your <head>, and it will still work as requested.

// Bind to the click event of all form buttons
$(document).on('click', 'form button', function() {
    // Find the closest div
    var wrap = $(this).closest('div.form_wrap');

    // Then, find all form ID's inside of the div:
    wrap.find('form').each(function() {
        var id = $(this).prop('id');
    });
});

What you do with those ID's is up to you, but there's several options, depending on your needs.

Upvotes: 1

Mehrad
Mehrad

Reputation: 1543

I think you want $( "[id^='form_']" ) which finds any ID that starts with "form_" although using a class is a better option when trying to find more than one element on a page.

var formWrap = $( "#SomeSpecificID" ).parent();
var formsInsideThatID = formWrap.children().attr('id');

Upvotes: 1

Related Questions