Yii Framework Forum: Input Value Via Link Into A Form Field - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Input Value Via Link Into A Form Field plus how to generate a random number via js Rate Topic: ***** 1 Votes

#1 User is offline   skworden 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 165
  • Joined: 14-June 12
  • Location:Virginia, USA

Posted 05 February 2013 - 01:36 AM

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

Attached File  Untitled.png (5.42K)
Number of downloads: 16

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.
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users