Run Javascript before Submit

Hello Everyone,

I’m newbie in Yii && PHP/Javascript. I want to run a Javascript function before submit my Form

Do some thing like that in Yii


<html>

<head>

<script>

function doThis()

{

alert("testing");

return true

}

</script>

</head>

<body>

<form action="test.php" onsubmit="return doThis()" method="post">

<input type=submit >

</form>

</body>

</html>

Any body can help me how to implement that in Yii ?

Many thanks :D

You can implement into your javascript condition - whether to continue submission or prevent it;

Your function must return true if you want to continue submission or false - to prevent it.

Your code can look like this:

This javascript example is written on jQuery, so you must connect jQuery library to have this code working.

Thank you for your response =).

I m newbie with jQuery too :s.

But here what i did:

I have 2 forms the first is a simple form that have a multiple input fields


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

		'id'=>'first-form',

		'enableAjaxValidation'=>false,

	)); ?>



The second is for uploading files:


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

	'id'=>'uploads-form',

	'enableAjaxValidation'=>false,

	'htmlOptions' => array('enctype' => 'multipart/form-data')

	)); ?>

Now I want to create a new record for the first form before uploading the file. So when a user filled the first form && upload relative files it will create a new record for the first form and create an other new record for the upload form (the first form and upload are two separated ActiveRecord related by a foreign key).

To do that I create a javascript function that copied information filled in the first form to a hidden input on upload form.


<?php 	$js = <<< EOF_JS

function copyFirstFormToUploadsForm(){

var FirstForm= document.getElementById('first-form');

var UploadsForm = document.getElementById('uploads-form');

UploadsForm.elements["Title"].value = FirstForm.elements["Title"].value; .....

	}

EOF_JS;

Yii::app()->clientScript->registerScript('uploads-form-beforeValidate', $js, CClientScript::POS_READY);

	?>

NOW I WANT TO RUN THIS JS FUNCTION BEFORE SUBMITING to get information from the first form and passe them in to the hidden input !

My submit button is


	<div class="row buttons">

		<?php 

		echo CHtml::button('Upload', 

		array('submit' => array('controller/action'))

		); 

		?>

	</div>	

SO HOW CAN I DO IT ?