Search code examples
javascriptdjangomultichoiceitems

How to select a MultipleChoice option based on text variable


I have a MultipleChoiceField and a variable my_choice = 'mystring'

I want check the option relative to my_choice

Here my html:

    ul id="id_layer_select"><li><label for="id_layer_select_0"><input checked="checked" id="id_layer_select_0" name="layer_select" type="checkbox" value="1" /> <span style='font-weight:normal'>Mychoice1</span></label></li>
<li><label for="id_layer_select_1"><input id="id_layer_select_1" name="layer_select" type="checkbox" value="2" /> <span style='font-weight:normal'>Mychoice2</span></label></li>
<li><label for="id_layer_select_2"><input id="id_layer_select_2" name="layer_select" type="checkbox" value="3" /> <span style='font-weight:normal'>Mychoice3</span></label></li> [...]</ul>

here my javascript:

var my_choice = 'mystring'
var opt = $("#id_layer_select option");
opt.filter("[value=my_choice]").attr("selected", true);

I can use jquery. Thank you

PS: Off course mystring is an option Mychoice1 or Mychoice2 or etc.

I don't want use the id_layer_select_x and I prefer to not add and attribute.

The problem is that the checkbox stay unchecked and

console.log(opt)=Object { length: 0, prevObject: Object[1] }

Solution

  • You can filter all spans by the text they contain. You can then get the previous element and have it checked.

    $(document).ready(function() {
      var txt = "Mychoice3";
      
      
      var labelMatchingTxt = $('#id_layer_select span').filter(function(i, el) {
        return txt === el.childNodes[0].nodeValue; // avoiding DOM reselection.
      }).prev().prop('checked', true);
    });
    <head><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></head>
    
    <body>
    
    <ul id="id_layer_select"><li><label for="id_layer_select_0"><input id="id_layer_select_0" name="layer_select" type="checkbox" value="1" /> <span style='font-weight:normal'>Mychoice1</span></label></li>
    <li><label for="id_layer_select_1"><input id="id_layer_select_1" name="layer_select" type="checkbox" value="2" /> <span style='font-weight:normal'>Mychoice2</span></label></li>
    <li><label for="id_layer_select_2"><input id="id_layer_select_2" name="layer_select" type="checkbox" value="3" /> <span style='font-weight:normal'>Mychoice3</span></label></li> [...]</ul>
    </body>