cphill
cphill

Reputation: 5914

jQuery Passing Checked Input Text to Different Input

I am trying to pass the text in the list item for selected values in my list to a hidden field value on form submission, but I'm not sure of the best way to select and pass these values (emails) so they are captured with each form submission.

Provided are my form fields being interacted with:

<form action="/app/blog/create?_csrf={{csrfToken}}" method="post" enctype="multipart/form-data" id="blogSubmission">
<div class="member-tag-container">
    <ul class="list-group checked-list-box">
        <li class="list-group-item">
            <p><input type="checkbox" class="member-tag-checkbox" name="memberTag[0]" value="1">John Doe ([email protected])</p>
        </li>
        <li class="list-group-item">
            <p><input type="checkbox" class="member-tag-checkbox" name="memberTag[1]" value="2">Jane Doe ([email protected])</p>
        </li>
        <li class="list-group-item">
            <p><input type="checkbox" class="member-tag-checkbox" name="memberTag[2]" value="3"> ([email protected])</p>
        </li>
        <input type="hidden" class="member-tag-hidden" name="memberTagEmail">
    </ul>
</div>
<button type="submit" id="create-blog-button"></button>
</form>

Here is the jQuery:

$('#blogSubmission').submit(function(){
        var regExp = /\(([^)]+)\)/;
        var memberEmail = []
        $("input.member-tag-hidden:checked").each(function() {
            memberEmail.push(regExp.exec($(this).parent()))
        })
});

Here is what I'm looking to achieve:

Checked checkboxes = name="memberTag[0]", name="memberTag[2]"

Hidden field updated = <input type="hidden" class="member-tag-hidden" name="memberTagEmail" value="[email protected], [email protected]">

Upvotes: 0

Views: 28

Answers (1)

Chris Happy
Chris Happy

Reputation: 7295

If I understand you, I would

  • Grab the values
  • Add them to the hidden field

Code: (untested)

$('#blogSubmission').submit(function(){
        var regExp = /\(([^)]+)\)/;
        var memberEmail = []

        // Get all of the checkboxes checked
        $("input.member-tag-checkbox:checked").each(function() {
            var result = regExp.exec($(this).parent().text());
            if (typeof result[1] !== 'undefined') { // if has value
              memberEmail.push(result[1]);
            }
        })

        // Add to hidden
        $('.member-tag-hidden').val(memberEmail.join(', '));
});

Upvotes: 1

Related Questions