Go to dom using jquery to get specific elements

I am trying to use jquery parent / siblings to search for specific input elements, but I cannot figure out what is 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 the box, I want the text box inside the same div.selectItem to contain "1". If they uncheck the box, I want the value to be removed.

Q2: I also want the checkbox to be checked if the value is entered in the text box and not checked if the text box is empty.

Thank you for your help.

+4
source share
2 answers

Something like this should work. (Not tested for exact syntax, but the algorithm is robust.)

 // 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",""); } }); 
+4
source

This works with your markup (verified):

 $(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(''); } }); }); 
+1
source

All Articles