Chris
Chris

Reputation: 13

Wondering why my onlclick() runs instantly

I'm creating a filter where after you've selected what you want to filter I create span tag with your selection. My end goal is that when you click on the span tag it will be removed from the list. Problem with a simple test function that changes the text of the span on click, the function is being called as soon as the span is created and instead of when it's clicked on

<!DOCTYPE html>
<html>
<body>
    <form>
        <select id="Catergories">
            <option value="blank"></option>
            <option value="country">Country</option>
            <option value="city">City</option>
            <option value="LastName">Last Name</option>
            <option value="company">Company</option>
        </select>


        <label>Enter filter here: </label><br>
        <input type="text" id="namehere"><br>

        <div class="col-md-6">
            <button type="button" onclick="displayname()">Add Filter</button>
        </div>




        <div id="demo"></div>
    </form>
</body>
</html>
<script>
    var filterCategory = [];
    var filterValue = [];
    function displayname() {
        filterCategory.push(document.getElementById("Catergories").value);
        filterValue.push(document.getElementById("namehere").value);
        var span = document.createElement('span')
        span.id = document.getElementById("Catergories").value + "_" + document.getElementById("namehere").value;
        span.style.width = 500;
        span.style.height = 500;
        span.style.backgroundColor = "red";
        span.innerHTML = "Category: " + document.getElementById("Catergories").value + " Filter value: " + document.getElementById("namehere").value;
        document.getElementById("demo").appendChild(span);
        span.onclick = "deleteSpan(span)";

    }

    function deleteSpan(element)
    {
        element.innerHTML = "test";
    }

</script>

Upvotes: 0

Views: 62

Answers (3)

user2377528
user2377528

Reputation:

Change this line

span.onclick = "deleteSpan(span)";

To

span.onclick = deleteSpan;

Demo

Upvotes: 0

bool3max
bool3max

Reputation: 2865

When you want to assign a function to any kind of a handler (onclick, onkeypress, etc...), you need to exclude the braces (). Whenever you have braces next to a function name, you're executing it immediately. So in this case, you'd do :

 span.onclick = deleteSpan;

Now, you can't pass arguments to your function, but that can be easily fixed using function expressions.

span.onclick = function(){
    deleteSpan(span);
}

Upvotes: 4

Jonas K&#246;ritz
Jonas K&#246;ritz

Reputation: 2644

As Matt already wrote, remove the parenthesis behind the function name in your onclick. If you use parenthesis JavaScript will evaluate the function aka run it to get the return value, which should be a the function to use as the onclick handler.

Upvotes: 0

Related Questions