Adding input fields in Javascript with onclick button [duplicate] - javascript

This question already has answers here:
Dynamically creating a specific number of input form elements
(2 answers)
Closed 7 years ago.
The community reviewed whether to reopen this question 4 months ago and left it closed:
Original close reason(s) were not resolved
Im always used to using jquery or other javascript frameworks but right now I have no frameworks to use so i wanted to see if anyone knows how i can do this in straight javascript if possible.
Basically i have a div like this
<input type="button" id="more_fields" onclick="add_fields();" value="Add More" />
<div id="room_fileds">
<div class='label'>Room 1:</div>
<div class="content">
<span>Width: <input type="text" style="width:48px;" name="width[]" value="" /><small>(ft)</small> X </span>
<span>Length: <input type="text" style="width:48px;" namae="length[]" value="" /><small>(ft)</small</span>
</div>
</div>
What i need one is when the add more button is clicked i need to basically add more width and length fields either creating a entire structure like the one above with all the divs or just inserting new span tag with the fields below the existing ones.
I know how to do it with jquery or prototype framework but unfortunatley I cannot use any frameworks for this. Does anyone have any idea how to do it. I would post code iv done for this but I dont even know where to beging.

You can use the innerHTML property to add content. Add a id="wrapper" to the div surrounding your span elements and then you can do
var dummy = '<span>Label: <input type="text"><small>(ft)</small></span>\r\n';
document.getElementById('wrapper').innerHTML += dummy;
Of course you don't need the id and can use other DOM methods to get to the div, but I find using ids easier and cleaner. Here's a quick fiddle
Also note that you shouldn't inline your css code, neither attach your javascript calls directly inside the DOM elements. Separating DOM, Javascript and CSS will make your life easier.

Don't need create new room?.
var room = 1;
function add_fields() {
room++;
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
divtest.innerHTML = '<div class="label">Room ' + room +':</div><div class="content"><span>Width: <input type="text" style="width:48px;" name="width[]" value="" /><small>(ft)</small> X</span><span>Length: <input type="text" style="width:48px;" namae="length[]" value="" /><small>(ft)</small></span></div>';
objTo.appendChild(divtest)
}
Demo: http://jsfiddle.net/nj4N4/7/

just use the innerHTML like this:
btw I changed div class="content" to id="content" you can add new id if you prefer.
function add_fields() {
var d = document.getElementById("content");
d.innerHTML += "<br /><span>Width: <input type='text'style='width:48px;'value='' /><small>(ft)</small></span> X <span>Length: <input type='text' style='width:48px' value='' /><small>(ft)</small</span>";
}
DEMO: http://jsbin.com/oxokiq/5/edit

Related

