简体   繁体   中英

Check a checkbox based on variable

I'm trying to create an inventory form that starts with a single item checked based on a variable passed from the URL.

Assuming I've gotten the variable here: $StartingInv = $_GET["SInv"];

And that variable, if present, will perfectly match the value of one of a list of inputs like this:

<input type="checkbox" class="inventory" name="order[]" value="IT1501"><label>Item IT1501 Name</label><br/>
<input type="checkbox" class="inventory" name="order[]" value="IT1502"><label>Item IT1502 Name</label><br/>

Is there some way to compare the value of an input to a variable when the page is loaded to programmatically assign a "checked" tag?

What I'd like to do is have a script that gets the input by it's value and assigns a checked tag, but I don't know if that's possible.

Alternatively, I could put something like this into each of the inputs, but I don't know how to reference it.

<?php if ($VALUE_OF_THIS_FORM == $StartingInv) echo "checked='checked'"; ?>

Your alternative is good enough, which is backed up by @adeneo on the comments. However, you could also try jQuery for this like so:

var startingInv = "<?= $StartingInv ?>";
$(":checkbox").each(function() {
    if ($(this).val() == startingInv) $(this).prop("checked", true);
}

You can place the php code inside your input:

<input type="checkbox" class="inventory" name="order[]" value="IT1501" <?php if($StartingInv == 'IT1501') echo 'checked'; ?>> <label>Item IT1501 Name</label><br/>
<input type="checkbox" class="inventory" name="order[]" value="IT1502" <?php if($StartingInv == 'IT1502') echo 'checked'; ?>><label>Item IT1502 Name</label><br/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM