Jump to content

getting the deeper click event


phppup
Go to solution Solved by requinix,

Recommended Posts

I have TWO buttons inside a form.

<form onsubmit="return myFunc()">

myFunc displays a confirmation box after a button is clicked.

The message would be different depending on which button is clicked, but when I use

alert(event.srcElement.id);

I am getting a result that indicates that the FORM has been clicked, not which button has been clicked.

How can I get the button result in order to create an IF statement for comparisons?

 

 

Link to comment
Share on other sites

Something like...

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example</title>
    <meta charset="utf-8">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type='text/javascript'>
        $(function() {
            $(".form-button").click(function(e) {
                e.preventDefault()                            // stop button from submitting the form
                alert("Button " + $(this).val() + " clicked")
            })
        })
    </script>
    <style type='text/css'>
        #myform {
            padding: 30px;
            width: 330px;
            margin: 20px auto;
            border: 1px solid blue;
            text-align: center;
        }
    </style>
</head>
<body>

    <form id='myform' >
        <button class='form-button' name='form-button' value='1'>Button 1</button>
        <button class='form-button' name='form-button' value='2'>Button 2</button>
        <button class='form-button' name='form-button' value='3'>Button 3</button>
        <br><br>
        <button>Submit</button>
    </form>
</body>
</html>

 

Link to comment
Share on other sites

@kicken  Am I able to do this with .addEventListener ?

I've tried several alterations of the following with no success.

var inputs = document.getElementsByTagName('input');

for(var i = 0; i < inputs.length; i++) {
    if(inputs[i].type == 'submit') {
        inputs.addEventListener("click", alert(inputs[i].value);
    }
}

 

Link to comment
Share on other sites

Yes, see Barand's example.  The jQuery bits can be replaced with their plain DOM equivalents.

window.addEventListener('DOMContentLoaded', function(){
	document.querySelectorAll('.form-button').forEach(function(btn){
		btn.addEventListener('click', function(e){
			e.preventDefault();
			alert('Button ' + e.currentTarget.value + ' clicked');
		});
	});
});

 

Link to comment
Share on other sites

  • Solution
13 hours ago, phppup said:
<form onsubmit="return myFunc()">

myFunc displays a confirmation box after a button is clicked.

Not quite. Yes, it's displaying the confirmation after you click the button, but it's not displaying it because you clicked the button. What's happening is that you clicked the button (event #1) and then the button, having no other behavior imposed on it to override the default, causes the form to submit (event #2), and that shows the confirmation.

Additionally, "srcElement" is old, and what you should be using instead of it is "target". And that name communicates the purpose better: it isn't the "source element" of an event, which suggests that it's some element responsible for the event, but rather it's the target of the event - the thing the event is addressing.
It's a distinction that matters because of how events work and the fact that you can - and will, if you're not careful - receive events for child elements.

So the target (aka srcElement) during the onsubmit is going to be the form. Not whatever thing that you interacted with that set about the chain of events causing the form to be submitted, but the form the event is associated with.
Or another way to think about it is, your code is paying attention to the form being submitted when you actually wanted to pay attention to a button being clicked, and that mismatch is your problem.

But anyway, that "receive events for child elements" thing I said earlier is useful because it means you have a way to listen for a click event on any button in the form by listening to the form itself. That means you don't have to loop over the form's buttons, and you can use a single event handler.
jQuery makes doing this easy because you can tell it to (1) listen to the form (2) for a click event (3) triggered by a button.

$("#myform").on("click", "button.form-button", () => { ... });

Native DOM only does the first two parts so you have to handle the third yourself, which isn't hard since .matches exists.

document.querySelector("#myform").addEventListener("click", (e) => {
  if (e.target.matches("button.form-button")) {
    // e.target is the button, e.currentTarget is the form
  }
});

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.