Search code examples
phpjquerycheckboxexplodechecked

PHP prechecked check boxes from a String


Hello
I would like to tell you that I know there are lots of solved example on stack overflow regarding the same issues.But mine is different and complex.

I have Php Variable that has comma separated values like "car_ferrari,car_jaguar,car_lamborghini" and I have multiple check-boxes
enter image description here     name='car [ ] '      value = ' car_ferrari '   
enter image description here     name='car [ ] '      value = ' car_lamborghini '   
enter image description here     name='car [ ] '      value = ' car_hummer '   
enter image description here     name='car [ ] '      value = ' car_jaguar '   
enter image description here     name='car [ ] '      value = ' car_aston '   

I want to checked the checbox if this variable has the same value of string.
Like checkbox with the value of car_ferrari,car_jaguar,car_lamborghini should be checked
I have large number of these types of variables as well as large number of checkboxes array.I know I can use explode and then in_array() but it is really time consuming to put condition in for each and every checkbox for around 400 checkboxes.

if Jquery will help to sort it out ,I will use it but give me the appropriate answer.Ask me incase of query.
Thanks in advance.


Solution

  • I created a JSFiddle that demonstrates how to split the string by comma and then iterating and selecting the checkboxes with the corresponding value.

    Pure JS Solution

    var myString = "car_ferrari,car_jaguar,car_lamborghini";
    
    var selectedCarArray = myString.split(",");
    
    selectedCarArray.forEach(function(element) {
        document.getElementById('checkbox_' + element).checked = true;
    });
    <input type="checkbox" name="car[]" value="car_ferrari" id="checkbox_car_ferrari" />
    <input type="checkbox" name="car[]" value="car_lamborghini" id="checkbox_car_lamborghini" />
    <input type="checkbox" name="car[]" value="car_hummer" id="checkbox_car_hummer" />
    <input type="checkbox" name="car[]" value="car_jaguar" id="checkbox_car_jaguar" />
    <input type="checkbox" name="car[]" value="car_aston" id="checkbox_car_aston" />

    jQuery Solution

    var myString = "car_ferrari,car_jaguar,car_lamborghini";
    
    var selectedCarArray = myString.split(",");
    
    selectedCarArray.forEach(function(element) {
        $('input[value="' + element + '"]').prop('checked', true);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="checkbox" name="car[]" value="car_ferrari" />
    <input type="checkbox" name="car[]" value="car_lamborghini" />
    <input type="checkbox" name="car[]" value="car_hummer" />
    <input type="checkbox" name="car[]" value="car_jaguar" />
    <input type="checkbox" name="car[]" value="car_aston" />