0

I am pretty new in JavaScript and I have the following problem. Into a JSP page I have something like this:

    <tbody>
        <c:forEach items="${listaProgetti.lista}" var="progetto" varStatus="itemProgetto">
            <tr id='<c:out value="${progetto.prgPro}" />'>
                <td><input type="checkbox" class="checkbox" onchange="changeCheckbox()"></td>
                .....................................................
                .....................................................
                .....................................................
            </tr>
        </c:forEach>
    </tbody>

So a you can see clicking on the checkbox it is call this changeCheckbox() that actually is something very simple:

function changeCheckbox() {
    alert("INTO changeCheckbox()");
    
    var checkedRowList = new Array();
}

The problem is that into this function I have to retrieve what is the input object that fire the change event (I think something like the this)

How can I obtain the reference to the clicked checkbox in my previous changeCheckbox() function?

1 Answer 1

6

The element is available in the event handler content attribute, not in changeCheckbox. But you can pass it as an argument.

  • Using this

    changeCheckbox(this)
    

    function changeCheckbox(elem) {
      elem.style.marginLeft = '100px';
    }
    <input type="checkbox" onchange="changeCheckbox(this)" />

  • Using event:

    changeCheckbox(event.target)
    

    function changeCheckbox(elem) {
      elem.style.marginLeft = '100px';
    }
    <input type="checkbox" onchange="changeCheckbox(event.target)" />

Note it would be better to use addEventListener:

document.querySelector('input').addEventListener('change', changeCheckbox);

Then the function changeCheckbox will receive the event object as its first parameter, and the current target element as the this value.

document.querySelector('input').addEventListener('change', changeCheckbox);
function changeCheckbox(e) {
  e.target.style.marginLeft = '100px';
}
<input type="checkbox" />

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.