Where To Write Jquery,ajax Code In Custom Autocomplete Text Field

Hi all,

I"m trying to write custom auto complete for text field. can anyone pls tell me where to write this jquery, ajax code for this textfield in yii…I knew that CJuiAutocomplete is there.but I need to implement own custom auto complete. can anyone pls guide me or help me to develop custom autocomplete textfield. taking the id while displaying name in the textfield.


<div id="output" class="row">

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

  <?php echo $form->hiddenField($model,'id'); ?>

  <?php echo $form->textField($model,'id');

  '$("#search").change(function(){

  

  $.ajax({url:BASE_URL + '/controller/lookup/',

  		type:"POST",

  		data:this.value,

  		success:function(data){

  		$("div").innerHTML()

  }

  });

  

  });'?>

Many Thanks

Im trying like this…am I doing correct?? ajax request is being fired to controller but my textfield is getting vanished :(. how to get the value into my textfield…this statement showing Hello world in success response $("#result").html(“Hello World”);

here is my code now: can anyone help pls…

my form is something like this…


<div id="result" class="row">

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

  <?php echo $form->hiddenField($model,'organisation_id'); ?>

  <?php echo $form->textField($model,'organisation_id');

  ?>

  

in my scripts.js file i added something like this:


$(function() {


	$('#result').change(function(){

	  	$.ajax({

	  	url: BASE_URL + '/benefit/search/',

	  	type:'POST',

	  	data:this.value,

	    success:function(data){

	    $('#result').html(data);

            //$("#result").html("Hello World"); 

	  

	    },

	    		 

	      });

	    });

});



thanks in advance

Hi,

why don’you use CJuiAutoComplete

It provides a simple way to handle this kind of situation.

yes use CJuiAutoComplete

dont complicate it with other ajax.

check the error using "firebug" console in firefox.

Thanks for your reply rajith and Luc. but i need to write cusotm autocomplete.

pls find the link for my code

Here’s a sample usage:




	<?php echo $form->hiddenField($model,'immat'); ?>

	<?php $this->widget('zii.widgets.jui.CJuiAutoComplete', array(

		'name'=>'Vol[planeur]',

		'value'=>$model->immat,

// you can use sourceUrl also

		'source'=>Vol::model()->getPlaneurs(),

		'options'=>array(

			'minLength'=>'2',

// here we update the hiddenField

			'select' => 'js:function(event, ui){ jQuery("#Vol_immat").val(ui.item["immat"]); }'

		),

		'htmlOptions'=>array(

			'style'=>'margin-right:10px',

			'class'=>'span1',

		),

	));

	?>



Dear Friend

As Rajith and Luc suggested, things can be easily done with CJuiAutoComplete.

Following is my attempt to acheive what you intend.

I have a field with attribute name.

Autocomplete is going to fetch data from model Person.

one.php displaying form and registering necessary scripts.




<div class="form">


<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'person-form',

	'enableAjaxValidation'=>false,

)); ?>


	<p class="note">Fields with <span class="required">*</span> are required.</p>


	<?php echo $form->errorSummary($model); ?>


	<div class="row">

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

		<?php echo $form->textField($model,'name',array('size'=>36,'maxlength'=>64,'id'=>"autoField")); ?>




<!--Updating the data in div with id test. making some style to match the input field -->


		<div id="test" style="width:316px;background:ghostWhite;display:none;margin-top:-8px;border-radius:10px;padding:10px;box-shadow:black 1px 1px 1px"></div>


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

	</div>


	


	<div class="row buttons">

		<?php echo CHtml::submitButton('Save'); ?>

	</div>


<?php $this->endWidget(); ?>


</div><!-- form -->


<?php


