JavaScript: Print HTML Form Values onChange
I'm trying to echo out the value of the chosen value out of the form drop down box (named sets) once it has been selected. At the moment, I'm having no luck. Also to note I am using codeigniter but I dout this will be the problem.
<head>
<script type="text/javascript"&开发者_StackOverflow中文版gt;
function set_boxes()
{
var TestVar = form.sets.value;
alert("TestVar");
}
</script>
</head>
<h1>New Entry</h1>
<?php
echo form_open('log/add_entry');
/*Weight Entry*/
echo form_label('Weight:', 'weight');
echo form_input('weight');
/*Weight Measurement*/
$measurementOptions = array('kg' => 'KG', 'lbs' => 'LBS');
echo form_dropdown('measurement', $measurementOptions, 'kg');
echo " - ";
/*Sets at Weight*/
echo form_label('Sets:', 'sets');
$setOptions = array('' => '', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', );
$js = 'onChange="set_boxes(this.form);"';
echo form_dropdown('sets', $setOptions, '', $js);
A few possibilities:
Your function and its call aren't consistent with each other:
onChange="set_boxes(this.form)" // 1 argument
function set_boxes() // 0 arguments
I think what you want is this:
function set_boxes(form)
With that, the form
variable within the function will equal the expected DOM object:
var TestVar = form.sets.value;
Also, did you mean to alert the string "TestVar"
? If you want to alert the value of the variable, just drop the quotes:
alert(TestVar);
So, give this a try:
function set_boxes(form)
{
var TestVar = form.sets.value;
alert(TestVar);
}
For select boxes, you can't just use .value
It's a little more complicated. This should be what you want:
var TestVar = form.sets.options[form.sets.selectedIndex].value;
精彩评论