Event watcher failing on dynamically added content [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 months ago.
Thank you in advance for any help! :)
I am using javascript to add fields to a document but the element monitor only works on hard coded fields.
For example in the code below, lozfield is monitored for change which works fine initially.
However, if you click the populate button and repopulate with exactly the same input field, the watch no longer works.
In debug, the field has EVENT next to it... until it is repopulated at which point the EVENT disappears.
(apologies for my probably incorrect terminology!).
$("#lozfield").change(function() {
alert("lozfield-CHANGED");
});
$("#populate").click(function() {
document.getElementById("lozcontainer").innerHTML = '<input type="text" id="lozfield" value="ABC">';
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="lozcontainer">
<input type="text" id="lozfield" value="ABC">
</div>
<input id="populate" type="button" value="POPULATE">
You need to delegate your event to a higher element - which in your case I'd suggest is lozcontainer
$("#lozcontainer").change("#lozfield", function() {
alert("lozfield-CHANGED");
});
$("#populate").click(function() {
document.getElementById("lozcontainer").innerHTML = '<input type="text" id="lozfield" value="ABC">';
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="lozcontainer">
<input type="text" id="lozfield" value="ABC">
</div>
<input id="populate" type="button" value="POPULATE">

How to create a form with a variable number of inputs?

Take this code for example:
var add = function() {
var added = document.createElement("div");
document.getElementById("ID").appendChild(added);
added.setAttribute("id", "Task " + document.getElementById("ID").childElementCount);
added.appendChild(document.createElement("input"));
added.appendChild(document.createElement("br"));
};
<form id="ID">
Name:
<br>
<input type="text" name="name">
<br>
</form>
<button onclick="add()">Add</button>
Every time you click the button, a new input is created for the form.
Is this the best way of making the number of form elements dynamic?
I looked into using HTML templates, but it didn't seem like there was a way to edit the ID of each individual additional element, which would be necessary for my applications.
Also, a subquestion: I'm using AngularJS and can't figure out how to add the bs-datepicker directive to my elements with JavaScript. How can I do that?
Here's an example of bs-datepicker which I know works:
<input type="text" class="form-control"
ng-model="options.fromDate"
max-date="{{options.toDate}}"
start-date="{{options.currentDateValue.toString()}}"
start-week="1" placeholder="From" bs-datepicker>

Dynamic javascript form

I have a simple form as follows so a user can type the name of a question:
<input type="text" id="question_name" name="question_name" value="">Question Name: <br />
Add Another
<div id="container"/>
<input id="go" name="btnSubmit" type="submit" value="Submit" class="btn" />
I am wanting to create a Javascript function (addNewQuestion()) which allows a user to add another question dynamically by clicking the "Add Another" link. All the text boxes with the questions should be displayed on the screen.
I understand that it is using getElementById and most likely a for loop but I keep hitting a brick wall. Can anyone show me a simple solution please?
There are many ways to do this. Here's a simple example in plain JavaScript. Note that you will either want to avoid using ids so they aren't duplicated in the DOM, or you will want to dynamically name them.
function addNewQuestion() {
var container = document.getElementById("questions");
var question = document.querySelector(".question");
container.appendChild(question.cloneNode(true));
return false;
}
.question { display: block }
<div id="questions">
<label class="question">
Question Name:
<input type="text" value="" />
</label>
</div>
Add Another

User input list using HTML plus a way to process the information

I am trying to run a simple code for something at work -- me and my co-workers are going to make a list of songs. So using what seems to be a pretty simple coding in HTML I managed to achieve the following:
<!DOCTYPE html>
<html>
<body>
<form action="list">
Band Name:<br>
<input type="text" name="BandName">
<br>
Song Name:<br>
<input type="text" name="SongName">
<br><br>
<input type="submit">
</form>
</body>
</html>
This runs fine to create the buttons and boxes for user input. But I still do not know how to process this information. The ideal result would be a way to append the names, as the users placed their inputs, in a list at the action page. Would that be possible? I'm trying to achieve this in the HTML box of google sites, by the way.
Edit:
With some help, I was able to run the following code on http://jsfiddle.net/:
////HTML///
<form>
Band/Artist:<br>
<input type='text' id='idea' />
<br>
Music:<br>
<input type='text' id='idea2' />
<br><br>
<input type='button' value='Adicione' id='add' />
<ul id='list'></ul>
<script type="text/javascript">
////JAVASCRIPT//////
//Defining a listener for our button, specifically, an onclick handler
document.getElementById("add").onclick = function() {
//First things first, we need our text:
var text = document.getElementById("idea").value; //.value gets input value
var text2 = document.getElementById("idea2").value; //.value gets input value
//Now construct a quick list element
var node = document.createElement("li");
var textnode = document.createTextNode(text+" - "+text2);
node.appendChild(textnode);
//Now use appendChild and add it to the list!
document.getElementById("list").appendChild(node);
(the code came partially from TymeVM's answer in adding user input to a list of text items on a html page, but something seemed to be wrong with it)
It works fine. But I was not able to run it on page of Google Sites. Is it possible? If not, do you guys know a better option?
As my edition seems to answer my question, I'll post it also as an answer. Please feel free to add any suggestions to it.
The following code, with the addition of Javascript, produces the needed answer for the first question above, according to http://jsfiddle.net/.
////HTML///
<form>
Band/Artist:<br>
<input type='text' id='idea' />
<br>
Music:<br>
<input type='text' id='idea2' />
<br><br>
<input type='button' value='Adicione' id='add' />
<ul id='list'></ul>
<script type="text/javascript">
////JAVASCRIPT//////
//Defining a listener for our button, specifically, an onclick handler
document.getElementById("add").onclick = function() {
//First things first, we need our text:
var text = document.getElementById("idea").value; //.value gets input value
var text2 = document.getElementById("idea2").value; //.value gets input value
//Now construct a quick list element
var node = document.createElement("li");
var textnode = document.createTextNode(text+" - "+text2);
node.appendChild(textnode);
//Now use appendChild and add it to the list!
document.getElementById("list").appendChild(node);
(As it was pointed in the edition of the question above, the code came partially from TymeVM's answer in adding user input to a list of text items on a html page. But it did not work on http://jsfiddle.net/)
But still does not run on Google Sites, it seems. I do not know if I should create another question for this problem.

Make readonly using getElementByName? [duplicate]

This question already has answers here:
JavaScript getElementByName doesn't work
(4 answers)
Closed 9 years ago.
I need to make "readonly" a text field by place javascript code inside external JS file. I can't modify html directly because the page is located on remote server..but I can interact by adding code in external JS who is located on my own host.
The html is this:
<form id="newunitform" class="left" action="page.php" style="width:600px" method="post">
<fieldset>
<ul>
<li>
<label for="add">
<input type="text" value="" name="add">
<input type="hidden" value="" name="remove">
<input type="hidden" value="105" name="resource_id">
<input type="hidden" value="" name="editid">
</li>
</ul>
<label for="submit"> </label>
<input class="button" type="submit" value="Add name" name="submit">
</fieldset>
</form>
I tried several combination such this:
document.getElementByName('add').readOnly=true;
or this:
var add = document.getElementByName('add');
add.readOnly = true;
or this:
document.getElementById('newunitform');
document.getElementByName('add').readOnly=true;
but none work.
As Rocket Hazmat suggests in the comment to your question, you should use
document.getElementsByName('add')[0].readOnly=true;
document.getElementsByName('name')
returns an array. You need to use brackets or .item() to point to your element.
I suggest you using this one, in my opinion it is a better solution:
var newUnitForm = document.getElementById('newunitform');
newUnitForm.add.readOnly = true; //or newUnitForm['add'], it's the same
That's true -- it's either getElementById (single element) or getElementsByName which access all the elements in the DOM that have the name you're looking for.
Once you change Element to Elements you should be able to set the readOnly attribute.
You could also try, document.getElementByNames('someElement').disabled = true; but be careful if there are multiple elements with the same name.
Also -- because syntax like this has tripped me up any number of times, if a function doesn't work as expected, I'll make sure I'm getting the object I think I'm getting by alerting some aspect of the element.
e.g. alert(document.getElementsByName('someElement').length) or alert(document.getElementsByName('someElement').name)
Good luck
If you know there is only one element named "add", you can try something like this:
var elem = document.getElementsByName("add")[0];
elem.setAttribute("readonly", "true"); // or elem.readOnly = true;
If you know there is only one element named "add" inside the "newunitform" form, use LightStyle's suggestion:
var elem = document.getElementById("newunitform").add;
elem.setAttribute("readonly", "true"); // or elem.readOnly = true;
In any case, make sure the snippet is executed after the element in question has been rendered (e.g. you could place it in body's onload method.

Categories