How to make when we tick on checkbox and another input will fill up automatically
Form by example.
$开发者_开发问答fullname = 'John Travolta';
<input type="text" name="fullname" />
<input name="same" type="checkbox" /> Tick if same name
- When we tick on the checkbox the
input fullname
will insert automatically by data from$fullname
- How to do that by javascript, jquery or etc ?
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 = '';
}
}
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>
<!-- 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>
精彩评论