开发者

Can't get jquery to set value of select input when value of first select changes

I'm trying to update the value of a select input when I change the value of another select input. I cannot get anything to happen on the page and want to make sure I don't have a syntax error or some other dumb thing in this code.

<div class="group">
<div class="inputs types">
<strong style="font-size:13px;">Category:</strong>
   <select name="id" id="ctlJob">
<option value="1">Automotive</option>
<option value="2">Business 2 Business</option>
<option value="3">Computers</option>
<option value="4">Education</option>
<option value="5">Entertainment & The Arts</option>
<option value="6">Food & Dining</option>
<option value="7">Government & Community</option>
<option value="8">Health & Beauty</option>
<option value="9">Home & Garden</option>
<option value="10">Legal & Financial Services&l开发者_开发技巧t;/option>
<option value="11">Professional Services</option>
<option value="12">Real Estate</option>
<option value="13">Recreation & Sports</option>
<option value="14">Retail Shopping</option>
<option value="15">Travel & Lodging</option>
  </select>
<select name="type" id="ctlPerson"></select>
</div>
</div>

<script>
$(function() {
    $("#ctlJob").change(function() {
        //Get the current value of the select
        var val = $(this).val();

 $('#ctlPerson').html('<option value="123">ascd</option>');
    });    
});
</script>


Try using append instead:

$(function() {
    $("#ctlJob").change(function() {
        //Get the current value of the select
        var val = $(this).val();
        var ctl = $('#ctlPerson').append('<option value="123">'+val+'</option>')[0].options;
        ctl.selectedIndex = ctl.length-1;
    });
});

http://jsfiddle.net/J69q8/


I think you also need to set the 'selected' property. Add

$('#ctlPerson option[value="123"]').attr('selected', 'selected');

to the end of the script. You are currently adding the option to the select list, but are not changing the select list to show it.


<div id="test">
<select name="sel" id="sel">
    <option name="1" id="1" value="1">Automotive</option>
    <option name="2" id="1 value="2">Business 2 Business</option>
    <option name="3" id="1 value="3">Computers</option>
</select>
<select name="sel2" id="sel2"></select>
</div>

<script>
$("#sel").change(function() {
    var val = $(this).val();
    $('#sel2').html('<option value="1">NEW</option>');
)};
</script>

this works fine for what you need to do. it's something like what you have

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