Create input labels from "for" attribute, without changing HTML - javascript

Having an issue learning JavaScript in a college course. This is my last project and the problem I am having with the HTML code is creating an input field for a label without an id, it has a "for" element though. It cannot be created with JQuery or JSON.
So the HTML looks something like this:
<"label for="car">What car do you have? <"span class="required"><"/span><"/label">
So I was thinking I could create the input text field and add it to the DOM:
// Create the input field
var firstCar = document.createElement("input");
// Create the type node and store what the field will be text
var newType = document.createTypeNode("text");
// Create a new ID of car and attach it to the input
var newID = document.createIdNode("car")
/* put the created Element within the HTML with ["this determines which label it will be under"]:*/
var position = document.getElementByTagName("label")[1];
// Insert the element into the position
position.appendChild(firstCar);
I ran this and it says that TypeNode is not a function in my browser.

That's not how you set the type and id. Try this
var firstCar = document.createElement("input");
firstCar.type = "text"; // set the type
firstCar.id = "car"; // set the ID
var position = document.getElementsByTagName("label")[1]; // it should be getElements... not getElement...
position.appendChild(firstCar);

Related

Can't access property once selecting element

Can't get the title right. I am using jquery to create a textarea.
function build_form() {
// Clear all previous form elements
$('#form_content').html('');
// Grabs all elements that will be dynamically created
var elements = templates.types[$('#selectType')[0].selectedIndex].content.elements;
for (ele in elements){
var $div = $(document.createElement('div'));
$div.attr('class', 'div_form');
// Create description for input box
var $x = $(document.createElement('text'));
$x.html(elements[ele].description);
$div.append($x);
// Create input box itself
var $i = $(document.createElement(elements[ele].type));
$i.attr('placeholder', elements[ele].placeholder);
$i.attr('class', 'form_input');
if (elements[ele].value) {
// For textareas
$i.text(elements[ele].value);
// For input
$i.val(elements[ele].value);
}
console.log($x);
console.log($x[0]);
console.log($x[0].scrollHeight);
$div.append($i);
$('#form_content').append($div);
var $linebreak = $(document.createElement('br'));
$('#form_content').append($linebreak);
}
}
Resulting in:
This is as much an understanding problem as a problem blocking me. $x shows that there is a textarea at $x[0] and, expanding it, I see a giant list of properties. One of which is scrollHeight which I am trying to access.
However once accessing $x[0], it then gives me the HTML and $x[0].scrollHeight results in 0. The text is present.
What am I missing?
Edit: The height of the textarea is non-zero.

How can I prevent users input to be cloned in the appended input box in javascript

When I insert some thing in the input box of module 1 and click add module button to clone the required elements that I need it clones also the inserted input I've tried to prevent that using event.preventDefault(); but it's still copying the input box with the inserted input from module 1 however, I can't clear it using the clear button that is located in the input box moreover the appended select options doesn't work and when I select an option it doesn't change.
Here is my demo of what's happening:-
http://jsfiddle.net/0ojjt9Lu/6/
and here is my javascript code:
$(document).ready(function(){
$("#Sadd").click(function(event) {
event.preventDefault();
var lastId = $("#modules h1").length;
var $newLabel = $("#module-1-label").clone();
var $newSc = $("#module-1-scredit").clone();
var $newSgrade = $("#module-1-sgrade").clone();
$newLabel.html("<h1>Module " + (lastId+1) + ":</h1>");
$newSc.find("label").attr("for", "Sc"+(lastId+1));
$newSc.find("input").attr("name", "Sc"+(lastId+1)).attr("id", "Sc"+(lastId+1));
$newSgrade.find("label").attr("for", "Sgrade"+(lastId+1));
$newSgrade.find("select").attr("name", "Sgrade"+(lastId+1)).attr("id", "Sgrade"+(lastId+1));
$("#modules").append($newLabel, $newSc, $newSgrade);
});
$("#Sremove").click(function() {
var lastId = $("#modules h1").length;
if(lastId > 5){
var lastLi = $("#modules h1").last().closest("li");
var lastLi2 = lastLi.next("li");
var lastLi3 = lastLi2.next("li");
lastLi.remove();
lastLi2.remove();
lastLi3.remove();
}
});
});
Use .val("") on the new input to clear the data in on the clone
or do $(clone).find('input').val(""); if there is more than one input
In your case with the select box you need to add the following lines
After you declare (or on the same line) the variables
var $newSc = $("#module-1-scredit").clone().find('input').val("");
var $newSgrade = $("#module-1-sgrade").clone().find('option:selected').removeAttr('selected');
$newSgrade.find('option[value="-1"]').attr('selected',true);
Edit: Had to handle the reselection of the select due to default value being "-1" however you may need to look at the cloning of this select element. Perhaps on the page have the blank question hidden and just clone that.

Remove and Re-Create Element on event:

I am attempting to remove an entire element and recreate it on an event:
I cannot seem to get this right despite several variations of the same code:
For example on event, I need to remove the element and then recreate the same element. I do not want to remove the text:
This is what I have tried (experimental): The result is inconsistent and the code is repetitive.
function removeCreate(){
var input = document.getElementById('display');
var body = document.getElementsByTagName('body')[0];
if(!!input){
input.parentNode.removeChild(input);
input = document.createElement('input');
input.id = 'display';
input.setAttribute('type',"text");
body.appendChild(input);
} else {
input.parentNode.removeChild(input);
input = document.createElement('input');
input.id = 'display';
input.setAttribute('type',"text");
body.appendChild(input);
}
}
Your reason for removing your input element and re-creating it is quite unclear, but let's say it gets modified somehow and you want to "reset" its state.
When you say "I do not want to remove the text", the most probable thing I understand is that you want to keep the current value that the user has typed into your input.
If this fits your situation, then you could simply hold a "template" of your input element in memory, so that you can clone it when needed and use the clone to replace the one in DOM. When doing so, retrieve first the current input value, and inject it back into the cloned input.
Result:
var inputTemplate = document.createElement('input');
inputTemplate.setAttribute('type', 'text');
function cloneInput() {
var newInput = inputTemplate.cloneNode(true);
newInput.id = 'display';
return newInput;
}
var input = document.getElementById('display');
var body = document.getElementsByTagName('body')[0];
if(!!input){
// First retrieve the current value (what the user has typed / default value)
var value = input.value;
input.parentNode.removeChild(input);
input = cloneInput();
input.value = value; // Re-inject the value.
body.appendChild(input); // Note that this would put your input at the bottom of the page.
} else {
//input.parentNode.removeChild(input); // useless?
input = cloneInput();
body.appendChild(input);
}

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);

How to add value to dynamic input box in javascript

I am Creating one input box dynamically using javascript
Below is the Code:
var addtxt = document.createElement("input");
addtxt.type = "text";
addtxt.name = "admissionno" ;
addtxt.id = "admissionno" ;
If i add value in static way it will take using addtxt.value="11";
But am adding like this dynamically
addtxt.value=result.studentlist[j].admissionno
it will not work.please give me the idea its helpful for me.
Try this:
document.getElementById("admissionno").value = (result.studentlist[j].admissionno);

Categories