A
A
Alexander2016-07-02 13:24:49
JavaScript
Alexander, 2016-07-02 13:24:49

How to refer to input through the value of a variable?

There is a piece of HTML code

<div id="1group1" class="right-item">
  <div class="img-container"> 
    <img src="" alt=""/>
  </div>
        <div class="description">
        	<div class="wrap-check"> </div> 
                <h3>Заголовок</h3>
                <p>тра ля ля</p>
        </div>  
</div>


and elsewhere in the same document

<input type="checkbox" id="1group1i" name="group1" value="">
<label for="1group1i"><a href="#1group1">Какой то заголовок</a></label>


The idea is that when you click on the .wrap-check element, the input should be removed or marked. Function written in jQuery:

$(".wrap-check").click(function() {
        var checkBoxes = $("#1group1i");
        checkBoxes.prop("checked", !checkBoxes.prop("checked"));
  $(this).toggleClass("red");
});


Works. However, there are a lot of inputs and they all have their own id, and in order not to specify everything, it was decided to specify the input id through a variable. Those. look for the parent of .wrap-check with the class .right-item and see what its ID is and add "i" to it at the end, this is the ID of the input that we are changing.

I rewrite the code:
$(".wrap-check").click(function() {
        	checkBoxes = $(this).closest(".right-item").attr("id")+"i";
    find(checkBoxes).prop("checked", !checkBoxes.prop("checked"));
    $(this).toggleClass("red");
    });


But such a construction does not work, it writes in the console "checkBoxes.prop is not a function"

As far as I understand, when a variable is substituted, the appeal ceases to be made to the object.
What is the correct way to refer to an object through a variable?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2016-07-02
@dikht

CheckBoxes contains an id, so you can select an element by a unique id like this - $('#' + checkBoxes).
Apparently find(checkBoxes).prop("checked", !checkBoxes.prop("checked")); should be replaced with
or something like that.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question