Working with a checkbox array

0

Well, here's what I'm trying to do is edit a record that contains only one name and an array of other records, ifs (a 1-to-N relationship). This array of ifs I play in the view as checkboxes, but I'm not able to get it checked.

I'm using vues. I wanted, when I clicked edit, to have checked the states he already has.

    
asked by anonymous 25.10.2017 / 00:13

1 answer

0

When you click "Edit", you get a code in JSON format:

{ "idnomes": 15, "strnome": "JOSIVAN SOUSA", "has_uf": [ { "iduf": 1, "struf": "AC", "strdescricao": "Acre", "bolvisualizar": 1 }, { "iduf": 2, "struf": "PA", "strdescricao": "Para", "bolvisualizar": 1 }, { "iduf": 2, "struf": "MA", "strdescricao": "Maranhão", "bolvisualizar": 1 } ] }

Now you need to make a parse in this code by turning it into a JSON object:

objeto = JSON.parse('{ "idnomes": 15, "strnome": "JOSIVAN SOUSA", "has_uf": [ { "iduf": 1, "struf": "AC", "strdescricao": "Acre", "bolvisualizar": 1 }, { "iduf": 2, "struf": "PA", "strdescricao": "Para", "bolvisualizar": 1 }, { "iduf": 2, "struf": "MA", "strdescricao": "Maranhão", "bolvisualizar": 1 } ] }');

Then get all the checkbox that has modal (change "meumodal" to id of your modal):

elems = document.getElementById("meumodal").getElementsByTagName("input");

Then a double loop will check the checkbox that has value equal to the acronym in JSON:

for(x=0;x<objeto.has_uf.length;x++){
    for(y=0;y<elems.length;y++){
        if(elems[y].value == objeto.has_uf[x].struf){
            elems[y].checked = true;
        }
    }
}

Open the example below:

objeto = JSON.parse('{ "idnomes": 15, "strnome": "JOSIVAN SOUSA", "has_uf": [ { "iduf": 1, "struf": "AC", "strdescricao": "Acre", "bolvisualizar": 1 }, { "iduf": 2, "struf": "PA", "strdescricao": "Para", "bolvisualizar": 1 }, { "iduf": 2, "struf": "MA", "strdescricao": "Maranhão", "bolvisualizar": 1 } ] }');
elems = document.getElementById("meumodal").getElementsByTagName("input");
for(x=0;x<objeto.has_uf.length;x++){
	for(y=0;y<elems.length;y++){
		if(elems[y].value == objeto.has_uf[x].struf){
			elems[y].checked = true;
		}
	}
}
<div id="meumodal">
	<input type="checkbox" value="AC" /> AC
    <br />
	<input type="checkbox" value="DF" /> DF
    <br />
	<input type="checkbox" value="MA" /> AC
</div>
    
25.10.2017 / 01:32