skip to Main Content

enter image description here

this is code in html :

<div class="col-9">
    <form>
        <div class="multiselect">
            <div class="selectBox" onclick="showCheckboxes()">
                <select>
                    <option placeholder="www"></option>
                </select>
                <div class="overSelect"></div>
            </div>
            <div id="checkboxes">
                @foreach ($subjects as $subject)
                <label for="itemform">
                    <input type="radio" value="{{ $subject->id }}"/>{{ $subject->name }}
                </label>
                @endforeach
            </div>


            @error('subjects')
            <small class="form-text text-danger">{{ $message }}</small>
            @enderror
        </div>
    </form>
</div>

and this is code in java script :

<script>

    var expanded = false;

    function showCheckboxes() {
        var checkboxes = document.getElementById("checkboxes");
        if (!expanded) {
            checkboxes.style.display = "block";
            expanded = true;
        } else {
            checkboxes.style.display = "none";
            expanded = false;
        }
    }
</script>

My question is how can I choose to select only one item from the list given that I used the type is radio

3

Answers


  1. Try this code,

    <input type="radio" name="itmname" value="{{ $subject->id }}" />{{ $subject->name }}
    

    use this script.

    function showCheckboxes() {
        var checkboxes = document.getElementsByName("itmname");
        var checkboxesContainer = document.getElementById("checkboxes");
        var expanded = checkboxesContainer.style.display !== "block";
    
        checkboxesContainer.style.display = expanded ? "block" : "none";
    
        if (expanded) {
            for (var i = 1; i < checkboxes.length; i++) {
                checkboxes[i].checked = false;
            }
        }
    }
    
    Login or Signup to reply.
  2. You need to use the "onclick" function in the HTML code.

    For example:

    <input type="radio" value="{{ $subject->id }}" onclick="showCheckboxes()" />{{ $subject->name }}
    

    This will allow the user to only select one radio button at a time. The function showCheckboxes() will ensure that only one box is checked.

    Hope this helps!

    Login or Signup to reply.
  3. @foreach ($subjects as $subject)
        <label for="{{$subject->id }}">
          <input type="radio" id="{{$subject->id }}" value="{{ $subject->id }}" />
                {{ $subject->name }}.   
       </label>
                                                            
    @endforeach
    

    Your label’s for attribute should be the same as your input’s ID attribute value.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search