momori14 momori14 - 2 months ago 19
Twig Question

show checkbox value on textbox/label

I have a the following code which generated a list of data with radio button:

<div class="inline-radio">
{% for a in TimeInfo %}
<div class="row radio-row full-width no-padding">
<label class="radio-label-multiline font-weight-normal no-padding no-margin" for="slot_308395561">
<div class="columns small-1 width20 no-margin no-padding">
<input id="slot_308395561" name="form[slots]" required="required" value="" data-value="308395561" checked="checked" type="radio">
<div class="columns small-11 no-margin no-padding" id="slot_label_308395561"><span>{{ a.slotStartTime }} at {{ a.c.address}}</span></div></label></div>
{% endfor %}

I want to show the value of the selected checkbox in a label or textbox. I tried to use javascript but it didn't show the result.


You're setting all of your radio buttons' values to a blank string: value="". That doesn't make a lot of sense, especially since you want to show the selected radio button's value elsewhere.

Set their values to some property of a:

{% for a in TimeInfo %}
    // ...
    <input type="radio" ... value="{{ a.value }}" />
{% endfor %}

You were right in thinking to use JavaScript to display the selected value. I can't explain why it's not working (without seeing what you've tried), but the process for displaying the value of a selected radio button in some other element is (in plain JS):

// Find the selected radio button's value
var radioButtons = document.getElementsByName('form[slots]');
var value;

for (var i = 0; i < radioButtons.length; i++) {
    if (radioButtons[i].checked) {
        value = radioButtons[i].value;

// Now display var value in another element:

// Say we have a header tag with an id: <h2 id="selectedValue"></h2>
var headerElement = document.getElementById('selectedValue');
headerElement.innerHTML = value;

Of course, this will only execute once. To update the <h2> whenever a radio button is selected you'll need to listen for a change event on the radio buttons.

Or with jQuery:

$('input[name="form[slots]"]').on('change', function() {

One last logic error. You're setting every radio button to checked, however, only one radio button can be checked at a time.

{% for a in TimeInfo %}
    // ...
    <input type="radio" ... {% if a.someProperty %}checked{% endif %} /> // assuming a is a PHP object and someProperty is boolean
    // the presence of the checked attribute is the same as
    // checked="checked" == checked="true" == checked="ducks"
{% endfor %}