1

I'm trying am making a dropdown with 2 questions in it. Say question A and question B. Either option they will get 3 more questions they will answer with a number 1-10. Right now if they choose A it works perfect. But if they select B, the second option it does not work. I have been looking for a way to do this for days and I'm amazed I can't find a easy way. I don't understand why this don't work because what ever they input will go to box1, box2 or box3 anyway. This is my fiddle

$('.myOptions').change(function(){

$('.list').removeClass('active')
.filter('.' + $('.myOptions').children('option:selected').attr('value'))
.addClass('active');

});

$('#butt').click(function () {

4

2 回答 2

2

问题是选项的值与分配给.list元素的类不同

解决方案是将选项的值更改为ownernot-owner

<option value="owner">Owner</option>
<option value="not-owner">Not Owner</option>

演示:小提琴

如果您不想更改选项的值,那么您可以引入一个新属性来解决问题

<option data-type="owner" value="under 45 years old">Owner</option>
<option data-type="not-owner" value="over 45 years old">Not Owner</option>

然后

$('.list').removeClass('active').filter('.' + $('.myOptions').children('option:selected').data('type'))
.addClass('active');

演示:小提琴

更新:
另一个问题是分配给输入元素的重复 ID,这里我建议的解决方案是使用 class 而不是 id,然后从活动list元素获取输入值。

<div class="list owner">
    <p>a</p>
    <input class="box1" type="text" size="2"/><br/>
    <p>b</p>
    <input class="box2" type="text" size="2"/><br/>
    <p>c</p>
    <input class="box3" type="text" size="2"/><br/>
    <!-- questions for owners -->
</div>

<div class="list not-owner">
    <p>x</p>
    <input class="box1" type="text" size="2"/><br/>    
    <p>y</p>
    <input class="box2" type="text" size="2"/><br/>
    <p>z</p>
    <input class="box3" type="text" size="2"/><br/>
    <!-- questions for non-owners -->
</div>

然后

var active = $('.list.active');

var $boxOne = active.find('.box1');
var k1 = parseInt($boxOne.val(), 10);
var $boxTwo = active.find('.box2');
var k2 = parseInt($boxTwo.val(), 10);

var $boxThree = active.find('.box3');
var k3 = parseInt($boxThree.val(), 10);
var total = k1 + k2 + k3;

演示:小提琴

于 2013-07-01T03:06:02.543 回答
1

这可能是因为您正在选择option值,而您实际上是在寻找文本:

$('.myOptions').change(function(){
    var optionText = $(this).find('option:selected').text();
    $('.list').removeClass('active').filter('.' + optionText).addClass('active');
});

它还在搜索一类not-owner当你的文本说时Not Owner,两个非常不同的东西。

于 2013-07-01T03:06:16.980 回答