I'm really new in the use of Drupal 7.

I would like to create a form with 2 fields width_inch and with_cm where after the user insert the value automatically will be computed the other field.

I created template.php inside the theme directory (/ sites / all / themes / my_theme / template.php ):

<?php
function ayb_preprocess_node(&$variables) {
  if (isset($variable['node']) && $variables['node']->type == 'prova') {
	  drupal_add_js(drupal_get_path('theme', 'ayb') . '/js/convert.js');
  }
}
?>

Then I tried to write my js file in the Javascript directory ( / sites / all / themes / my_theme / js / convert.js ), but I could not understand what to write in. At this moment I am not able to show a simple javascript warning:

<script>
$( "#edit-field-width_inch-und-0-value" ).change(function() {
  alert( "Handler for .change() called." );
});
</script>

It's mandatory to insert "<script>" or not? How must I call the field "width_inch"?

TNX in advance. Sorry for my bad english. Ilic

Comments

jaypan’s picture

hook_preprocess_node() is called when a node is rendered. You are trying to act on the node form though. This hook will not be called when the node form is loaded. Instead you want to use hook_form_alter().

Contact me to contract me for D7 -> D10/11 migrations.

Aleph-srl’s picture

Please be less laconic. Give me some more suggestions.
 

I need the JS just on that specific form.
In the JS how can I call the field?

TNX. Ilic

jaypan’s picture

What have you tried? What's not working?

Contact me to contract me for D7 -> D10/11 migrations.

Aleph-srl’s picture

Finally I got it!

In template.php:

<?php
function mytheme_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form_id) && $form_id == 'prova_node_form') {
      drupal_add_js(drupal_get_path('theme', 'mytheme') . '/js/convert_inch2cm.js');
  }
}
?>

In convert_inch2cm.js:

(function ($) {
  $(document).ready(function(){
	$('#edit-field-prova1-und-0-value').change(function(){
		$('#edit-field-prova2-und-0-value').val( Math.round( $('#edit-field-prova1-und-0-value').val()*3.28084 ) );
	});
  });
  $(document).ready(function(){
	$('#edit-field-prova2-und-0-value').change(function(){
		$('#edit-field-prova1-und-0-value').val( Math.round( $('#edit-field-prova2-und-0-value').val()*0.3048 ) );
	});
  });
})(jQuery);
jaypan’s picture

Nice work. Well done.

One note - in Drupal, we don't use $(document).ready(), we use Drupal.behaviors, to tie in with Drupal's JavaScript API: https://www.drupal.org/docs/7/api/javascript-api/managing-javascript-in-...

Contact me to contract me for D7 -> D10/11 migrations.