Dynamic creation of radio button in Html for IE - javascript

Can anybody give me a working code for creating dynamic radio buttons in html (and javascript) which works in IE, Firefox and Chrome?
I saw a lot of codes in the internet, but none of them worked for me.
I also need them to have a label. And I don't want to use Jquery.
Tried this code:
function test() {
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute('type', 'radio');
element.setAttribute('value', 'source');
element.setAttribute('name', 'source');
element.setAttribute('id', 'source_id');
var foo = document.getElementById("divTxt");
foo.appendChild(element);
var newlabel2 = document.createElement("Label");
newlabel2.for = "source_id";
newlabel2.innerHTML = "first name ";
foo.appendChild(newlabel2);
}

var radio1 = document.createElement('input');
radio1.id = 'myRadioId1';
radio1.type = 'radio';
radio1.name = 'radioGroup';
radio1.value = 'someValue1';
var radio2 = document.createElement('input');
radio2.id = 'myRadioId2';
radio2.type = 'radio';
radio2.name = 'radioGroup';
radio2.value = 'someValue2';
var label1 = document.createElement('label');
label1.htmlFor = radio1.id;
label1.innerHTML = 'label for radio1';
var label2 = document.createElement('label');
label2.htmlFor = radio2.id;
label2.innerHTML = 'label for radio2';
Appending to container:
var container = document.getElementById('mydivid');
container.appendChild(radio1);
container.appendChild(label1);
container.appendChild(radio2);
container.appendChild(label2);
If you need radio group, you should give them same names. Here is fiddle

The main problem with the code (which you posted in a comment and I copied into the question) is that it contains only a function definition. The function is not called at all, so need to have a statement like test(). Moreover, the function postulates that there is an element with id=divTxt on the page, and that element must appear before the calling the function. The following code successfully creates a radio button element and its label and inserts them into an existing element on the page:
<!DOCTYPE html>
<title>Demo</title>
<div id=divTxt></div>
<script>
function test() {
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute('type', 'radio');
element.setAttribute('value', 'source');
element.setAttribute('name', 'source');
element.setAttribute('id', 'source_id');
var foo = document.getElementById("divTxt");
foo.appendChild(element);
var newlabel2 = document.createElement("Label");
newlabel2.setAttribute('for', "source_id");
newlabel2.innerHTML = "first name ";
foo.appendChild(newlabel2);
}
test();
</script>
(You cannot use the for property in JavaScript; the property name is htmlFor, but it is probably simpler to set the for attribute as above.)
However, radio buttons should always appear in groups, due to their nature, so you should use a function with some arguments to generate a set of radio buttons according to a common pattern. Like this:
<!DOCTYPE html>
<title>Demo</title>
<div id=divTxt></div>
<script>
function radio(name, value, text) {
var element = document.createElement("input");
var id = name + value;
element.setAttribute('type', 'radio');
element.setAttribute('value', value);
element.setAttribute('name', name);
element.setAttribute('id', id);
var foo = document.getElementById("divTxt");
foo.appendChild(element);
var newlabel2 = document.createElement("label");
newlabel2.setAttribute('for', id);
newlabel2.innerHTML = text;
foo.appendChild(newlabel2);
}
radio('sex', '0', 'male');
radio('sex', '1', 'female');
</script>
You should minimally enhance this by adding code that adds line breaks between the items, or preferably put each pair of a button and its label inside a div elemebt.

Related

Trying to print dynamic content and one variable is not being accessed at "onclick" event

