7

On the press of a div (which I made into a button with other code) I would like the following code:

<div id="w1" name="w1-0" onclick="weekclick(id)">1<br /></div>

...for the name to change from name="w1-0" to name="w1-1"

I'm using the following JavaScript:

function weekclick(id)
{    
 document.getElementById(id).input.name = "w1-1";
}

When I alert the id's name attribute, it says it is undefined. What do?

4
  • 5
    Div elements do not have a name attribute, and DivElementNode objects do not have an input property. Div elements are designed to be generic containers, if you want a button, then use a <button>. Commented Feb 25, 2012 at 19:47
  • 7.5.4 Grouping elements: the DIV and SPAN elements Commented Feb 25, 2012 at 19:51
  • What is the name attribute used for? What's it's purpose on the page? Commented Feb 25, 2012 at 19:55
  • @JaredFarrish It's used to pass values to the server (in the format name=value), via GET or POST methods on a FORM. Commented Feb 11, 2020 at 12:39

2 Answers 2

22

see code below:

<div id="w1" name='w1-0' onclick="weekclick(id)">1<br /></div>
<div onclick="weekclick('w1');">click me</div>​

<script type="text/javascript">
function weekclick(id) {    
    document.getElementById(id).setAttribute("name","w1-1");
}​
</script>

link to fiddle - http://jsfiddle.net/TH9C2/

(remove the alert line from the fiddle - it is just there to show you that it works)

Sign up to request clarification or add additional context in comments.

2 Comments

"fiddle attached" Why not "See code below (with link to fiddle)."?
changed the answer - satisfied now? :)
2

first of all change your call in the html to this user this.id and not just id:

<div id="w1" name='w1-0' onclick="weekclick(this.id)">1<br /></div>

than make your js like this (remove .input and use setAttribute):

function weekclick(id) {    
    document.getElementById(id).setAttribute('name', 'w1-1');
}

EDIT or you you change your call in html to this:

weekclick(this)

and your js function have to be like this:

function weekclick(domElement) {    
    domElement.setAttribute('name', 'w1-1');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.