Alexandr
Alexandr

Reputation: 1031

Tick checkbox via javascript console by lable names

I would like to check boxes via javascript.

The thing is I have a task to check more then 300 checkboxes whith specific names.

I can check one box, or check all boxes... but how to check specific boxes?

Here is an example:

<li id="s1" class="city-select">
    <input name="rid" id="r1" value="1" type="checkbox">
    <label for="r1" id="l1">Paris</label>
</li>
<li id="s1" class="city-select">
    <input name="rid" id="r2" value="2" type="checkbox">
    <label for="r2" id="l2">Plovdiv</label>
</li>
<li id="s1" class="city-select">
    <input name="rid" id="r3" value="3" type="checkbox">
    <label for="r3" id="l3">Berlin</label>
</li>

I would like to tick only "Berlin" and "Paris" - here is what I'm using to tick all:

[].forEach.call(document.querySelectorAll('input[type="checkbox"]'),function(el){el.checked=true});

And here is what am I trying to type:

$("lable:contains('paris, berlin')").prev().find('input').addAttr("checked");

Upvotes: 0

Views: 172

Answers (2)

fdomn-m
fdomn-m

Reputation: 28621

It looks like your use of prev should be parent or closest.

So you take the current label, go up to the container, then down to the checkbox.

If you use prev then you restrict how much you can change the html (eg if you add a div wrapper around the label in the future, you'll have to change all your code).

given:

<li id="s1" class="city-select">
    <input name="rid" id="r3" value="3" type="checkbox">
    <label for="r3" id="l3">Berlin</label>
</li>

then use

$("label:contains(Paris),label:contains(Berlin)")
    .closest("li")
    .find(":checkbox")
    .prop("checked",true);

More info at the API documentation: https://api.jquery.com/closest/


How to use this for 300 cities?

This depends on how they are stored. If it's a comma separated list (Paris,Berlin) then split into an array first, if it's json, then convert to an array first...(see the pattern?)

var citiesList = "Paris,Berlin".split(",");

$(citiesList).each(function() {
    $("label:contains(" + this + ")")
        .closest("li")
        .find(":checkbox")
        .prop("checked",true);
});

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

You have wrong selector to target checkboxes. You need to use:

$("label:contains(Paris),label:contains(Berlin)").prev().prop("checked",true);

Working Demo

Update:

var cities = ["Paris","Berlin"];
 $("label:contains('" + cities.join("'),label:contains('") + "')").prev().prop("checked",true);

Working Fiddle for update

Upvotes: 2

Related Questions