generate inputes automatically PUREj-s - javascript

I'm trying to generate inputs automatically according to user's input.
For example if he enter 2 then it will automatically generate:
2 x (select option(values : M-Mr) + text input + text input + date
input )
I already made the 3 last inputs(text-text-date) , I faced a probleme with the select option
Thank you!!
<input type="text" id="member" name="member" value="">Number of members: <br/>
Fill Details
<div id="container"/>
and this is funtion :
function addFields(){
var number = document.getElementById("member").value;
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
container.appendChild(document.createTextNode("Member " + (i+1)));
var input = document.createElement("input");
var input1 = document.createElement("input");
var input2 = document.createElement("input");
input.type = "text";
input1.type = "text";
input2.type = "date";
container.appendChild(input);
container.appendChild(input1);
container.appendChild(input2);
container.appendChild(document.createElement("br"));
}
}
for the snipped code :
https://jsfiddle.net/f4hptzsy/

This example adds the select element with two options included.
See comments in the code for explanation of how it works.
// Identifies existing HTML elements
const member = document.getElementById("member");
const container = document.getElementById("container");
// Calls `useNumber` when `member` changes
member.addEventListener("change", useNumber);
// Defines `useNumber`
// (The listener can automatically access the triggering event)
function useNumber(event){
// The element where the event happened is the `target`
const memberValue = event.target.value;
// Calls `addFields` if the value can be used as an integer
const num = parseInt(memberValue);
if(num){
addFields(num);
}
}
function addFields(number) {
// Clears container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
// Creates new elements and adds them to container
for (i = 0; i < number; i++) {
container.appendChild(document.createTextNode("Member " + (i + 1)));
// Defines a select element
const dropdown = document.createElement("select");
// Enumerates options and adds them to the select element
let options = ["M", "Mr"];
for (let option of options){
optionElement = document.createElement("option");
optionElement.value = option;
optionElement.innerHTML = option;
dropdown.appendChild(optionElement);
}
var input = document.createElement("input");
var input1 = document.createElement("input");
var input2 = document.createElement("input");
input.type = "text";
input1.type = "text";
input2.type = "date";
// Adds the select element to the page
container.appendChild(dropdown);
// Adds other inputs to the page
container.appendChild(input);
container.appendChild(input1);
container.appendChild(input2);
container.appendChild(document.createElement("br"));
}
}
<input id="member" />
<br />
<div id="container"></div>
EDIT:
The useNumber function just tests if the input is a valid integer before calling addFields.
It would be fine to omit this function and have addFields itself be the event listener instead, like:
// Identifies existing HTML elements
const member = document.getElementById("member");
const container = document.getElementById("container");
// Calls `addFields` when `member` changes
member.addEventListener("change", addFields);
function addFields(event) { // We name the triggering event "event"
// Gets value of element where the `change` event happened
const memberValue = event.target.value;
// Converts value to a number
const number = parseInt(memberValue);
// Makes sure conversion succeeded before proceding
if(number){
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i = 0; i < number; i++) {
container.appendChild(document.createTextNode("Member " + (i + 1)));
// Defines a select element
const dropdown = document.createElement("select");
// Enumerates options and adds them to the select element
let options = ["M", "Mr"];
for (let option of options){
optionElement = document.createElement("option");
optionElement.value = option;
optionElement.innerHTML = option;
dropdown.appendChild(optionElement);
}
var input = document.createElement("input");
var input1 = document.createElement("input");
var input2 = document.createElement("input");
input.type = "text";
input1.type = "text";
input2.type = "date";
// Adds the select element to the page
container.appendChild(dropdown);
container.appendChild(input);
container.appendChild(input1);
container.appendChild(input2);
container.appendChild(document.createElement("br"));
}
}
}
<input id="member" />
<br />
<div id="container"></div>

Related

Is there a reason why my check mark box won't be selected when I click the span tag?

//init function
function init() {
createTaskElements();
}
//create elements and add them to the unordered list
//set attributes
function createTaskElements() {
const arrChores = ["Walk the dog", "Set dinner table", "Load dishwasher", "Empy Dishwasher", "Clean dinner plates"];
for (var i = 0; i < arrChores.length; i++) {
var task = document.createElement("LI");
task.id = "task";
var input = document.createElement("INPUT");
input.type = "checkbox";
input.id = "chore";
var span = document.createElement("SPAN");
span.innerHTML = arrChores[i];
span.addEventListener("click", crossClick);
task.appendChild(input);
task.appendChild(span);
task.addEventListener("click", crossOut);
document.getElementById("itemsList").append(task);
}
}
//set the class name of the list item whenever it is clicked to completed
function crossOut() {
this.className = "completed";
}
function crossClick() {
}
W
hat I want to do when I click the span tag it checks the check box next to the element, but it isn't working.
I know the .checked method, but I'm not sure how I would get my function to work.
Replace
var span = document.createElement("SPAN");
span.innerHTML = arrChores[i];
with
const label = document.createElement("label");
label.textContent = arrChores[i];
label.htmlFor = input.id;
You don't need to add any Javascript behaviour to that label as it already comes with the functionality you ask for.

