开发者

Updating textbox with dropdown value doesn't work in IE [JavaScript]

I'm trying to update the text in a textbox when a value is selected from a dropdown form element using onchange().

This works fine in Firefox, Safari, Chrome but not in Internet Explorer.

Here's the stripped down code:

<script type="text/javascript">
$(document).ready(function(){
   document.forms['time_form'].elements['hours'].onchange = function(){
   document.getElementById('hours_text').value = '';     // Clear the current value
   document.forms['time_form'].elements['hours_text'].value += this.value;             开发者_运维百科 
   };
});
</script>

<select name="hours" id="hours" class="time">
      <option value"01">01</option>
      <option value"02">02</option>
      <option value"03">03</option>
      <option value"04">04</option>
      <option value"05">05</option>
      <option value"06">06</option>
      etc...
</select>
<input type="text" id="hours_text" name="hours_text" value="01" />

The current text is cleared as it should be but not updated with the new value. Any ideas what's going on? Is this my error or IE's?


Change your code to something like:

$(document).ready(function(){
    // apply a change event
    $('#hours').change(function() {
        // update input box with the currently selected value
        $('#hours_text').val($(this).val());
    });
});

You are using jQuery already so make use of it's abilties to control the events of an element and write your code the jQuery way. Do not mix code such as onchange on this (although it may work) but it's better to make things consistent.


I've spent 5 minutes trying to figure out why your code doesn't work, only to find out you forgot the = character in your OPTION start tags. Grrrr.... :)

Replace <option value"01"> with <option value="01"> for every OPTION start tag.

Here you go:

$('#hours').change(function() {
    $('#hours_text').val( this.value );
});

Live demo: http://jsfiddle.net/ubrcq/


I don't see why you'd blank the value property and then immediately append more text using +=, you could achieve the same thing by simply setting the value property to this.value in one go.

Also, you are targeting the 'hours_text' element in 2 different ways:

document.getElementById('hours_text')

and

document.forms['time_form'].elements['hours_text']

It would be a little bit cleaner to assign to a variable like so:

var hours_text = document.getElementById('hours_text');
hours_text.value = this.value;


function ChangeValue()
{
    $("#hours_text").val($("#hours").val());
}

<select name="hours" id="hours" class="time" onchange="ChangeValue()">
      <option value"01">01</option>
      <option value"02">02</option>
      <option value"03">03</option>
      <option value"04">04</option>
      <option value"05">05</option>
      <option value"06">06</option>
      etc...
</select>
< input type="text" id="hours_text" name="hours_text" value="01" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