Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to add input fields to a page dynamically, when a user clicks a button.
I have the following code, which is being called, but doesn't work as expected
var a= document.getElementsByTagName("button");
a[0].addEventListener("click", clicked);
function clicked(){
var input = document.createElement("input");
document.appendChild("input");
}
The error I am facing is this:
"error"
"TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
at HTMLButtonElement.clicked (sofodipabe.js:5:12)"
What is causing this issue?
Do you wish to use jQuery? If you are using jQuery you can follow my easy solution below other wise #kira-sen had provided good solution.
Here is the fiddle you may look at.
HTML
<input type="text" id="n" placeholder="How may elements to add">
<button id="addElements">Add elements</button> <br>
<div id="addElementsHere">
</div>
JS
$("#addElements").click(function(e){
var n = parseInt($(this).siblings("#n").val());
for(var i = 0; i<n; i++){
$("#addElementsHere").append("<input class='xyz' type='text' placeholder=' Enter value for input number " + (i + 1) + "' id='inp-"+(i+1)+"'>");
}
});
Hope this helps.
Try This
// Creating 10 Input textboxes
var div = document.createElement('div');
for(var i = 0; i < 10; i++) {
var inputElement=document.createElement('input');
inputElement.setAttribute('type','text');
inputElement.setAttribute('id','id' + i);
inputElement.value='My Value ' + (i+1);
div.appendChild(inputElement);
}
document.getElementById("container").appendChild(div);
// Adding class
var inputElements = document.querySelectorAll('input');
for(var i=0; i < inputElements.length; i++) {
inputElements[i].className='MyClass' + i;
// Getting value
console.log(inputElements[i].value);
}
<div id="container"></div>
You can use this as an example to do what you want.
var container = document.querySelector('#container')
for (var i = 0; i < 10; i++) {
var input = document.createElement('input') // create a new element
input.classList.add('input') // Add .input class to the created element
input.placeholder = 'Input ' + i // set an attribute
input.id = 'input' + i // set the ID
container.append(input) // Append the element to a parent element (container in this case)
}
.input {
width: 100%;
}
<div id="container"></div>
Related
This question already has answers here:
Todo list wont refresh after pushing to array
(3 answers)
Closed 1 year ago.
I'm stuck. Trying to push input values into an array, which actually works, but then I want to get them out into an unordered list, and they don't show up. What am I doing wrong?
const inputBtn = document.querySelector("#input-btn");
let myLeads = [];
const inputEl = document.querySelector("#input-el");
const ulEl = document.querySelector("#ul-el");
inputBtn.addEventListener("click", function() {
myLeads.push(inputEl.value);
console.log(myLeads);
});
for (let i = 0; i < myLeads.length; i++) {
ulEl.innerHTML += "<li>" + myLeads[i] + "</li>";
}
<input type="text" id="input-el" />
<button id="input-btn">SAVE INPUT</button>
<ul id="ul-el"></ul>
Your loop doesn't do much because it's executing before any clicks.
Remove the dependence on the array, and use insertAdjacentHTML to add the wrapped value of the input directly to the list within the click handler.
(Note: I'm using insertAdjacentHTML here because there are performance issues that arise from concatenating HTML to an element's innerHTML property.)
const inputBtn = document.querySelector('#input-btn');
const inputEl = document.querySelector('#input-el');
const ulEl = document.querySelector('#ul-el');
inputBtn.addEventListener('click', function() {
ulEl.insertAdjacentHTML('beforeend', `<li>${inputEl.value}</li>`);
});
<input type="text" id="input-el" />
<button id="input-btn">SAVE INPUT</button>
<ul id="ul-el"></ul>
Additional documentation
Template/string literals
One option would be to immediately call your for loop right after pushing to the array. Like so:
inputBtn.addEventListener("click", function() {
myLeads.push(inputEl.value);
for (let i = 0; i < myLeads.length; i++) {
ulEl.innerHTML += "<li>" + myLeads[i] + "</li>";
}
console.log(myLeads);
});
Right now, the for loop isn't run at all.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to fill my HTML table with my array. I tried it with $rowTemplate.find('[data-id=id]').text(id);
But it didn't work. I work with sockets so I can't post all of my code that would be too confusing.
I will ads some of my code but it's a general question how to fill a HTML table with input of an two dim array.
socket.on('outputData', function(data) {
var $rowTemplate = $('<tr><td data-id="id"></td><td data-id="name"></td><td data-id="geburtsort"></td><td data-id="geburtsdatum"></td><td data-id="favorite"></td></tr>');
var resultArray = data.resultArray;
var name, location, bdate, id, anzahl = 0;
for (var i = 0; i < resultArray.length; i++) {
name = resultArray[i][0];
anzahl = anzahl + 1;
console.log(name);
location = resultArray[i][1];
bdate = resultArray[i][2];
favorit = resultArray[i][3];
id = resultArray[i][4];
$rowTemplate.find('[data-id=id]').text(id);
$rowTemplate.find('[data-id=name]').text(name);
$rowTemplate.find('[data-id=geburtsort]').text(location);
$rowTemplate.find('[data-id=geburtsdatum]').text(bdate);
}
$("#table > tbody").append(rowTemplate.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<table id="table">
<tbody>
<tr>
<th>ID</th>
<th>Name</th>
<th>Geburtsort</th>
<th>Geburtsdatum</th>
<th>Favorit</th>
</tr>
</tbody>
</table>
The problem lies with your variable rowTemplate. Get rid of the $ and it should work.
var rowTemplate = $('<tr><td data-id="id"></td><td data-id="name"></td><td data-id="geburtsort"></td><td data-id="geburtsdatum"></td><td data-id="favorite"></td></tr>');
rowTemplate.find("[data-id=id]").text("bcd");
Test it out here: https://jsfiddle.net/Lwmu4p6q/
I am not quite sure why that is the case, though. I think it is problematic because of jQuery. You can still use variables starting with a dollar sign, but when you start cascading with jQuery functions, it doesn't seem to work.
EDIT: Another way to do it would be to manually "build up" the row.
Instead of parsing the HTML with jQuery like rowTemplate = $('...'); and then manipulating it with jQuery selectors you could do it like this with vanilla JavaScript:
var outputHTML = "";
for (var i = 0; i < array.length; i++) { // i for the rows
var newRow = "<tr>";
for (var j = 0; j < array[i].length; j++) { // j for the colums
newRow += "<td>" + array[i][j] + "</td>";
}
outputHTML += newRow + "</tr>";
}
I would suggest using let instead of var if possible. And I would argue that this version might perform faster, but the difference, if existent at all, would only matter with really big tables. It depends on the way jQuery selectors and text() has been implemented, though.
EDIT 2:
Check https://jsfiddle.net/Lv9vdv8u/ for the second version.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am using a HTML page where I have multiple textbox inputs, lets say five for example. I have a submit button. Once I enter all values in the text boxes and hit submit, i want all the values to be displayed in the area below submit button on the document in an ascending order. I want to sort all the values to display as result. I just used an array to test if my concept is right, but no luck. Anyone could help is highly appreciated.
This is the code:
function myFunction() {
var txt = new array[];
var txt[0] = $('input:text[name=text1]').val();
var txt[1] = $('input:text[name=text2]').val();
var txt[2] = $('input:text[name=text3]').val();
var txt[3] = $('input:text[name=text4]').val();
var txt[4] = $('input:text[name=text5]').val();
txt.sort();
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').value + ' ';
}
}
The .text-1, .text-2, etc are the classes of your input fields. The .val() will get the user input of those once they click on your submit button. The last line creates a new div and appends the user input to the results div.
$('.submit-button').on('click', function() {
aaa = $('.text-1').val();
bbb = $('.text-2').val();
ccc = $('.text-3').val();
ddd = $('.text-4').val();
eee = $('.text-5').val();
$('<div>' + aaa + '<br />' + bbb + '<br />' + ccc + '<br />' + ccc + '<br />' + ddd + '<br />' + eee + '</div>').appendTo('.results-div');
});
Here is a fiddle that does what I think you want done:
http://jsfiddle.net/KjHB3/3/
Here is the HTML code:
<input type="text" name="text1" id="text1" /><br/>
<input type="text" name="text2" id="text2" /><br/>
<input type="text" name="text3" id="text3" /><br/>
<input type="text" name="text4" id="text4" /><br/>
<input type="text" name="text5" id="text5" /><br/>
<input type="button" value="submit" id="submit" />
<div id="result">replace</div>
Here is the javascript code:
$("#submit").click(function() {
// Extract all the values into an array
var valArray = [];
$("input[type=text]").each(function(index, el) {
valArray[index] = jQuery(el).val();
});
// Output list of values (in order they appear in form)
$("#result").html("In order of text box: <ol id='list1'></ol>");
$.each(valArray, function(index, value) {
$("#list1").append("<li>" + value + "</li>");
});
// Output list of values (in sorted order)
$("#result").append("In sorted order: <ol id='list2'></ol>");
valArray = valArray.sort();
$.each(valArray, function(index, value) {
if (value != null && value != "") {
$("#list2").append("<li>" + value + "</li>");
}
});
});
Your code appears to be correct, except for the line document.getElementById('txt[i]').value + ' ';. There's nothing writing the values back to the document.
First, starting with the selector, you need to change 'txt[i]' to 'text'+i, because the browser is looking for an element with id txt[i] and finding nothing, thus doing nothing. Also, you should use jQuery, since it makes everything more concise.
Then, to write back to the document, you need to set the value. What your current code (.value + ' ';) does is it gets a value, then adds it to the string ' ', then the statement ends. What you need to do is to set the value of the string, with jQuery (.val(txt[i]);) or stock Javascript (.value = txt[i];).
So, to conclude, just swap the code inside the for loop in your code with this line:
$("input:text[name=text"+i+"]").val(txt[i]);
Let me break down your code in two part to show why it is not working yet.
function GetInputValues() {
var txt = new array[];
var txt[0] = $('input:text[name=text1]').val();
var txt[1] = $('input:text[name=text2]').val();
var txt[2] = $('input:text[name=text3]').val();
var txt[3] = $('input:text[name=text4]').val();
var txt[4] = $('input:text[name=text5]').val();
txt.sort();
return txt; // added by me to encapsulate getting the values
}
The first part of your function myFunction() is correct. You are using jQuery to get the values of the input boxes and writing the values into an array.
The second part has some mistakes:
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').value + ' ';
}
The function document.getElementById("lastname") returns the html-element whose id is lastname. So in your for-loop you are trying to get the value but you already have the values in your array txt. On top this 'txt[i]' is only a string. So javascript tries to find an element that matches <... id="txt[i]" ...>. But you do not want to get the values you want to write the values back into the document. Assuming you have a div like this <div id='txt[i]'> ...</div> you could wrhite your code like this:
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').innerHTML += txt[i];
}
Another way would be to join the array:
var myInputValues = GetInputValues(); // this returns your array txt
document.getElementById('myResult').InnerHTML = myInputValues.join(", ");
This assumes that you have a element with id=myResult for example <div id='myResult'>..</div>
Update to adress issues in your code
Your fiddle has this part:
myFunction(txt) { // <-- function declaration: there is something missing here
var myInputValues = GetInputValues(); // this returns your array txt
document.getElementById('myResult').InnerHTML = myInputValues.join(", ");
} //<--- this is the end of myfunction
}); // <-- these do not belong here
// you never execute myFunction
You have to define the function and later call it. Since your mistakes are so basic i really recommend to start with a tutorial to learn javascript. I can recommend Eloquent JavaScript:
to learn the basics of functions
to understand the basics about the Document-Object Model
I've been trying to figure this out for a while, and I'm totally stumped.
I'm writing a program that is supposed to display a basic series of multiple-choice questions. You see a question, you click one of the answers, and you move on to the next question.
The problem is, I can't figure out how to display one question, then display the next question when the user clicks one of the buttons. Nothing happens when I click a button. What's going wrong?
// progress meter
var progress = new Array();
for (var i = 0; i < questions.length; i++) progress.push("0");
var i = 0;
display(0);
// display questions
function display(i) {
var prg_string;
for (var j = 0; j < progress.length; j++) prg_string += progress[j];
document.write(
"<div id = 'background'>"
+ "<div id = 'progress'>" + progress + "</div>"
+ "<div id = 'title'>-JogNog Test v1-<br></br>" + tower + "</div>"
+ "<div id = 'question'>" + questions[i].text + "</div>"
+ "<div id = 'stats'>Level " + level + "/" + total_levels + " Question " + (i + 1) + "/" + questions.length + "</div>"
+ "</div>"
);
document.write("<button id = 'answer1' onclick = 'next(questions[i].answers[0].correct)'>" + questions[i].answers[0].text + "</button>");
if (questions[i].answers.length > 0)
document.write("<button id = 'answer2' onclick = 'next(questions[i].answers[1].correct)'>" + questions[i].answers[1].text + "</button>");
if (questions[i].answers.length > 1)
document.write("<button id = 'answer3' onclick = 'next(questions[i].answers[2].correct)'>" + questions[i].answers[2].text + "</button>");
if (questions[i].answers.length > 2)
document.write("<button id = 'answer4' onclick = 'next(questions[i].answers[3].correct)'>" + questions[i].answers[3].text + "</button>");
}
// go to next question, marking whether answer was right or wrong
function next(correct) {
if(correct) progress[i] = "T";
else progress[i] = "F";
i += 1;
display(i);
}
I haven't read through your code, (you might want to work on posting SSCCEs by focusing just on the part that handles the loop) but I get the feeling a loop is not what you want here. Loops are great if you need to automatically iterate through something. But really, you want to display only a single question at a time.
The easiest way to do this, assuming you have a means of handling each question independently, is just to keep track of which question the user is up to. Display that question. When the user submits an answer, call whatever function renders a question using the counter, plus one. Make sure to check that you haven't hit the end of the quiz so that you don't reference a question that doesn't exist.
Here's some pseudocode:
var questionNumber, questions; //assume these already have values
function printQuestion(questionNumber){ ... }
function nextQuestion(){
if(questionNumber < questions){
questionNumber++;
printQuestion(questionNumber);
}
else{
showResults();
}
}
I agree with #ngmiceli that a loop isn't what you want here. You want to display one question, and then create click event handlers that will move on to the next question when the user selects an answer to the previous question.
I went ahead and created a different setup to demonstrate. You can see a demo here:
-- jsFiddle DEMO --
But I'll walk through the process. First, I set up a basic HTML document:
<body>
<h1>-Test v1-</h1>
<h2>Simple Math</h2>
<div id="container">
<div><span id="numRight">0</span> of <span id="numQuestions">0</span></div>
<div id="question"></div>
<div id="answers"></div>
</div>
</body>
Then, I created a questions array, each element in the array being an object. Each question object contains the question itself, an array of possible answers, and an "answerIdx" property that indicates the array index of the correct answer.
questions = [
{
question: 'What is 0 / 6 ?',
options: ['0','1','2'],
answerIdx: 0
},
{
question: 'What is 2 + 2 ?',
options: ['72','4','3.5'],
answerIdx: 1
}
]
I also created some other variables that point to the HTML elements I am going to want to manipulate:
numRight = 0,
numQuestions = 0,
answerDiv = document.getElementById('answers'),
questionDiv = document.getElementById('question'),
numRightSpan = document.getElementById('numRight'),
numQuestionsSpan = document.getElementById('numQuestions');
Next, I created a 'displayQuestion' function which takes a single question object as a parameter:
function displayQuestion(q) {
// insert the question text into the appropriate HTML element
questionDiv.innerHTML = q.question;
// remove any pre-existing answer buttons
answerDiv.innerHTML = '';
// for each option in the 'options' array, create a button
// attach an 'onclick' event handler that will update
// the question counts and display the next question in the array
for(i = 0; i < q.options.length; i++) {
btn = document.createElement('button');
btn.innerHTML = q.options[i];
btn.setAttribute('id',i);
// event handler for each answer button
btn.onclick = function() {
var id = parseInt(this.getAttribute('id'),10);
numQuestionsSpan.innerHTML = ++numQuestions;
// if this is the right answer, increment numRight
if(id === q.answerIdx) {
numRightSpan.innerHTML = ++numRight;
}
// if there is another question to be asked, run the function again
// otherwise, complete the test however you see fit
if(questions.length) {
displayQuestion(questions.shift());
} else {
alert('Done! You got '+numRight+' of '+numQuestions+' right!');
}
}
answerDiv.appendChild(btn);
}
}
Finally, I displayed the first question:
displayQuestion(questions.shift());
I have a some problem
i.e i have a 60 text box controls in asp page i want to text box text to empty so , i am using like below
var st = document.getElementById("<%=hiddenrate.ClientID%>").value;//Total Control names
var controlnames = st.split(','); //split with comma
var i = 0;
for (i = 0; i <= controlnames.length; i++)
{
var gh = '' + '.SetText(' + "'Empty text'" + '' + ');';
ft[i] + gh;
//example rate1.SetText('');
rate2.SetText('');
'
'
rate60..SetText('');
}
but in javascript is that control name and property
How to set text as empty in total controls dynamically?
Thanking You,
Rajesh
IF you want to clear the values of all text inputs use this code:
// get all <input> elements
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
// check input type
if (inputs[i].type === 'text') {
inputs[i].text = '';
}
}
You could easily modify that code to handle textareas as well or add some more filtering to the elements.
If you consider using JS framework you can make this code much shorter. For example if you use jQuery then here's the code for you:
$(document).ready(function () {
$('input:text').text('');
});
Here is another sample to clear value all textboxes:
<script type="text/javascript">
function pp(){
for(p in form1.childNodes) {
if(form1.childNodes(p).type=="text")
form1.childNodes(p).value="";
}
}
</script>
<body>
<form name="form1">
<input type="text" name="a1"/>
<input type="text" name="a2"/>
<input type="text" name="a3"/>
<input type="button" name="a11"/>
<input type="submit" name="a12"/>
<input type="button" value="Clear" onclick="pp()" name="a13"/>
</form>
</body>
How about simply calling document.forms["form1"].reset() in Javascript? It will clear the values of all the controls in the form.
Thanking u all i got the solution like below method
var i = 0;
for (i = 0; i <= ft.length; i++) {
x = new Object();
x = ft[i];
propertyName = ".SetText";
propertyValue = " ";
if(x !="undefined")
eval(''+x+'' + propertyName + "('" + propertyValue + "');");
or
eval(x).SetText('');
}
thnks to all.