I have a Netresults form on my webpage that I need to prepopulate. The form is inserted into the page with javascript and so I am unable to see the form fields in the source code.
I would use the below code if the form was on my page but as its not, I have no idea how to target the fields. Can anyone help?
var keywords = getUrlParameter('keywords'); $('input[name=netres-keywords]').val(keywords);
The netresults form is inserted with this code:
(function() { var $__MAForm; ($__MAForm =function(){ if(typeof($__MA)=="undefined"){ return window.setTimeout($__MAForm,50); }else{ $__MA.addMAForm("43788303-2b62-4774-ad0f-63542e3ed92a", "forms.example.com"); } })(); })();
1 Answers
Answers 1
This may require the use of a Mutation Observer.
A mutation observer will check for changes to the DOM (added elements, etc), and we can use this to fire an event. The code below will change the value of an input with name netres-keywords
any time a new <form>
element is added to the <body>
.
In the example JSFiddle at the bottom of this post, I've created a button that simulates a form being added to the page. As you can see, the textbox will pre-populate.
$(document).ready(function() { var keywords = "this is a test keyword"; var formCount = $("form").length; var observer = new MutationObserver(function() { var newFormCount = $("form").length; if (newFormCount > formCount) { $('input[name=netres-keywords]').last().val(keywords); } }); $("button").click(function() { $form = $("<form>").html("<h1>New form:</h1><input type='text' name='netres-keywords'>"); $("body").append($form); }); var observerConfig = { attributes: true, childList: true, characterData: true }; var targetNode = document.body; observer.observe(targetNode, observerConfig); });
form { padding: 10px; border: 1px solid red; margin-bottom: 20px; } h1 { margin: 0; padding: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button> SIMULATE ADDING FORM </button> <br> <br>
0 comments:
Post a Comment