How to Search and Replace with jQuery?

I have a form that has a hidden field with a value of "{UTMCode}". I want to find this value and replace it with data that I have stored in a variable.

The IDs and classes on the fields are dynamic, so I can’t target by ID or class, but a default value can be set, so that’s how I am trying to target the field.

The code looks like this –

<div class="form-wrapper" id="contactForm">
  <form>
    <div class="inputContainer" style="margin-left:3px; width: auto; "> 
      <input type="hidden" name="HiddenElement_0[value]" value="{UTMCode}"> 
    </div>
  </form>
</div>

Is there a jQuery function so I can search the page or form/div for "{UTMCode}" and replace it with my variable?

>Solution :

NO need for jQuery.

document.getElementById('contactForm')
  .querySelector('.inputContainer > [type=hidden][value="{UTMCode}"]')
  .value=yourVar;

but if you insist

$('#contactForm')
  .find('.inputContainer > [type=hidden][value="{UTMCode}"]')
  .val(yourVar);

[type=hidden] is not even needed unless there are other fields with that value

Leave a Reply