0

I found a thread, Change an element's 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!

Community
  • 1
  • 1
Kyle
  • 1

3 Answers3

1

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

azatoth
  • 2,379
  • 15
  • 18
1

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
  • 709
  • 5
  • 12
0

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.

indianwebdevil
  • 4,879
  • 7
  • 37
  • 51
  • Thanks for that, but I can't get it to work. I've copied it, changed the input elements to buttons, and added my "selected" & "notselected" CSS styles, but nothing happens when I click the buttons. I'll just keep at it. – Kyle Jun 23 '10 at 14:21
  • Did you change onfocus event to onclick. – indianwebdevil Jun 25 '10 at 02:39
  • I have checked that. It works. I am sure browser doesn't discriminate human beings. – indianwebdevil Jun 25 '10 at 14:07