简体   繁体   中英

how to add a class to an element when i click a different element with jquery

I have an input that is supposed to add a class of clicked to another element with an id of #zip when clicked. Here is the code:

 $('#billing_zip').click(function () { $('#zip').addClass('clicked'); }); 
 #zip { color: #444; font-style: italic; position: absolute; top: 8px; left: 35px } .clicked { display: none; } 
 <div class="chkField"> <label for="billing_zip">Zip</label> <input type="text" onchange="clearContent(this);check_address('billing');" class="txtBoxStyle hasPlaceholder" tabindex="10" size="10" value="" id="billing_zip" maxlength="15" name="billing_zip"> <!--START: req_billing_zip--> <img width="12" height="12" alt="" src="assets/templates/common/images/error2.gif"> <!--END: req_billing_zip--> <div class="clear"></div> <div id="zip">zip</div> </div> 

I don't know why the above jQuery is not working.

You forgot to declare id for billing_zip.

 $(document).ready(function(){ $('#billing_zip').click(function () { alert('hi'); $('#zip').addClass('clicked'); }); }); 
 #zip { color: #444; font-style: italic; position: absolute; top: 8px; left: 35px } .clicked { display: none; } 
 <div class="chkField"> <label id="billing_zip" for="billing_zip">Zip</label> <input type="text" onchange="clearContent(this);check_address('billing');" class="txtBoxStyle hasPlaceholder" tabindex="10" size="10" value="" id="billing_zip" maxlength="15" name="billing_zip"> <!--START: req_billing_zip--> <img width="12" height="12" alt="" src="assets/templates/common/images/error2.gif"> <!--END: req_billing_zip--> <div class="clear"></div> <div id="zip">zip</div> </div> 

Your code is working OK

It could be 2 possible issues:

  1. You are missing to add the jQuery reference:

  2. You should wrap your code inside the document.ready event:

    $(function(){ $('#billing_zip').click(function () { $('#zip').addClass('clicked'); }); });

Check out the jsfiddle here. Use document.ready if required. One important point i found out is that, if the placeholder text on input box is lengthy, then it covers up entire input box area and doesn't allow to trigger click event. refer the jsfiddle.

$('#billing_zip').click(function () { 
    $('#zip').addClass('clicked');
});

$('#zip').click(function () { 
    $('#zip').addClass('clicked');
});

If this only what you want. Then you can do directly like:

$('#billing_zip').click(function () {
    $('#zip').css("display","none"); // or you can use hide or fadeout property.
});

When I wrapped your jQuery code in a "$(document).ready" it worked:

$(document).ready(function(){
  $('#billing_zip').click(function () {
   $('#zip').addClass('clicked');
 });
});

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