Sam San
Sam San

Reputation: 6903

javascript change class of multiple inputs onclick

I wanted to change the class of some inputs of my form having a class='mypost_title' at onclick.

I tried this and it doesn't work

<a href='' onclick='popup_mypost(e)'>change me</a>
<a href='' id=edit-href onclick='popup_mypost(e)'>back me</a>

<script>
    function popup_mypost(e) 
    {
        var inputs = document.getElementsByClassName("mypost_title");
        for(var i = 0; i < inputs.length; i++) 
            {
            inputs[i].className = "change";
            }

        var edit_href = document.getElementById("edit-href");
        edit_href.onclick = function()
        {
            var inputs = document.getElementsByClassName("change");
            for(var i = 0; i < inputs.length; i++) 
                {
                inputs[i].className = "mypost_title";
                }
        }
    }
</script>

Upvotes: 0

Views: 1580

Answers (3)

Undefined
Undefined

Reputation: 11431

For a jQuery approach see my code below. Personally I find this easier to read and follow. Also this will work fully cross-browser!

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>

$(document).ready(function() {
    $(".mypost_title").each(function() {
        $(this).addClass("change");
    });
});

</script>

I have had a quick check for cross-browser compatibility with getElementsByClassName and the results have been quite surprising. IE8 and below do not support this! Please see this table here for the tests.


Edit

I am guessing a little at what you are looking for here. Here is my interpretation:

When one of these div's is clicked you want to add the change class to the clicked one and remove the change class from all the others?

In which case you would do:

//This focus event will fire when the user "focuses" on an input
$(".mypost_title").focus(function() {
    $(this).removeClass("mypost_title");
    $(this).addClass("change");
});

//This blur event will fire when the user clicks outside the input, or tabs out etc
$(".mypost_title").blur(function() {
    $(this).removeClass("change");
    $(this).addClass("mypost_title");
});

Upvotes: 1

Ketan Modi
Ketan Modi

Reputation: 1800

Change this line and try:

var inputs = document.getElementsByClassName("mypost_title");

Upvotes: 0

Jamiec
Jamiec

Reputation: 136134

The method is getElementsByClassName - ie, you missed an s!

Docs: https://developer.mozilla.org/en-US/docs/DOM/document.getElementsByClassName

Upvotes: 3

Related Questions