Not able to replace checkboxes Javascript

I am creating a mozilla add on for a web page. Using the attached Javascript code I am able to create checkbox. The checkbox should replace with other checkbox depending on the selected value in dropdown. Onclick on dropdown I am calling fun_sub_cat function which is creating checkbox and also replacing but it replace only once. For eg: If there are 2 option in dropdown 1 and 2, Selecting option 1 checkbox values should 1,2,3 and for option 2 checkbox values should be a,b,c.
On Click function it creates checkbox and changing the value for the first time replaces the checkbox value as well however when I click 3rd time on dropdown or change the value, it does not work. It attains the 2nd time changed checkbox values.
var k = 0;
function fun_cat_sub() {
console.log("Value Changed");
var Myarry = "";
if(document.getElementById('sub_cat').value == 'Password Reset'){
Myarry = check_list1;
if(k == 0){
console.log("creating checkbox for the first time");
k = k+1;
for (var i = 0; i < Myarry.length; i++) {
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.id = "checkBox"+i;
checkbox.value = Myarry[i];
checkbox.class = "_class";
checkbox.appendAfter(br_3);
var lab_chk = document.createElement('label');
lab_chk.innerHTML = Myarry[i];
lab_chk.id = "lab_chk"+i;
lab_chk.value = Myarry[i];
lab_chk.style.marginLeft = "10px";
lab_chk.appendAfter(checkbox);
document.createElement('br').appendAfter(lab_chk);
}
}
else if(k != 0){
console.log("I am in 1st Loop");
checking(Myarry);
}
}
else {
Myarry = check_list2;
console.log("I am in 2nd Loop");
checking(Myarry);
}
}
function checking(Myarry){
console.log(Myarry.length);
for (var i = 0; i < Myarry.length; i++) {
var old_chk = document.getElementById('checkBox'+i);
var new_chk = document.createElement("input");
new_chk.type = "checkbox";
new_chk.id = "checkBox"+i;
new_chk.value = Myarry[i];
old_chk.parentNode.replaceChild(new_chk, old_chk);
var old_lab_chk = document.getElementById('lab_chk'+i);
var new_lab_chk = document.createElement('label');
new_lab_chk.innerHTML = Myarry[i];
new_lab_chk.style.marginLeft = "10px";
old_lab_chk.parentNode.replaceChild(new_lab_chk, old_lab_chk);
}
}

Dynamic checkbox onclick is not working

I am creating dynamic checkboxes and want a function to be called every time I check any checkbox. The checkbox looks good but my onclick event does not work. Also if I do not pass 'this' to my function, my function gets called on load as well.
Below is my code:
for(var i=0; i<options.length; i++) {
var op = options[i].new_name;
var label = document.createElement("label");
var description = document.createTextNode(op);
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.name = "multiselectCheckbox";
checkbox.value = op;
checkbox.onclick= "getCheckedValues(this)";
label.appendChild(checkbox);
label.appendChild(description);
document.getElementById("multiselect").appendChild(label);
document.getElementById("multiselect").appendChild(document.createElement("br"));
}
Please let me know what am I doing wrong here.
The below snippet works. I suppose this is what you want to do. You need not pass this in the function and also call the function without ""
var options = [{new_name: "1"}, {new_name: "2"}]
for(var i=0; i<options.length; i++) {
var op = options[i].new_name;
var label = document.createElement("label");
var description = document.createTextNode(op);
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.name = "multiselectCheckbox";
checkbox.value = op;
checkbox.onclick = getCheckedValues;
label.appendChild(checkbox);
label.appendChild(description);
document.getElementById("multiselect").appendChild(label);
document.getElementById("multiselect").appendChild(document.createElement("br"));
}
function getCheckedValues() {
alert(this.value);
}
<div id="multiselect"></div>

Pass contextual variable to onclick event handler as argument

