Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 849
Joel G Mathew Avatar asked Jul 07 '26 21:07

Joel G Mathew


2 Answers

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.

like image 177
christopher Avatar answered Jul 10 '26 10:07

christopher


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.

like image 32
Ivan Chernykh Avatar answered Jul 10 '26 12:07

Ivan Chernykh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!