Getting elements from a dynamic page and submitting it with a form

Hello! When a user submits a form, I’d like to also include an img src and text from an element on the page.

I think I can accomplish this by saving the img src and text from the dynamic page into local storage, and then passing that into a hidden field which would get submitted along with the user input. But maybe there is an easier way - maybe dynamically submitting the form and having it also include the img src of imageX and text from elementY as part of the submitted data.

If anyone can point me into the right direction, I would really appreciate it!

Yes, you can achieve your goal by dynamically submitting the form and including the img source and text from an element on the page as part of the submitted data. Here’s an example of how you can accomplish this using JavaScript:

Get the img source and text from the desired elements on the page. You can use methods like document.querySelector or document.getElementById to select the elements and retrieve their values. For example:
var imgSrc = document.querySelector(‘#imageX’).src;
var elementText = document.querySelector(‘#elementY’).textContent;
In the above code, #imageX and #elementY are placeholders for the actual IDs or CSS selectors of the elements you want to extract data from.

Attach an event listener to the form submit event. When the form is submitted, you can retrieve the form data, append the img source and text values, and then submit the form programmatically. Here’s an example:
var form = document.querySelector(‘#yourFormId’);
form.addEventListener(‘submit’, function(event) {
event.preventDefault(); // Prevent the form from submitting normally

var formData = new FormData(form);
formData.append(‘imgSrc’, imgSrc);
formData.append(‘elementText’, elementText);

// Perform any additional form data manipulation if needed

// Submit the form programmatically
fetch(form.action, {
method: form.method,
body: formData
.then(function(response) {
// Handle the form submission response
.catch(function(error) {
// Handle any errors
In the above code, #yourFormId is a placeholder for the actual ID or CSS selector of your form element.

This approach dynamically retrieves the img source and text from the page when the form is submitted and includes them in the form data. You can then process this data on the server-side when handling the form submission.