Text

And I also have a form:

Send the value of the <p> element when submitting the html form

I have this code: <p class = "foo">Text</p>

And I also have a form: <form action = "XXX.php" method = post></form>

However, how can I get the <p> value when I send it, since the <p> element can be changed.

So, I mean, you can send the <p> value when the user submits the form, and be able to access it from this php file with: $_POST['foo'];

Thank you, I tried to be as clear as possible.

+4
source share
6 answers

I think your best bet is to make it input with readonly enabled and style to look like <p> . This is better than trying to add it to the POST parameters using JavaScript.

Here is a quick example . I bet it can still be improved with a few extra CSS addictions, experiment a bit.

+1
source

You must use Javascript for this

JQuery function that will work

 $("form").submit(function(){ var value = $("p").html(); // If foo already exists if( $("[name=foo]").length > 0 ) { $("[name=foo]").val(value); } else { var input = $("<input />", { name : "foo", value : value , type : "hidden" }); $(this).append(input); } }); 
+2
source

Use

 <input type="hidden" value="something" name="something" id="something" /> 

and when changing the internal html <p> change the value of the hidden input.

+2
source

The easiest way is to set the value of the hidden form field when changing the contents of your <p> .

Alternatively, you can get its contents and publish using JavaScript.

+1
source
  • For text, you need to use the input field:

    <input type="text"/>

  • Form fields must have id :

    <input type="text" id="pewpew" class="foo"/>

I would go with:

<input type="text" id="pewpew" class="foo" value="default text goes here"/>

OR

Go with various workarounds, such as using hidden form elements on the fly, etc.

0
source

You can create a hidden field on the fly and set its value on the submit form. Like this:

 <form id="form" action="/somewhere" method="post"> <p>Some text</p> <input type="submit" value="Submit"/> </form> <script type="text/javascript"> var form = document.getElementById('form'); form.onsubmit = function() { var p = this.getElementsByTagName('p')[0]; if (!document.getElementById('pval')) { var pinput = document.createElement('input'); pinput.setAttribute('type', 'hidden'); pinput.setAttribute('id', 'pval'); pinput.setAttribute('name', 'p'); this.appendChild(pinput); } document.getElementById('pval').value = p.innerHTML; return true; } </script> 

It works, I tested.

0
source

Source: https://habr.com/ru/post/1381541/


All Articles