Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I target specific labels with Javascript? (i.e. not using "contains")

Apologies in advance, I have zero programming knowledge.

So my company just bought some software that includes a checkout function. For some reason, the checkout page does not by default highlight which fields are mandatory vs optional in order to complete checkout.

My boss has asked to me highlight the mandatory fields, which can be done through javascript. Except I don’t know javascript.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The support guy helped me out, and I’ve been able to do most of it using the ‘contains’ function, like this:

$('.page-checkout label:contains(Country)').after(' <span class="required-text" style="color:red">* Required</span>');

But, I have some fields don’t have a unique enough label for the contains function to only highlight what I need (e.g. I want to highlight the mandatory "address" field, but not the optional "address 2" field).

How do I only target the "address" field without also hitting the "address 2" field?

>Solution :

(i.e. not using "contains")

Or perhaps using "not contains"?

You could amend the :contains(Address) with a :not(:contains(2)). For example:

$('.page-checkout label:contains(Address):not(:contains(2))').after(' <span class="required-text" style="color:red">* Required</span>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="page-checkout">
  <label for="address">Address</label>
  <input id="address">
  <label for="address2">Address 2</label>
  <input id="address2">
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading