views:

73

answers:

3

I found a thread, http://stackoverflow.com/questions/195951/change-an-elements-css-class-with-javascript, that is along the lines of what I'm going for, but I don't know how to implement it.

I have a page with 4 input buttons and two CSS styles: "Selected" and "notSelected". One button will be hard coded initially as "Selected". When the user clicks another button, I'd like to programatically iterate through all the buttons (the number of buttons on each page will be between 2 and 10), set the clicked button's class to "Selected", and make sure all the other buttons are set to "notSelected".

I've got the logic down, but I've never done anything with JavaScript before, so I haven't the slightest idea about how to do this. If someone knows of a tutorial/piece of code already out there that does this, please point me in the right direction.

Thanks a ton!

+1  A: 

You can go the easy way and use a framework like jQuery that does the hard work for you

azatoth
+1  A: 

As you are new to JavaScript, this might be a bit much, but have you considered using jquery? Take a look at toggleClass(): http://api.jquery.com/toggleClass/

Spencer
A: 

Hi just made a quick script, Hope that helps you. Let me know if you find any problem with the script.

I am using focus event and input box, you may change it as needed.

function doSelect( obj ){ var mylist=document.getElementById("formDiv") var inputItems= mylist.getElementsByTagName("input"); for (i=0; i < inputItems.length; i++){ document.getElementById(inputItems[i].id).className = "Notselected"; } document.getElementById(obj.id).className = "selected"; }

Have a form tag within the div tag id="formDIV"

Have few input tags of type text and onfocus="doSelect(this)"

<body> <div id="formDiv"> <form name="testform"> <input type="text" name="tx1" id="text1" onfocus="doSelect(this)"/> <input type="text" name="tx2" id="text2" onfocus="doSelect(this)"/> <input type="text" name="tx3" id="text3" onfocus="doSelect(this)"/> <input type="text" name="tx4" id="text4" onfocus="doSelect(this)"/> <input type="text" name="tx5" id="text5" onfocus="doSelect(this)"/> </form> </div> </body>

this should help.

nepsdotin
Kyle
Did you change onfocus event to onclick.
nepsdotin
I have checked that. It works. I am sure browser doesn't discriminate human beings.
nepsdotin
Here is the working demo http://neps.in/code/click.html
nepsdotin