Reputation: 2170
I am trying to use jquery's parents/siblings to find particular input elements but I cannot seem to get this right.
I have the following HTML:
<div id="ExtrasOptions">
<div class="selectItem">
<div class="selectPrice"><span>Qty: <input name="qty" type="text" value="0" maxlength="2" id="qty" class="AccessoryQuantity" /></span></div>
<div class="selectIt"><span><input name="extraselected" type="checkbox" id="extraselected" value="9" /><label for="extrasID">Add this</label></span></div>
</div>
<div class="selectItem">
<div class="selectPrice"><span>Qty: <input name="qty2" type="text" value="0" maxlength="2" id="qty2" class="AccessoryQuantity" /></span></div>
<div class="selectIt"><span><input name="extraselected2" type="checkbox" id="extraselected2" value="9" /><label for="extrasID">Add this</label></span></div>
</div>
</div>
Q1: When someone checked a checkbox I want the textbox within the same div.selectItem to have a '1' put into it. If they uncheck the checkbox I want the value to be removed.
Q2: I also want the checkbox to be checked if a value is entered into the textbox and unchecked if the textbox is blank.
Thanks for your help.
Upvotes: 4
Views: 6605
Reputation: 15946
Something like this should work. (Not tested for precise syntax, but the algorithm is solid.)
// Bind an event to each of your checkboxes, for when they are clicked
$("input[type=checkbox]").click(function() {
if ($(this).attr("checked")) {
// The checkbox is checked, so find the associated text input and change its value
$(this).parents(".selectItem").find("input[type=text]").val("1");
} else {
// The checkbox is unchecked, so find the associated text input and remove its value
$(this).parents(".selectItem").find("input[type=text]").val("");
}
});
// Bind an event to each of your text inputs, for when they have text entered into them
$("input[type=text]").keypress(function() {
if ($(this).val() != "")) {
// There is something in the text input box, so check the associated checkbox
$(this).parents(".selectItem").find("input[type=checkbox]").attr("checked","checked");
} else {
// There is nothing in the text input box, so uncheck the associated checkbox
$(this).parents(".selectItem").find("input[type=checkbox]").attr("checked","");
}
});
Upvotes: 4
Reputation: 342635
This works with your markup (tested):
$(document).ready(function() {
$('input:checkbox').change(function() {
if($(this).is(':checked')) {
$(this).val('1');
} else {
$(this).val('');
}
});
$('input[type=text]').keyup(function() {
if($(this).val() != "") {
$(this).parent()
.parent()
.next('.selectIt')
.find('span > input:checkbox')
.attr('checked','checked')
.val('1');
} else {
$(this).parent()
.parent()
.next('.selectIt')
.find('span > input:checkbox')
.removeAttr('checked')
.val('');
}
});
});
Upvotes: 1