skip to Main Content

I’ve seen many different variations of my question, but nothing specific to my use case. I am trying to create a form field with multiple checkboxes and have done so successfully. If I do something like…

$("#select_all_1").click(function() {

  count1++;

  count1 % 2 ? $firstFunction1() : $secondFunction1();
});

function $firstFunction1 ()  {$('#is_access_manager_department_choices input[type=checkbox]').prop('checked', true);}
function $secondFunction1 () {$('#is_access_manager_department_choices input[type=checkbox]').prop('checked', false);} 

This totally works and does what I want it to.

What I’m trying to do is a variation of this. I want to get a list of users, potentially as a hidden input and then when the user clicks on select user group, it will only selectively select ( add a checkmark) to those users that are on my hidden list….I don’t want to select all users…only the "hidden" ones.

I’ve seen array examples…but only for select all…I’ve found something like this…dynamic check/uncheck of checkboxes but again it does all. I’m thinking I need to create a hidden input with all of the checkboxes checked and then loop through and do a compare of my user list to the whole user list and then if it exists on my user list…check it…But just can’t seem to figure out how to piece it together.

Thanks in advance for any thoughts.

2

Answers


  1. Chosen as BEST ANSWER

    I ultimately pulled together a solution based on various solutions that I found. I ultimately used AJAX so that when a user clicks on the dropdown field, a URL is executed to populate the field in question.

    AJAX

        $(document).ready(function (){
        $("#id_project").change(function () {
          var url = $("#forms").attr("data-load-attendee-users-url");
          var projectId = $(this).val();
          var token = '{{csrf_token}}';
    
          $.ajax({
            headers: { "X-CSRFToken": token },
            url: url,
            data: {
              'project': projectId
            },
            success: function (data) {
              $("#id_attendees").html(data);
            }
          });
    
        });
    

    MY HTML..

    {% for user in all_users %}
    <div class="spacer318">
    {% if user in team_members %}
      <input type="checkbox" value="{{user.id}}" name="attendees"
      {% if user.id %}
        checked
      {% endif %}'>
      <div class="spacer320">
        {{ user.get_full_name }}
      </div>
      {% else %}
      <input type="checkbox" value="{{user.id}}" name="attendees"
      {% if user.id %}
      {% endif %}'>
      <div class="spacer320">
        {{ user.get_full_name }}
      </div>
      {% endif %}
    </div>
    {% endfor %}
     
    

    My View( Class Based )

    class ProjectMeetingMinutesLoadAttendeeUsersView(LoginRequiredMixin,View):
    
        def get(self, request):
            project_id = request.GET.get('project')
            all_users = User.objects.all().exclude(is_active="False").order_by('last_name','first_name').distinct()
            team_members = User.objects.filter(project_team_members=project_id)
            return render(request,'project_meeting_minutes_load_attendee_users.html', {'team_members': team_members, 'all_users': all_users })
    

  2. If I understand you correct and it is OK to submit the data using JavaScript this could be a solution. Instead of adding input elements/checkboxs to the form you can add data about the users when the form is submitted.

    By getting the form data in a FormData object you can then add more data to the object and send that in the end.

    const groups = {
      "1": ["User 1", "User 2"],
      "2": ["User 3", "User 4"]
    };
    
    document.forms.form01.addEventListener('submit', e => {
      e.preventDefault();
      let formData = new FormData(e.target);
      if(e.target.group.value){
        groups[e.target.group.value].forEach(user => {
          formData.append('users', user);
        });
      }
      // new requst object with form data
      let request = new Request('data:application/json,{"status":"OK"}', {
        method: "POST",
        body: formData
      });
      // see the body of the request
      request.text().then(text => console.log(text));
      // do the "submit" of the form to an endpoint
      // here I fake the endpoint with a data URI (see above)
      fetch(request).then(response => response.json()).then(json => {
        // do something after the POST
      });
    });
    <form name="form01">
      <select name="group">
        <option value="">Select a group</option>
        <option value="1">Group 1</option>
        <option value="2">Group 2</option>
      </select>
      <input type="submit"/>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search