Joel G Mathew
Joel G Mathew

Reputation: 8061

Using HTML attributes in javascript

I am a beginner in javascript. I'm trying to add a function to generate new form elements using javascript, on a page that's generated in php.

The code works in creating new <tr>, <td>, <input type="text"> html elements. However when I try to create buttons using css styles, I find that the styles are lost from the tags.

if(document.createElement) 
var tr = document.createElement("tr");
var input = document.createElement("input");
// If NS is passed, should become NS[2] etc
input.id = field+"["+count+"]";
input.name = field+"["+count+"]";
input.type = "text"; //Type of field - can be any valid input type like text,file,checkbox etc.

var td=document.createElement("td");
var newContent = document.createTextNode("NS");
td.appendChild(newContent);

tr.appendChild(td);     
td=document.createElement("td");        
td.appendChild(input);
tr.appendChild(td);                 

var btnDel=document.createElement("a");
btnDel.class="btn btn-primary";
btnDel.onclick = "addField(\'nameservers\',\'NS\',10);" ;


var btnText=document.createElement("span");
btnText.class="btn-label";
btnText.innerHTML="Add";


btnDel.appendChild(btnText);        
td.appendChild(btnDel);
tr.appendChild(td);         
field_area.appendChild(tr);

}

The produced code shows:

<a><span>Add</span>
</a>
</td>

instead of what I expect:

<a onclick="addField('nameservers','NS',10);" class="btn btn-primary">
<span class="btn-label">Add     
</span>
</a>

What am I doing wrong? What's the proper way of passing all html attributes using the script?

Upvotes: 3

Views: 116

Answers (2)

christopher
christopher

Reputation: 27336

For the on click

Instead of trying to output this into the HTML, why not do this in pure Javascript, using the addEventListener method?

element.addEventListener('click', function() {

    addField('nameservers','NS',10);

    }, false);

This approach is known as non-obtrusive Javascript, and it's actually quite a desirable attribute when developing a website.

For the class

As mentioned, use className and not class.

class usually precedes the declaration of as new class, and can't be used like an attribute, in the same way that you can't call a variable var.

Upvotes: 2

Ivan Chernykh
Ivan Chernykh

Reputation: 42166

Use className= instead of class=. So it will be like:

btnDel.className="btn btn-primary";

It is because the class word is reserved word in JavaScript.

Upvotes: 2

Related Questions