Show a different value from an input that what will be received as php

30,583

An odd request to be sure but...

You can't change the field's value and just do a simple form submission. The field will dutifully send whatever is in it. There's a few hackery ways around this tho

Option 1 - Hidden fields

So make a field, disable it, and add a hidden field. Disabled fields are never successful, although the user will be unable to change the field value and many browsers will change the styling of the field automatically

<input type="text" name="name" value="John" disabled>
<input type="hidden" name="name" value="Doe">

Option 2 - Change the value on submit

As you mentioned, you can always change the value when the form is submitted. The below listener will capture the form submitt Using jQuery since you asked it that way

$("form").on( "submit", function( event ) {
  event.preventDefault();
  $('input[name="name"]').val('Doe');
  $("form").submit();
});
Share:
30,583
Baldráni
Author by

Baldráni

Updated on December 15, 2021

Comments

  • Baldráni
    Baldráni over 2 years

    I'd like to know if there is a way to show in an input of type text a different value than the one send to PHP.

    For example, let say you have :

    <input type="text" value="John"> that display John.

    Can I change the value to "Doe" for the user but keep it to "John" for php?

    Can I achieve this using the difference between $.attr('value') and $.val()?

    I ran a couple of tests and it seems that I will have to reverse it directly in my controller. Is there an other solution?

    Here is a little jSFiddle to play around.

  • Funk Forty Niner
    Funk Forty Niner almost 8 years
    "Can I change the value to "Doe" for the user but keep it to "John" for php." - I misread that part. I'll take a negative vote(s); I've broad shoulders.
  • Funk Forty Niner
    Funk Forty Niner almost 8 years
    I misread the question. This part: "Can I change the value to "Doe" for the user but keep it to "John" for php." - My bad. I "might" end up deleting my answer.
  • RiggsFolly
    RiggsFolly almost 8 years
    You might want to change one of the name="name" names as well. If you follow me
  • Baldráni
    Baldráni almost 8 years
    Both answer were correct I tough of them before but wasn't sure if there was not a better way (quicker, safer, etc..) Anyway Thank you !
  • Funk Forty Niner
    Funk Forty Niner almost 8 years
    @Baldráni You're most welcome. I'm glad you got the solution that you needed, cheers.