*This is happening inside a larger block of code, in a for loop. See end of post for entire loop.
I've read all of the posts that seem to be about this subject, but I'm still lost.
I'm trying to assign an onclick event to a checkbox. The function being assigned to the onclick event needs to have access to a variable that is available in the scope where the checkbox is defined (idvariable).
var idvariable = parentChildList[i].children[j]["subjectid"];
var input = document.createElement("input");
input.type = "checkbox";
input.value = "";
input.onclick = function () {
return clicked(idvariable);
};
function clicked(id) {
alert(id);
};
I've tried every variation of inline and named functions, but I can't figure out how to give the clicked function access to idvariable. In this example above, the value of that variable is undefined.
Or, if I try it with this way:
var input = document.createElement("input");
input.type = "checkbox";
input.value = "";
var idvariable = parentChildList[i].children[j]["subjectid"];
input.onclick = function (idvariable) {
return clicked(idvariable);
};
function clicked(id) {
alert(id);
};
I get an alert that says [object MouseEvent]. Same with the following where I removed the () from the method name I'm assigning to the onclick event:
var idvariable = parentChildList[i].children[j]["subjectid"];
input.onclick = function () {
return clicked;
}(idvariable);
function clicked(id) {
return alert(id);
};
*entire loop:
for (var i = 0; i < parentChildList.length; i++) {
var row = table1.insertRow(-1);
var cell = row.insertCell(0);
cell.innerHTML =
"<h4 class=\"panel-title\"><a data-toggle=\"collapse\" data-parent=\"#accordion\" href=\"#collapse" + i + "\">" + parentChildList[i]["title"] + "</a></h4>";
if (parentChildList[i].children.length > 0) {
var row2 = table1.insertRow(-1);
var cell2 = row2.insertCell(0);
var table2 = document.createElement("table");
table2.className = "collapse";
table2.id = "collapse" + i;
cell2.appendChild(table2);
for (var j = 0; j < parentChildList[i].children.length; j++) {
var row3 = table2.insertRow(-1);
var cell3 = row3.insertCell(0);
var div = document.createElement("div");
div.className = "checkbox";
var label = document.createElement("label");
label.innerText = parentChildList[i].children[j]["title"];
var input = document.createElement("input");
input.type = "checkbox";
input.value = "";
input.setAttribute('subj', idvariable);
var idvariable = parentChildList[i].children[j]["subjectid"];
alert(idvariable);
input.onclick = function () {
return clicked(this.getAttribute('subj'));
};
function clicked(id) {
return alert(id);
};
cell3.style.padding = "0px 0px 0px 10px";
cell3.style.fontsize = "x-small";
cell3.appendChild(div);
div.appendChild(label);
label.insertBefore(input, label.childNodes[0]);
}
}
}
onclick handler receives Event object. If a handler attached as elem.onclick=handler then the element is available inside the handler as this. So this is workaround.
var idvariable = parentChildList[i].children[j]["subjectid"];
var input = document.createElement("input");
input.type = "checkbox";
input.value = "";
input.setAttribute('data-subj', idvariable);
input.onclick = function () {
return clicked(this.getAttribute('data-subj'));
};
function clicked(id) {
alert(id);
};
You will have to append the checkbox to some existing element first, using the following code.
var element = document.getElementById("one").appendChild(input);
Then you can get the parent by using something like the following...
var x = document.getElementById("someId").parentElement;
where x will contain the parent element.
This link https://stackoverflow.com/a/9418326/886393 is about custom data in an event (custom event). Hope that helps.
Thanks
Paras

Checkbox to change textdecoration input field

With javascript, i want my checkbox to change the text decoration of an input text field.
So when it's checked, the text in the input text field turns bold.
Remember i'm learning so i'm not a pro as you guys ;)
I thought something like this;
var checkbox = create("input");
checkbox.type = "checkbox";
checkbox.id = "checkboxId" + counter;
div.appendChild(checkbox);
checkbox.onClick="boldChange(this)"
var input = create("input");
input.type = "input";
input.id = "inputId" + counter;
div.appendChild(input);
function boldChange()
var boldgroup = document.getElementsByName(el.name);
for (var b=0; boldgroup[b]; ++b)
inputId.style.textDecoration = boldgroup[b].checked ? 'bold' : 'none';
}
How can i make this work?
Thank you so much in advance
Here is a working JSFiddle example based on your code above: Link to example
Code snippet: (place below </body> so that all of DOM is loaded)
<script>
var div = document.getElementById('div'),
counter = 0;
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = "checkboxId" + counter;
div.appendChild(checkbox);
checkbox.onclick = boldChange;
counter++;
var input = document.createElement("input");
input.type = "text";
input.id = "inputId" + counter;
div.appendChild(input);
function boldChange() {
input.style.fontWeight = (checkbox.checked)?'bold':'normal';
}
</script>

Categories

Resources