var noOfPersons;
function printEmptyBoxes() {
noOfPersons = document.getElementById("NumberOfPeople").value;
var dynamicAttach = document.getElementById("dynamic_Content");
for(var i=0;i<noOfPersons;i++) {
var name = document.createElement("input");
var expenditure = document.createElement("input");
var button1 = document.createElement("input");
var button2 = document.createElement("input");
name.setAttribute("type", "text");
name.setAttribute("id", "person"+(i+1)+"");
expenditure.setAttribute("type", "text");
expenditure.setAttribute("id", "Expenditure"+(i+1)+"");
button1.setAttribute("type", "button");
button1.setAttribute("value", "+");
button1.setAttribute("onclick", 'document.getElementById("Expenditure"+(i+1)+"").value += "+"');
button2.setAttribute("type", "button");
button2.setAttribute("value", "=");
// button2.setAttribute("onclick", "x += eva);
dynamicAttach.appendChild(name);
dynamicAttach.appendChild(expenditure);
dynamicAttach.appendChild(button1);
dynamicAttach.appendChild(button2);
var brk = document.createElement("br");
dynamicAttach.appendChild(brk);
}
}
/*
It's showing uncaught reference error unable to access i on "onclick" but my i variable is getting accessed at both of id attributes I have created before that statement("person"+(i+1)+"");
*/
In your case, the code is not exactly the same way you look
'document.getElementById("Expenditure"+(i+1)+"").value += "+"'
I believe what you want is have Expenditure+(i+1) (after calculate i+1) as the ID, but since it is covered by a single quote (before document and at the end), it still treat Expenditure+(i+1) (before calculate i+1) as an actual ID.
The easy way for you to check this error is look at the color of string in your editor, you will easily see that those 2 color are not the same.
So, how to fix?
Simplest way, set the ID as a different variable and use it later on
var expID = "expenditure" + (i+1);
Furthermore, don't use setAttribute for onclick event. Use .onclick() instead
button1.onclick = function_name;
Have a loop through my simple code here:
http://jsfiddle.net/mankinchi/7x6z6hgr/

Newline added when appending elements to a div

The output of code below produces a line of text and then a button below the text.
How can I place the button beside the text?
var count = document.createTextNode('My text: ');
document.getElementById('container').appendChild(count);
var f = document.createElement('form');
f.setAttribute('method','POST');
f.setAttribute('action','test');
var text = document.createElement('input');
text.setAttribute('type','hidden');
text.setAttribute('name','text');
text.value = 'Hey! - hidden value';
var s = document.createElement('input'); //input element, Submit button
s.setAttribute('type','submit');
s.setAttribute('value','Hey!');
f.appendChild(text);
f.appendChild(s);
document.getElementById('container').appendChild(f);
s.onclick=function(){
f.submit();
};
jsFiddle: http://jsfiddle.net/bobbyrne01/hk0annoq/
The display attribute of form elements is set to block by default, which means that when they're created they'll skip one line within a paragraph. To solve this, one approach would be to make the form's display atrribute to inline or inline-block:
f.style.display = 'inline';
Here:
var f = document.createElement('form');
f.setAttribute('method','POST');
f.setAttribute('action','test');
f.style.display = 'inline';
Your updated fiddle here.
Update:
Expanding epascarello's answer, a more correct approach would be:
var f = document.createElement('form');
f.setAttribute('method','POST');
f.setAttribute('action','test');
// Create your label
var label = document.createElement('label');
// Set its text
var count = document.createTextNode('My Text: ');
var text = document.createElement('input');
text.setAttribute('type','hidden');
text.setAttribute('name','text');
text.value = 'Hey! - hidden value';
var s = document.createElement('input'); //input element, Submit button
s.setAttribute('type','submit');
s.setAttribute('value','Hey!');
// Append your text, hidden input and submit button to the label
label.appendChild(count);
label.appendChild(text);
label.appendChild(s);
// Append the label to the form
f.appendChild(label);
// Append the form to the container
document.getElementById('container').appendChild(f);
Because it gives the document better semantics.
What you have
<text node - inline>
<form - block - causes new line>
You would need to append it inside the form, not the container.
f.appendChild(count);
f.appendChild(text);
f.appendChild(s);
document.getElementById('container').appendChild(f);
You should also look at using a label element since that is how you are treating that text.
It's easier than what they say and no CSS needed, look at HERE
You just had to put 'count' inside the form rather than the container
f.appendChild(count);
instead of
document.getElementById('container').appendChild(count);

