首页 > 解决方案 > Jquery:如何使用所需的特定 ID 进行选择

问题描述

我的注册表有问题。我用 aforeach来获得所有额外的选择和额外的选项,但我想让它,如果你选中 1 个复选框,则选择成为必需的。现在我所拥有的是,如果您选中 1 个复选框和 1 个额外的复选框,则所有选择都成为必需的。

所以我想要的是:在 jquery 中给出extraoptions_id.extraoptions,以便它只使用 id 进行选择,而不是全部。

注册表单html

<label>Options</label><br>
@foreach($option_array as $option)  
    <div>
        <input type="checkbox" class="option" id="option_{{ $option->exa_id }}" name="option_{{ $option->exa_id }}" value="{{ $option->exa_id }}" {{ isset($cache) ? (isset($cache['option_' . $option->exa_id]) ? 'checked' : '')  : (old() ? (old('option_' . $option->exa_id) ? 'checked' : '') : ($registration ? (in_array($option->exa_id, $registration_options) ? 'checked' : '') : '')) }} >
        <input type="hidden" value="{{ $option->exa_price }}" class="option_price_{{ $option->exa_id }}">
        <label>{{ $option->exa_name }}</label> <label class="exa_price">  €{{ $option->exa_price }} </label>    
    </div>

    <select name="extraoptions_{{ $option->exa_id }}" class="form-control extraoptions" id="extraoptions_{{ $option->exa_id }}">
        <option></option>
        @foreach($option->extraoptions as $extraoption)
            <option value="{{ $extraoption->eos_id }}" {{ ($registration? (in_array($extraoption->eos_id, $registration_options_extra) ? 'selected' : '') : '') }}>{{ $extraoption->eos_name }}</option>
        @endforeach
    </select>
    <br>
@endforeach

jQuery

$(".option").change(function(){
    var current_price = parseFloat($(".price").val());
    //console.log(current_price);

    var id = $(this).attr('id');
    console.log(id);

    var id_number = id.split("_")[1];
    //console.log(id_number);

    var option_price = parseFloat($(".option_price_" + id_number).val());
    //console.log(option_price);        


    if(this.checked){
        var new_price = parseFloat(current_price + option_price).toFixed(2);
        $(".price").val(new_price);

        var extraoption_id = $(".extraoptions").attr('id'); 
        console.log(extraoption_id);    
        //the problem:                      

        var extraoption_number = extraoption_id.split("_")[1];
        console.log(extraoption_number);                        


        $(".extraoptions").attr('required', 'True');
    }
    else{
        var new_price = parseFloat(current_price - option_price).toFixed(2);
        $(".price").val(new_price);                         

        $(".extraoptions").attr('required', 'False');
    }
}

那么我该如何提供extraoptions_id所需的呢?提前致谢!

标签: jquerylaravel

解决方案


在输入复选框上添加data-extra-id="{{ $option->exa_id }} 。

<input type="checkbox" class="option" id="option_{{ $option->exa_id }}" data-extra-id="{{ $option->exa_id }}" ...
        $(".option").change(function(){
    
    ....
    
    $("#extraoptions_"+$(this).data('extra-id')).attr('required', 'True');
...

推荐阅读