Home > Enterprise >  How to check the checkboxes based on the input field value
How to check the checkboxes based on the input field value

Time:02-26

Like 1,2 or one, two checks the first and second boxes.

I need a solution using Javascript or JQuery

<input type="text" id="select" value="1,2" placeholder="type any thing">

<button id=submit> click </button>

<table>

    <thead>
        <tr>
            <th> </th>
            <th> Name </th>
            <th> ph </th>
            <th> email </th>
            <th> reg no </th>
        </tr>
    </thead>

    <tbody>
        @foreach ($studentlist as $list)
            <tr>
                <!-- THE CHECKBOXES -->
                <td>
                    <div >

                        <input type="checkbox" value="{{ $list->studentid }}" name="checkbox[]"
                            id="checkbox-in-{{ $list->studentid }}">

                        <label for="checkbox-in-{{ $list->studentid }}"></label>

                    </div>
                </td>
                <td> {{ $list->studenName }} </td>
                <td> {{ $list->studentphnuumber }} </td>
                <td> {{ $list->email }} </td>
                <td> {{ $list->Regno }} </td>
            </tr>
        @endforeach
    </tbody>

</table>

CodePudding user response:

const controlInput = document.querySelector("#select");
const checkboxes = document.querySelectorAll("input[type=checkbox]");

// Initial check
check(controlInput);

// Check on update
controlInput.addEventListener("keyup", (e) => {
    check(e.target);
});

/**
 * @param {HTMLInputElement} controlInput
 */
function check(controlInput) {
    input = cleanInput(controlInput.value);

    const targetCheboxesIds = input.split(",");

    checkboxes.forEach((box) => {
        if (targetCheboxesIds.includes(box.id)) {
            box.checked = true;
        } else {
            box.checked = false;
        }
    });

    controlInput.value = input;
}

/**
 * @param {string} input
 */
function cleanInput(input) {
    // Removing white space and letters
    return input.replaceAll(/\s /g, "").replaceAll(/[a-zA-Z]/g, "");
}
<label>Students</label>
<input type="text"  id="select" placeholder="type any thing" value=",3,5">

<div>
  <label for="checkbox1"> 1 </label>
  <input type="checkbox" name="checkbox1" id="1">
</div>

<div>
  <label for="checkbox2"> 2 </label>
  <input type="checkbox" name="checkbox2" id="2">
</div>

<div>
  <label for="checkbox3"> 3 </label>
  <input type="checkbox" name="checkbox3" id="3">
</div>

<div>
  <label for="checkbox4"> 4 </label>
  <input type="checkbox" name="checkbox4" id="4">
</div>

<div>
  <label for="checkbox5"> 5 </label>
  <input type="checkbox" name="checkbox5" id="5">
</div>

  • Related