I need to keep input checkboxes selection when I open modal. But I don't know:
I have a list of checkboxes about users. When I select and press button to open modal I need to keep this selection to send an email, but every checkbox is unselected in the modal.
HTML:
<div>
<h4>LIST USERS</h4>
@foreach ($agent as $agent)
<ul class="user-select">
<li>
<h5>{{ $agent->name }}</h5>
<input type="checkbox" name="agents[]"/>
</li>
</ul>
@endforeach
<p>
<a href="#" class="button register-interest">Register interest</a
</p>
</div>
MODAL:
<div class="register-modal">
<div class="modal-box">
<div class="header">
<h3 class="text-black">Register your interest</h3>
<a href="#" title="Close" class="close-modal">X</a>
</div>
<div class="content">
<h5>Select Agents</h5>
<form>
@foreach ($agents as $agent)
<ul class="agents-select">
<li>
<h5>{{ $user->name }}</h5>
<input type="checkbox" name="agents[]"/>
</li>
</ul>
@endforeach
<input type="text" name="name"/>
<input type="email" name="email"/>
<textarea name="comments"></textarea>
<button type="submit" name="register">SEND</button>
</form>
</div>
</div>
</div>
jQuery:
$('.register-interest').on('click', function(e) {
e.preventDefault();
$('.register-modal').show();
});
$('.register-modal a.close-modal').on('click', function(e) {
e.preventDefault();
$('.register-modal').hide();
});
How can save input selection and keep when I open modal?
SCREENSHOT ERROR
I suggest you to loop through the first list, then to copy its items' statut to the second list.
Use jQuery#eq
to find the corresponding looped <input>
and jQuery#prop
to get if it is checked or not:
$('.register-interest').on('click', function(e) {
e.preventDefault();
$('.user-select input').each((i, input) => {
$('.agents-select input').eq(i).prop('checked', $(input).prop('checked'));
});
$('.register-modal').show();
});
Working example:
$('#show-modal').on('click', () => {
$('#checklist input').each((i, input) => {
$('#modal input').eq(i).prop('checked', $(input).prop('checked'));
});
$('#modal').show();
});
$('#hide-modal').on('click', () => {
$('#modal').hide();
});
#modal {
display: none;
border: 1px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="checklist">
<li>
<span>User 1</span>
<input type="checkbox" name="user[]">
</li>
<li>
<span>User 2</span>
<input type="checkbox" name="user[]">
</li>
<li>
<span>User 3</span>
<input type="checkbox" name="user[]">
</li>
</ul>
<button id="show-modal">Show modal</button>
<ul id="modal">
<li>
<span>User 1</span>
<input type="checkbox" name="user[]">
</li>
<li>
<span>User 2</span>
<input type="checkbox" name="user[]">
</li>
<li>
<span>User 3</span>
<input type="checkbox" name="user[]">
</li>
<li>
<button id="hide-modal">Hide modal</button>
</li>
</ul>