'Pre-populate form field with the text from a <p> using JavaScript

I have this on a page:

<p class="test" style="width: 300px" title="intro">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>

Underneath, I want to have a hidden field... On clicking on the submit button, I would like the text from <p> with class "test" to pre-fill the hidden field.

Is this possible?

UPDATE

Have done this.. but:

  1. When the page loads, I get a popup with the contents of the field. Can this be stopped?

  2. I have the content in the <p> changing... can we also make the field 'update' when the content changes?



Solution 1:[1]

If your p doesn't change why don't you use simple jQuery assignment on document ready?

$(function() {
  $("#MyInput").val($("#TargetP").text());
  alert($("#MyInput").val());
});

Demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Oybek