Change the onClick function to target the edit buttons

I have the following script
var counter = 0;
function appendText(){
var text = document.getElementById('usertext').value;
if ( document.getElementById('usertext').value ){
var div = document.createElement('div');
div.className = 'divex';
var li = document.createElement('li');
li.setAttribute('id', 'list');
div.appendChild(li);
var texty = document.createTextNode(text);
var bigdiv = document.getElementById('addedText');
var editbutton = document.createElement('BUTTON');
editbutton.setAttribute('id', 'button_click');
var buttontext = document.createTextNode('Edit');
editbutton.appendChild(buttontext);
bigdiv.appendChild(li).appendChild(texty);
bigdiv.appendChild(li).appendChild(editbutton);
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
document.getElementById('usertext').value = "";
counter++;
}
};
var makeAreaEditable = function(){
alert('Hello world!');
};
I want the makeAreaeditable function to work when the Edit button is pressed(for each of the edit buttons that are appended under the textarea).. In this state, the script, alerts me when i hit the Addtext button.
the following is the html. P.S. i need this in pure javascript, if you can help. thanks
<textarea id="usertext"></textarea>
<button onClick="appendText()">Add text </button>
<div id="addedText" style="float:left">
</div>
instead of:
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
you need to do this:
editbutton.onclick = makeAreaEditable;
the function's name goes without brackets unless you want to execute it
instead of obtaining the element from the DOM using document.getElementById('button_click')
you can use the editbutton variable already created. this object is the DOM element you are looking for
SIDE NOTE:
the standard way to do it is to add the onclick property before appending the element

add html text with javascript

i am adding a input file tag and a link using a javascript function, works great. Now i want to add also a radio button and a text whit this radio... i can add the radio whit no problems, but the text... idk how.
here is the code...
addCampo = function () {
nDiv = document.createElement('div');
nDiv.className = 'archivo';
nDiv.id = 'file' + (++numero);
nCampo = document.createElement('input');
nCampo.name = 'archivos[]';
nCampo.type = 'file';
a = document.createElement('a');
a.name = nDiv.id;
a.href = '#';
a.onclick = elimCamp;
a.innerHTML = ' Eliminar';
portada = document.createElement('input');
portada.name = 'portada';
portada.type = 'radio';
portada.value = '1';
nDiv.appendChild(nCampo);
nDiv.appendChild(portada);
// HERE I WANT A SIMPLE TEXT SAYING WHATS DOES THE RADIO =)
nDiv.appendChild(a);
container = document.getElementById('adjuntos');
container.appendChild(nDiv);
}
this is working just fine! the only thing i dont know is how to add text whitout tags...
You need
text = document.createTextNode('what the radio does');
nDiv.appendChild(text);
Although it's better to use a label, because then you don't have to sharp-shoot the radio button. In that case you'd need:
portada.id = 'portada';
text = document.createElement('label');
text.innerText = 'what the radio does';
text.for = 'portada';
nDiv.appendChild(text);
Edit: as mentioned in the comments, innerText is not necessarily supported by all browsers, sorry! Just use innerHTML instead, use textContent if you don't care about old versions of IE, or create a text node and add it to the label node.

Getting INVALID_CHARACTER_ERR: DOM Exception 5

I'm writing a simple to-do list. that a user input a text and the it's added as a checkbox. But i'm getting this error i have no idea what's it about
INVALID_CHARACTER_ERR: DOM Exception 5
window.onload = function(){
var textBox = document.getElementById("taskInput"),
submitBtn = document.getElementById("submit"),
taskPool = document.getElementById("todoTask");
submitBtn.addEventListener("click", function(){
var task = document.createElement("<input type=\"checkbox\">" + textBox.value + "</input>");
taskPool.appendChild(task);
});
}
document.createElement takes the tag name only as its parameter, you'll have to set the type and value after
var task = document.createElement("input")
task.type = "checkbox";
task.value = textBox.value;
Also input tags are empty, there are no closing tag or inner html, the value is set as an attribute in markup.

Categories