Yii::app()->clientScript->registerScript('autoComplete','

$("#autoField").on("input",function(){

	var value=$(this).val();

	if(value.length>1)

	   {

		   $.ajax({

			  type:"POST",

			  url:"'.CHtml::normalizeUrl(array("trial/two")).'" ,

			  data:{autoField:value},

			  success:function(data){$("#test").html(data).show();}

			   });		   

		   }		

	});


$("body").on("click","#test span",function(){

	$("#autoField").val($(this).html());

	$("#test").hide();

	});

');



Sofar we have made a div with id test, and made it hidden.

We are using the event input in script to perceive the changes as user types inside the text field.

That event is triggered after atleast 2 charectors are put inside the textfield.

We are posting the input field value as autoField.

When data is fetched from AJAX request,test div is filled with date and display changed to block.

When user clicks on elements in test div, the value clicked will fillup the autocomplete fieldand then test div disappears.

TrialController.php




class TrialController extends Controller

{ 

    //Action one is to display the form	

    public function actionOne()

    {

        $model=new Person;

	if(isset($_POST['Person']))

	{

             $model->attributes=$_POST["Person"];

	     echo $model->name;

	     //Do something with $model

       }


	$this->render('one',array('model'=>$model));

		

   } 




//action two is to attend the ajax call.

    public function actionTwo()

    {

        if(Yii::app()->request->getIsAjaxRequest() && isset($_POST["autoField"]))

	{

            $criteria=new CDbCriteria;

	    $criteria->compare("name",$_POST["autoField"],true);

	    $models=Person::model()->findAll($criteria);

	    foreach($models as $model)

            {

	        echo "<span style=\"font-size:18px;padding:5px;cursor:pointer;\">".$model->name."</span>";

		echo "</br>";

	    }			  

        }		

    }       

}



Functionality is acheived ,but I really struggled to adjoin the update container with form field.

I have not used the hidden field.

I hope I have helped a bit.

The following is the screenshot from my localhost.

3699

autofield.png

thanks alot seenivasan…

thats huge help.

with your code i’m getting names displayed. but how can we get hidden field id as i need to capture id by showing name??

Dear Friend

Sorry for failing to understand your requirement completely.

Now I have added the hidden field.

Following is the code little modified.

Controller




class TrialController extends Controller

{ 

    //Action one is to display the form 

    public function actionOne()

    {

        $model=new Person;

        if(isset($_POST['Person']))

        {

             $model->attributes=$_POST["Person"];

             $id=$_POST["Person"]["id"];


             //Do something with $id

       }


        $this->render('one',array('model'=>$model));

                

   } 




//action two is to attend the ajax call.

    public function actionTwo()

    {

        if(Yii::app()->request->getIsAjaxRequest() && isset($_POST["autoField"]))

        {

            $criteria=new CDbCriteria;

            $criteria->compare("name",$_POST["autoField"],true);

            $models=Person::model()->findAll($criteria);

            foreach($models as $model)

            {

              echo "<option value=$model->id style=\"font-size:18px;cursor:pointer\">".$model->name."</option>";

              echo "</br>";

            }                     

        }               

    }       

}



FORM




<div class="form">


<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'profile-form',

	'enableAjaxValidation'=>false,

)); ?>


	<p class="note">Fields with <span class="required">*</span> are required.</p>


	<?php echo $form->errorSummary($model); ?>


	<div class="row">

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

		<?php echo $form->hiddenField($model,'id',array('id'=>"hiddenField")); ?>

		<?php echo $form->textField($model,'name',array('size'=>36,'maxlength'=>64,'id'=>"autoField")); ?>

		<div id="test" style="width:316px;background:ghostWhite;display:none;margin-top:-8px;border-radius:10px;padding:10px;box-shadow:black 1px 1px 1px"></div>

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

	</div>


	


	<div class="row buttons">

		<?php echo CHtml::submitButton('Save'); ?>

	</div>


<?php $this->endWidget(); ?>


</div><!-- form -->


<?php


Yii::app()->clientScript->registerScript('autoComplete','

$("#autoField").on("input",function(){

	var value=$(this).val();

	if(value.length>1)

	   {

		   $.ajax({

			  type:"POST",

			  url:"'.CHtml::normalizeUrl(array("trial/two")).'" ,

			  data:{autoField:value},

			  success:function(data){$("#test").html(data).show();}

			   });		   

		   }	

	});


$("body").on("click","#test option",function(){

	$("#autoField").val($(this).html());

	$("#hiddenField").val($(this).attr("value"));

	$("#test").hide();

	});

');



Kindly check whether it is working in IE.

It is working in chrome,firefox and opera in my linux machine.

Regards.