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 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 –

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

<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

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