用jQuery更改选择框的值 [英] Changing the value of a select box with jquery

查看:81
本文介绍了用jQuery更改选择框的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个选择框,第二个选择框中的值取决于选择框1的选择值.

I have 2 select boxes and the values in the second selectbox are depending on the selected value of selectbox number one.

我尝试将其设置为小提琴,但无法使其正常工作,但它在html页面中有效.

I try to set this in fiddle but I can't get it working, but it is working in the html page.

它应该加载类型一,在第二个选择框中输入值0、100、200、300和400.

It should load with Type one and in the second selectbox there are the value 0, 100, 200, 300 and 400.

将类型"的值从一改变为两个时,选择框中的值应为0、100、200.

When you change the value of Type from one to two, then the values in the selectbox should be 0, 100, 200.

所以这段代码对我来说非常有效,除了例如当我在第二个选择框中选择值200时,选择框不会显示200作为选择值,而是0,00.

So this code in fiddle works for me quite well except that when I select for example the value 200 in the second selectbox, the selectbox don't show 200 as the selected value but 0,00.

知道为什么吗?

我认为jQuery在两个选择框的每次更改都被调用的函数内部.

I think the jquery is inside a function that's called on every change of both selectboxes.

enter code here

http://jsfiddle.net/arieanneke/ee99o1f1/9/

推荐答案

您需要添加一个onChange事件,并且还需要一个onReady事件,就像下面的小提琴一样.

You needed to add an onChange event and also an onReady event look a the fiddle below.

function addOptions() {

if ($('#type').val() == "one") {
    $('#amount option[value="0"]').remove();
    $('#amount option[value="100"]').remove();
    $('#amount option[value="200"]').remove();
    $('#amount option[value="300"]').remove();
    $('#amount option[value="400"]').remove();
    $('#amount').append($('<option>', {
        value: 0,
        text: '0,00'
    }));
    $('#amount').append($('<option>', {
        value: 100,
        text: '100,00'
    }));
    $('#amount').append($('<option>', {
        value: 200,
        text: '200,00'
    }));
    $('#amount').append($('<option>', {
        value: 300,
        text: '300,00'
    }));
    $('#amount').append($('<option>', {
        value: 400,
        text: '400,00'
    }));
} else if ($('#type').val() == "two") {
    $('#amount option[value="0"]').remove();
    $('#amount option[value="100"]').remove();
    $('#amount option[value="200"]').remove();
    $('#amount option[value="300"]').remove();
    $('#amount option[value="400"]').remove();
    $('#amount').append($('<option>', {
        value: 0,
        text: '0,00'
    }));
    $('#amount').append($('<option>', {
        value: 100,
        text: '100,00'
    }));
    $('#amount').append($('<option>', {
        value: 200,
        text: '200,00'
    }));
}
}
$(document).ready(addOptions);

$('#type').on('change', addOptions);

http://jsfiddle.net/ee99o1f1/11/

这篇关于用jQuery更改选择框的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