简体   繁体   中英

jQuery find all elements with same name start as selector

I am building the form which has SELECT and few inputs. The part of it looks like this (only for Monday example, there will be 7 days..):

<div class="row">
    <div class="col-md-3">
        <div class="form-group mb-md">
            <input type="text" name="1[day]" class="form-control text-bold" value="Monday" readonly>
        </div>
    </div>
    <div class="col-md-1">
        <div class="form-group">
            <select class="form-control input-md mb-md" name="1[open]">
                <option value="1" selected>Open</option>
                <option value="0">Closed</option>
            </select>
        </div>
    </div>
    <!-- Working Hours -->
    <div class="col-md-2">
        <div class="form-group">
            <input type="text" class="form-control time" name="1[start]" value="08:00">
        </div>
    </div>
    <div class="col-md-2">
        <div class="form-group">
            <input type="text" class="form-control time" name="1[end]" value="22:00">
        </div>
    </div>

    <!-- Booking Hours -->
    <div class="col-md-2">
        <div class="form-group">
            <input type="text" class="form-control time" name="1[from]" value="08:00">
        </div>
    </div>
    <div class="col-md-2">
        <div class="form-group">
            <input type="text" class="form-control time" name="1[to]" value="22:00">
        </div>
    </div>
</div>

I want to make time fields with same name start as SELECT field name start react to SELECT change. If value is 0 then all fields with same name start get attribute disabled.

So far i made this function, however i don't know hot to determine changed field name and correspondingly take actions against other fields.

$("select[name$='[open]']").change(function() {
    if ($(this).val() == 0) {
        // Should disable all input fields with same name as SELECT
    } else if ($(this).val() == 1) {
        // Should enable all input fields with same name as SELECT
    }
});

Not sure if this is what you are attempting to achieve.

Please try below code.

$("select[name$='[open]']").change(function() {
    var num = $(this).attr("name").replace("[open]",''); 
    var elems = $( "input[name^='"+num+"']");
    if ($(this).val() == 0) {
        // Should disable all input fields with same name as SELECT
        elems.prop('disabled',true);
    } else if ($(this).val() == 1) {
        // Should enable all input fields with same name as SELECT
        elems.prop('disabled',false);
    }
});

Check the working fiddle here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM