Input Value Via Link Into A Form Field

This is a simple way to input text into a form field with a link.

I’ll show how I use it to auto generate a serial number for a product that does not have one.

The JS




<script type="text/javascript">

	function addValue(text,element_id) {

	document.getElementById(element_id).value = text;

	}

</script>



The form




	<div class="row">

		<?php echo $form->labelEx($model,'serial_number'); ?>

		<?php echo $form->textField($model,'serial_number',array('id'=>'randomserialnumber','style'=>'width: 185px;','maxlength'=>50,)); ?>

		<?php echo $form->error($model,'serial_number'); ?><br>


	<a href="#" onclick="addValue(Math.floor((Math.random()*9999999999999)+1000000000000),'randomserialnumber'); return false;"; style="font-size:13px">Generate Random Serial Number</a><br>


	</div>



The above code will generate a number between 1,000,000,000,000 and 9,999,999,999,999 (mine happened to require 13 digits that’s why it’s like that). You could do Math.random()*99)+1)to do between 1 and 99 etc. and input it into the form field automatically.

here is what it looks like after click

3823

Untitled.png

I use js to update it b/c it is client side and will update onclick every time vs something like mt_srand() in php where you would have to use more code to accomplish this same effect of updating every time onclick.

You could also do something like this




<div class="row">

		<?php echo $form->labelEx($model,'serial_number'); ?>

		<?php echo $form->textField($model,'serial_number',array('id'=>'randomserialnumber','style'=>'width: 185px;','maxlength'=>50,)); ?>

		<?php echo $form->error($model,'serial_number'); ?><br>


	<a href="#" onclick="addValue(Math.floor('YOUR VALUE','randomserialnumber'); return false;"; style="font-size:13px">Input YOUR VALUE</a><br>




This will place YOUR VALUE into the text field on click. You can add this to multiple fields in the same form just change the id’s for the links and the form field.