Skip to content
Advertisement

Value attribute of button not passed when icon is clicked directly

I have an html button created using bootstrap that is essentially an Icon used to toggle the state of an item on a website.

<button class='btn' value='${noteid}' onclick='toggleAck(event)'><i class="fas fa-eye"></i></button>

When it is clicked a request is fired:

function toggleAck(event) {
            const noteid = event.target.value
            console.log(event.target)
            $.post({
                    url: `/note/${noteid}/toggleacknowledge`,
                    dataType: "json"
                },
                (response) => {
                    if (!response.success) {
                        alert("Failed to mark as read")
                    }
                    refreshNotes()
                }
            )
        }

regardless of whether I click the button or the icon, the toggleAck event triggers. However, if I click the icon directly instead of the button the value attribute is not passed and the function fails.

How can I fix this HTML so that the value is passed regardless of where the user clicks?

Advertisement

Answer

The value is on the button, but the event.target is the element that triggered the event so when you click the icon it tries to retrieve the value from the icon.

Instead use event.currentTarget to get the value from the element to which the listener is attached.

const noteid = event.currentTarget.value;

function toggleAck(event) {
  console.log('target: ', event.target, event.target.value);
  console.log('currentTarget: ', event.currentTarget, event.currentTarget.value);
}
<button class='btn' value='${noteid}' onclick='toggleAck(event)'><i class="fas fa-eye">icon</i></button>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement