Using HTML attributes in javascript - 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?

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.

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.

Related

Using Javascript to write HTML inputs which call Javascript functions

I'll give you an example of what I'm trying to do.
In Javascript:
document.innerHTML += "<input type='button' id='moveButton' value='a' onclick='webInput('a');'>"
The problem is that the html being written has two levels of quotes, and I can't figure out how to format the second level of quotes here:
webInput('a')
In my Javascript file, I have one function write the inputs into the HTML at the end of the function, then clicking the inputs calls the next function, until eventually the inputs are rewritten.
I know the answer probably has something to do with Escape Characters, but I was confused as to how to format them because the text is being passed back and forther between Javascript and HTML, which use different Escape Characters.
You can create your button within the javascript code and define the method therein.
var button = document.createElement('button');
button.addEventListener('click',function(){
doSomething();
});
//This method adds your button to body
document.body.appendChild(button)
If you have requirements to add this as string to the document, you need to escape quotes:
"<input type='button' id='moveButton' value='a' onclick='webInput(\"a\")'>"
great answer with rules for escaping here: https://stackoverflow.com/a/16134942/5727598
Also, you should use innerHtml property for element in which you want to pass your string but be sure it will remove all content there;
If no requirements, create button and upend to the body:
var input = document.createElement('input');
input.type = 'button';
input.id = 'moveButton';
input.value = 'a';
button.addEventListener('click', function(){
webInput(this.value); //if you need to pass input value as parameter
})
document.body.appendChild(input);

JavaScript - append() not appending a button, but text

Example:
var buttonHTML = "<button>MyButton</button>";
document.getElementById("myDiv").append(buttonHTML);
In this case, the function ends up appending the text into the div.
However, if I do the same with JQ:
$("#myDiv").append(buttonHTML);
In this case it will actually append the button.
Now, for various reasons, I have to use plain JS (not JQ).
Anyone have any ideas?
I am not sure how it worked with you and appended the element as text here, because there is no .append function in pure JS
But I agree with what #Sam Judge said in his answer,and also want to mention that you can do it using javascript without creating nodes one by one using javascript function Element.insertAdjacentHTML()
insertAdjacentHTML() parses the specified text as HTML or XML and
inserts the resulting nodes into the DOM tree at a specified position.
It does not reparse the element it is being used on and thus it does
not corrupt the existing elements inside the element. This avoiding
the extra step of serialization make it much faster than direct
innerHTML manipulation.
And there is another option to do the same using the .innerHTML but for sure you will need to save what's already inside to do the append effect.
This is because your var buttonHTML is just a string of text, if you append it as a child, it will create a DOM textNode, rather than an elementNode. What you want to do instead is something along the lines of the following :
var buttonHTML = document.createElement("button");
var buttonText = document.createTextNode("MyButton");
buttonHTML.appendChild(buttonText);
document.getElementById("myDiv").appendChild(buttonHTML)
you can try this code
function myFunction() {
var myButton= document.createElement("button");
myButton.style.width = "100px";
myButton.style.height = "30px";
myButton.style.background = "grey";
myButton.style.color = "white";
myButton.innerHTML = "MyButton";
document.getElementById("demo1").appendChild(myButton);
}
<button type="button" onclick="myFunction()">create another button</button>
<p id="demo1"></p>

Invisible TextNode in JS/DOM

I have JS code like this:
var option = document.createElement("input");
option.id = "id";
option.type = "radio";
var txt = document.createTextNode("sample");
option.appendChild(txt);
but this "sample" is invisible on the site. HTML structure is like this (in Firebug):
<form id="answers"><input type="radio" id="id">sample</input></form>
but in default firefox inspector is:
<form id="answers"><input type="radio" id="id"></input></form>
I've tried with innerHTML but there is the same problem. I just don't see anything between <input> tags.
What are your suggestions?
You create the elements but do not append them to the form. You should use something like this:
document.getElementById('answers').appendChild(option);
In this way you will append the newly created option element to the form with id "answers".
Have in mind that is is conceptually wrong to have text inside of a input type radio!

Is there anyway to assign custom property for html element in it's tag? Need pure html + js solution

Maybe this is weird, but this is what I need.
For example, we can do this:
var elem = document.getElementById("some_id");
if ("asd" in elem)
alert(elem.asd); // and this in second pass
else
elem.asd = "dsa"; //this will be executed first
I want something like this:
<input type = "button" value = "test btn" asd = "something" />
But this does not work. maybe there is some other way?
I really can't use body.onload to assign needed things.
Don't create non-standard expando attributes. HTML 5 introduces the data-* attribute set which is designed for adding custom data to HTML elements.
<input type="button" value="test btn" data-asd="something">
You can then access them through the dataset property.
var button = document.querySelector('input');
alert(button.dataset.asd);
If you want to support old browsers, you can use getAttribute:
var button = document.querySelector('input');
alert(button.getAttribute('data-asd'));
Or a library with a compatibility routine, such as jQuery:
var button = $('input');
alert(button.data('asd'));
Your HTML is good enough. But for accessing attribute you should say like bellow.
var attr = elem.getAttribute("asd");
alert(attr);

Add a row to a table in Javascript that contains input classes

Im trying do this basically:
var tr = document.createElement("tr");
var td = document.createElement("td");
td.appendChild(document.createTextNode('<input class="param" type="text" name="dummy" value="fred"/>'));
tr.appendChild(td);
but it just displays the input... as normal text, how do I insert it so that it works as i require..?
im guessing its the createTextNode that needs to be changed?
Cheers
You could either
td.innerHTML = '<input class="param" type="text" name="dummy" value="fred"/>';
or
var ip = document.createElement( 'input' );
ip.className = 'param';
ip.type = 'text';
ip.name = 'dummy';
ip.value = 'fred';
td.appendChild( ip );
EDIT
ie won't allow the type of a form element to be changed dynamically. I'm pretty sure this only applies when the element already has a type and has already been inserted into the DOM. Best to check though. If it doesn't work use method 1
Try using innerHtml property of element.
That is try using td.innerHtml = "<input ...../>"
Meouw has the right idea. You're creating a text node in your example, and what needs to be done is create a dom element.
This is also another case where jQuery could simplify your code. What you were attempting to do by adding the element as an html string can be done with the jQuery html( val ) function:
http://docs.jquery.com/Attributes/html#val
Basically, to apply this technique with your given example, you would include the jQuery library on your page and write the following line:
$("#someTable").html('<tr><td><input class="param" type="text" name="dummy" value="fred"/></td></tr>');
You can also create any html element on the fly and string together attributes and event handlers in one line as in the following example:
http://www.peterbe.com/plog/creating-dom-element-with-jquery
var textbox = $("<input type='text'></input>").attr('name','dummy').addClass('param').val('fred');
$("#someTableCell").append(textbox);

Categories