tags:

views:

80

answers:

3

I am a jQuery noobie, and have been trying to add a script to change the id of a div onClick.

Here is a jsfiddle example.

$(function accept() {
    $("div:scrollwrap").attr('scrollwrap','highlight');
});​

Thanks :)

+1  A: 

if you want to change the div with the id scrollwrap to have the id highlight:

 $(document).ready(function() {
   $("#checkbox2").click(function() {
        $("#scrollwrap").attr('id','highlight');
    });
 });

remember an ID is unique, so this should only affect one element. if you want to affect multiple use classes and the functions .addClass()/.removeClass()

Moak
Thanks, that worked, how do I add it to my onCLick function? `<input value="1" type="checkbox" name="salgsvilkar" ID="checkbox2" onclick="accept();" />`
Kyle Sevenoaks
@kyle-sevenoaks updated
Moak
A: 

this is how you change a ID:

$(function accept(){ //makes sure your document is ready
  $('div#scrollwrap').attr('id', 'highlight')
})

(i assume scrollwram is you ID)

meo
+2  A: 

The first parameter of attr should be the attribute name, not the current value:

$(function accept() {
    $("div#scrollwrap").attr('id','highlight');
});​

However, reading your jsFiddle code, you appear to have a class of highlight and not an ID. Here is my edited version with what I think you are trying to achieve.

Note that I have changed the following:

  • Made the .hightlight class more specific by adding the ID, otherwise the highlight style will not override the original.
  • Removed the inline onClick as you can do this within your script, which is considered best practice (see JS for the .click() addition)
  • Changed the JS function to toggle the class, as I assume it should be invalidated if the user deselects the checkbox.

More resources (jQuery docs):

akamike
Great! thanks very much for the answer and the resources!
Kyle Sevenoaks