0

How can I set the default value of an element by comparing the innerHTML to a variable?

This is the select box

<select name="added_by" class="form-item-added_by" required="" id="id_added_by">
  <option value="" selected="">---------</option>

  <option value="1">admin</option>

</select>

This is what I've tried, but nothing happens.

<script type = "text/javascript">
    $(document).ready(function(){
        {%for note in notes%}
     added_by = "{{note.added_by}}"
     $(".form-item-added_by").val(added_by).change();
     {%endfor%}
        });
    </script>
1
  • I feel like this is trying to mix a server side loop with client side logic. Commented Oct 30, 2018 at 19:18

1 Answer 1

1

That's not going to work because you're changing the select based on the value which in this case is 1, so the variable added_by is not going to match anything.

Try this

<script type = "text/javascript">
    $(document).ready(function(){
        {%for note in notes%}
     added_by = "{{note.added_by}}"
     $('.form-item-added_by').val(function(){
    return $('.form-item-added_by option').filter(function(){
                return $(this).text() === added_by;
           }).val();
});
     {%endfor%}
        });
    </script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.