Nerdicon Nerdicon - 1 month ago 15
Twig Question

Getting coordinates upon checking a checkbox

so I'm doing this school thingy and I'm trying to get the x and y coordinates of looped checkboxes when they are checked and display the X and Y coordinates in their respective input box, and I need help because at this point I don't really know what I'm doing.

html.twig.

{% set cells = 10 %}
<div class="large-12">
<div class="large-6 columns">
<h6>Your Board</h6>
<table id="yours" class="ocean">
{% for i in 1..cells %}
<tr class="rowDiv">
{% for j in 1..cells %}
<td id="{{i}}col_{{j}}" rel="{{j}}" class="cell colDiv
{% for placement in yourships %}
{% for cell in placement %}
{% if cell.x_pos == i and cell.y_pos == j %}
{% if cell.hit == "hit" %}
hit
{% else %}
{{cell.class}}
{% endif %}
{% endif %}
{% endfor %}
{% endfor %}
">
<input class="pos-input" name="position" type="checkbox" value="{{j}}"/>
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<div class="large-12">
<div class="large-3 columns">
Y:<input type="text"/>
</div>
<div class="large-3 columns">
x:<input type="text"/>
</div>
<div class="large-3 columns">
<select>
<option>select</option>
<option>hit</option>
<option>miss</option>
</select>
</div>
<div class="large-3 columns">
<button>Initiate</button>
</div>
</div>
</div>
<script>
$('.chooser').click(function(){
$(this).removeClass('invisible');
var innerCheck = $(this).find('input[type=checkbox]')
innerCheck.prop('checked', true);

});
</script>

Answer

$(function() {
    $('.pos-input').on('click', function() {
         if ($(this).is(':checked')) alert( $(this).data('x')+':'+ $(this).data('y') );
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
{% set cells = 10 %}
....
{% for i in 1..cells %}
            <tr id="{{i}}" class="rowDiv">
                {% for j in 1..cells %}
                    <td id="{{i}}col_{{j}}" rel="{{j}}" class="cell colDiv chooser invisible 
                         {% for placement in yourships %}
                            {% for cell in placement %}
                                {% if cell.x_pos == i and cell.y_pos == j %}
                                        hit
                                {% else %}  
                                        no-ship      
                                {% endif %}
                            {% endfor %}
                        {% endfor %}                              
                        ">
                        <input class="pos-input" name="position" type="checkbox" data-x="{{ j }}" data-y="{{ i }}" />  
                    </td>
                {% endfor %}    
            </tr>
{% endfor %}