Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 482
RevConcept Avatar asked Aug 15 '12 20:08

RevConcept


People also ask

How check if checkbox is checked jQuery?

To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);

How do you test if a checkbox is checked?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

How do you pass checkbox value 0 if not checked and 1 if checked?

How do you pass checkbox value 0 if not checked and 1 if checked? Add a hidden input that has the same name as the checkbox with the value of 0 BEFORE the checkbox. If the checkbox is unchecked, the hidden field value will be used, if it is checked the checkbox value will be used.

What is the value of checkbox when checked?

It has a boolean value which returns true if the checkbox is checked by default, otherwise returns false.


1 Answers

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

$(function(){
    $('#gift').change(function() {
        $("#gift-true").val(($(this).is(':checked')) ? "yes" : "no");
    });
});
like image 199
Sebastian vom Meer Avatar answered Sep 30 '22 04:09

Sebastian vom Meer