skip to Main Content

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.

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?

2

Answers


  1. (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>
    Login or Signup to reply.
  2. This is maybe a more elegant way:

    //Labels to search for 
    const aSearch = ["Country", "Adress", "Firstname"];
    
    //Create a new CSS Class and append to head
    $( "<style>.my-required-class:after { color: #f00; content: '* Required'; }</style>" ).appendTo("head");
       
    
    //Search for labels and...
    for (let i = 0; i < aSearch.length; i++) {
      $(".page-checkout label").filter(function() {
        if ($(this).text() === aSearch[i]) {
          //... add new class
          $(this).addClass("my-required-class");
        }
      });
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div class="page-checkout">
      <label for="Firstname">Firstname</label>
      <input id="Firstname" />
      <br/>
      <label for="Lastname">Lastname</label>
      <input id="Lastname" />
      <br/>
      <label for="Country">Country</label>
      <input id="Country" />
      <br/>
      <label for="Adress">Adress</label><br/>
      <input id="Adress" />
      <br/>
      <label for="Adress-2">Adress 2</label><br/>
      <input id="Adress-2" />
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search