views:

117

answers:

3

Form by example.

$fullname = 'John Travolta';

<input type="text" name="fullname" />
<input name="same" type="checkbox" /> Tick if same name
  1. When we tick on the checkbox the input fullname will insert automatically by data from $fullname
  2. How to do that by javascript, jquery or etc ?
+1  A: 

Obviously, $fullname needs to be a JavaScript variable for this to work:

<script type="text/javascript">
    var fullname = 'John Travolta'; // can be entered on server side

    $('#check').change(function() {
        if ($('#check').attr('checked') == 'checked')
            $('#text').val(fullname);
    });
</script>
Franz
+1  A: 

You should use javascript (or JQuery, which is a javascript library) to do this, but since $fullname is probably a PHP variable you will need to use that too.

A simple javascript example (which can probably done a bit neater with JQuery) that uses the php variable:

<input id="fullname" type="text" name="fullname" />
<input id="same" name="same" type="checkbox" 
   onchange="javascript:samename('<?php echo htmlspecialchars($fullname) ?>')" />

this calls a javascript function that should look something like

function samename(fullname) {
  same = document.getElementById('same');
  full = document.getElementById('fullname');
  if(same.checked) {
    full.value = fullname;
  } else {
    full.value = '';
  }
}
Litso
Looking good. Mine's the jQuery option.
Franz
On second thought, does the value of the field have to be removed if the checkbox is unchecked?
Franz
@Franz yes :) I tried your jquery, more simple btw but I don't know how to make it work.
bob
Why? You just have to download the jQuery script and include it on your site... Then you have to assign the id `#check` to the checkbox and the id `#text` to the input field.I am not trying to talk you out of this solution, just explaining... Also, jQuery has quite a lot of additional benefits in other areas.
Franz
you're right franz, I use jquery myself all the time, but if this is the only solution you need it's a bit overdone to use jquery :P
Litso
I see your point :D
Franz
+1  A: 
<!-- I like using this.checked instead of $.attr -->
<script type="text/javascript">
  var fullname = "John Travolta"; // via PHP "<?= $fullname ?>";

  $("#same").change(function() {
    if (this.checked) {
      $("input[name=fullname]").val(fullname);
    }
  });
</script>
Caseman