jQuery Check if Checkbox is Checked, then Add Value to Input Field

14,904

Solution 1

You have to update your hidden field whenever the checkbox is changed:

$(function(){
    $('#gift').change(function() {
        $("#gift-true").val(($(this).is(':checked')) ? "yes" : "no");
    });
});

Solution 2

Use jQuery .val() to set the value of the input element. jquery .is() returns a boolean value, so you will have to check if it is true (using an if statement or a ternary operator like below), then conditionally update the value. Also, you should update this value whenever the box is selected/unselected:

$(document).ready(function(){
    $('#edit-checkbox-id').change(function() {
        $("#gift-true").val( this.checked ? "Yes" : "" );
    }
});​

Also, if your checkbox is:

<input type="checkbox" name="gift" id="gift" class="checkbox" value="" />

The appropriate id-selector is $('#gift'), not $('#edit-checkbox-id')

Share:
14,904
RevConcept
Author by

RevConcept

Web designer + developer. Founder and Creative Director at Mind-Blowing Things Digital Creative Agency. Principal Design + Development at Revelation Concept.

Updated on June 11, 2022

Comments

  • RevConcept
    RevConcept about 2 years

    I have a shopping cart checkout page and I'm trying to add a "gift" option. What needs to happen: Once the checkbox is selected for "Send Order As Gift", a value needs to be assigned to a hidden input field so that the information is moved onto the confirmation page and various receipts.

    HTML:

    <h3>Send Order As Gift</h3>
    <ul>
        <li class="fc_row fc_gift"><label for="gift" class="fc_pre">This is a gift, 
        please do not include a receipt.</label>
        <input type="checkbox" name="gift" id="gift" class="checkbox" value="" />
        <input type="hidden" name="Gift" id="gift-true" value="" /></li>
        <script type="text/javascript">
        $(document).ready(function(){
            $("#gift-true").input( $('#edit-checkbox-id').is(':checked').val() + "Yes"); 
        });​                
        </script>
        </li>
        <li class="fc_row fc_gift_message"><label for="Gift Message">Include a message 
        (limit 100 characters):</label>
        <textarea name="Gift Message" cols="50" rows="3" maxlength="100"></textarea>
        </li>
    </ul>