Hi.

Anyone know how to add javascript to a select element? On each option I want onclick='document.submitbutton.value="something_relevant_to_the_option"'. Is that possible?

Cheers.

Comments

Anonymous’s picture

Worked it out:

function blockform_smallprop_cta() {

print "<script lang='javascript'><!--
function changeSubmit() {
var x=document.getElementById(\"edit-blockform-smallprop-cta-bttc\");
document.getElementById(\"callme\").value = x.value;
}
-->
</script>";

$form['blockform_smallprop_cta_bttc'] = array(
		'#type' => 'select',
		'#title' => t('Best time to call you'),
	 	'#attributes' => array('onChange' => 'changeSubmit()'),
		'#options' => array('Call me in the morning' => 'morning', 'Call me in the afternoon' => 'afternoon', 'Call me in the evening' => 'evening'),
		'#required' => TRUE,
);
	
$form['submit'] = array(
		'#type' => 'submit',
		'#id' => 'callme',
		'#value' => t('Call me'),
);

return $form;
}

More elegant solutions welcome.

Anonymous’s picture

By the way, just printing a script is bad... IE explodes. use this code:

function blockform_smallprop_cta() {

drupal_set_html_head("<script lang='javascript'><!--
function changeSubmit() {
var x=document.getElementById(\"edit-blockform-smallprop-cta-bttc\");
document.getElementById(\"callme\").value = x.value;
}
-->
</script>");

$form['blockform_smallprop_cta_bttc'] = array(
'#type' => 'select',
'#title' => t('Best time to call you'),
'#attributes' => array('onChange' => 'changeSubmit()'),
'#options' => array('Call me in the morning' => 'morning', 'Call me in the afternoon' => 'afternoon', 'Call me in the evening' => 'evening'),
'#required' => TRUE,
);

$form['submit'] = array(
'#type' => 'submit',
'#id' => 'callme',
'#value' => t('Call me'),
);

return $form;
}
tr’s picture

Status: Active » Closed (fixed)

Original poster indicated in #1 and #2 that the problem is fixed.