tags:

views:

183

answers:

3
<p>First Name <input type="text" name="first_name"> Last Name <input type="text" name="last_name"></p>
<input type="hidden" name="screen_name" value="first_name + last_name">

How do I take what was typed into first_name and last_name fields and add them together to the screen_name so when the field is submitted, it inputs the values appropriately for the screen_name field?

I am looking for either a php or jQuery resolution.

Would this do the trick?

<?php $screen_name = $_POST["first_name"]." ".$_POST["last_name"]; ?>

  <input type="hidden" name="screen_name" value="<?php print $screen_name; ?>" />
+3  A: 

You're better off leaving out the screen_name all together. Just concatenate the values from first_name and last_name at the PHP side.

<?php

$screen_name = $_REQUEST['first_name'].$_REQUEST['last_name'];

?>

If you use JavaScript, someone may just disable it and send you a screen name that isn't actually their first and last name.

bucabay
Suggestions: Trim both the first_name and last_name since the user could have antecedently put spaces in them (and maybe put a space between the first and last name?) Maybe also make sure that the first and last name don't have characters below 31, no special chars, case-correction...
some
A: 

For PHP (on the server side):

$ScreenName = $_POST["first_name"]." ".$_POST["last_name"]

With jQuery (on the client side) you'll have to add ids to the fields to easier access them:

<p>First Name <input type="text" name="first_name" id="first_name"> Last Name <input type="text" name="last_name" id="last_name"></p>
<input type="hidden" name="screen_name" value="first_name + last_name" id="screen_name">

And then on the form submit event (or input field change event) set the screen_name field value:

var screenNameVal = $.("#first_name").attr("value")+" "+$.("#last_name").attr("value");
$.("#screen_name").attr("value",screenNameVal);
Gergely Orosz
@bucabay has a very important point though that someone can turn off Javascript and submit their own value for screen name, so while possible with jQuery to do it ahead of time it's best with PHP server side
ctshryock
Never ever trust the user input. Always sanitize it. At least trim it (remove white space at the beginning and at the end). Even if javascript is great and useful, make sure your pages works as much as possible even when it's not available (the user may have disabled it).
some
Check your jQuery, it doesn't work
Mike Robinson
I agree that if possible, all logic should be on the server side. In this case the PHP version is not only safer but even cleaner.
Gergely Orosz
+2  A: 

I agree it should be server side, but just to answer your question:

var combinedName = $("input[name='first_name']").val() + $("input[name='last_name']").val();
$("input[name='screen_name']").val(combinedName);
Mike Robinson