سؤال

I have a pricing table with three options and a select dropdown populated with the three price options - to choose a plan, user can either choose from the select list or click the relevant table option.

At the moment when the user clicks the relevant table I can get the select to populate with the correct value but I cannot apply a class (.plan_chosen) to the table so it is obvious which one is selected each time one is chosen.

Also if someone chooses directly from the select then how can I also apply the same class to the table so again they know which is selected?

$(function() {
    $('.pricing-table').click(function() {
        var choice=$(this).attr('id');
        $('#plan').val(choice);
        $('#choice').addClass('plan_chosen');
    });
});

<div class="pt">
    <ul class="pricing-table green" id="Core">
        <li class="plan">Core</li>
        <li class="sign-up"><a href="#">Select</a></li>
    </ul>

    <ul class="pricing-table green" id="Professional">
        <li class="extra-info">POPULAR</li>
        <li class="sign-up"><a href="#">Select</a></li>
    </ul>

    <ul class="pricing-table green" id="Enterprise">
        <li class="plan">Enterprise</li>
        <li class="sign-up"><a href="#">Select</a></li>
    </ul>       
</div>

<div class="select-group focus">
    <label>Plan</label>
    <div class="select">
        <select name="plan" id="plan" class="req">
            <option>Choose a plan</option>
            <option>Core</option>
            <option>Professional</option>
            <option>Enterprise</option>
        </select>
    </div>  
</div>

Fiddle

هل كانت مفيدة؟

المحلول

Try

$(function () {
    function select(choice) {
        $('#plan').val(choice);
        $tables.removeClass('plan_chosen');
        $('#' + choice).addClass('plan_chosen');
    }

    var $tables = $('.pricing-table').click(function () {
        var choice = this.id;
        select(this.id)
    });
    $('#plan').change(function () {
        select(this.value)
    })
});

Demo: Fiddle

  • you need to use choice as a variable and use it for string concatenation
  • you need to remove the plan_chosen class from previously selected element
  • you need to have a change handler for the select which will do the same

نصائح أخرى

Change script to

$(function() {
    $('.pricing-table').click(function() {
        var choice=$(this).attr('id');
        $('#plan').val(choice);
        $('.pt ul').removeClass('plan_chosen');
        $('#'+choice).addClass('plan_chosen');
    });

    $('#plan').change(function(){
        $('.pt ul').removeClass('plan_chosen');
        $('#'+ $(this).find(":selected").text()).addClass('plan_chosen');
    });
});

Here is Fiddle.

  • You must change $('#choice') to $('#'+choice)
  • You must remove class from prevoiusly clicked element
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top