Removing a text field using Javascript - javascript

I have the following code to add text fields when the function is called:
<span id="response"></span>
<script>
var qcountBox = 2;
var acountBox = 2;
var qboxName = 0;
var aboxName = 0;
function addInput()
{
var qboxName="question"+qcountBox;
var aboxName="answer"+acountBox;
if(qcountBox <=10 && acountBox <= 10)
{
document.getElementById('response').innerHTML+='<br/>Question '+qcountBox+': <input type="text" name="'+qboxName+'"/>';
document.getElementById('response').innerHTML+='<br/>Answer '+acountBox+': <input type="text" name="'+aboxName+'"/><br/>';
qcountBox ++;
acountBox ++;
}else
alert("No more than 10 questions allowed at this time.");
}
I also would like to be able to add a function to remove any new fields I have added. Any suggestions? Thanks

<script>
var qcountBox = 1;
var acountBox = 1;
var qboxName = 0;
var aboxName = 0;
function addInput()
{
var qboxName="question"+qcountBox;
var aboxName="answer"+acountBox;
if(qcountBox <=10 && acountBox <= 10)
{
document.getElementById('response').innerHTML+='<div id="'+qcountBox+'"><br/>Question '+qcountBox+': <input type="text" name="'+qboxName+'"/>';
document.getElementById('response').innerHTML+='<br/>Answer '+acountBox+': <input type="text" name="'+aboxName+'"/><br/></div>';
qcountBox ++;
acountBox ++;
}else
alert("No more than 10 questions allowed at this time.");
}
function removeInput(id)
{
document.getElementById(id).innerHTML = '';
}
You can remove any question that you added using the id of the question div (same as qboxName)

Surround each new piece of HTML in a span with a common class name. Then, find all the objects with that class name and remove them.
Add the span and class name to these:
document.getElementById('response').innerHTML+='<span class="added"> <br/>Question '+qcountBox+': <input type="text" name="'+qboxName+'"/></span>';
document.getElementById('response').innerHTML+='<span class="added"><br/>Answer '+acountBox+': <input type="text" name="'+aboxName+'"/><br/></span>';
Then, you can remove all the added spans like this:
var items = document.getElementsByClassName("added");
for (var i = 0; i < items.length; i++) {
items[i].parentNode.removeChild(items[i]);
}
Note: This is a generally better way to add your new HTML as it doesn't rewrite all previous HTML - it just adds new DOM objects:
var span = document.createElement("span");
span.className = "added";
span.innerHTML = '<br/>Question '+qcountBox+': <input type="text" name="'+qboxName+'"/><br/>Answer '+acountBox+': <input type="text" name="'+aboxName+'"/><br/>';
document.getElementById('response').appendChild(span);

You should actually create an input element in javascript and append it to your container through appendChild instead of using innerHTML +=.
You should also set an ID for those fields, not just a name. But it can be the same as theirs names.
Like this
var input = document.createElement("input");
input.type = "text";
input.name = input.id = qboxName;
document.getElementById("response").appendChild(input);
And then, you know, do the same for the other input field you need.
I know you need a text label for the boxes, or whatever, just do the same process to insert a span tag before them.
Also, I don't see a reason for those two counting variables. Instead of qcountBox and acountBox it's totally possible to have only one single counting variable. Maybe I'm wrong but shouldn't you increase this counting before setting the boxes names?
As for removing it, you can use the removeChild method, then, decrease your counting variable. like this:
function removeInput()
{
var qboxName = "question" + count;
var aboxName = "answer" + count;
document.getElementById("response").removeChild(document.getElementById(aboxName));
document.getElementById("response").removeChild(document.getElementById(aboxName));
count--;
}
Maybe if you're going to insert other elements together with these fields, like span tags for labels etc, it would be better to wrap them all up in a div or something, then simply do a removeChild to this container div only.

Related

How do you make javascript(including function with array and return) write in div on button click without going to another page

I have had a lot of problems with this problem. When I console.log(sum); I get the answer I am looking for, but when I try to output the answer from a button click and an input field it does not work. I changed felt3.innerHTML=addnumber(ttt); to document.write(addnumber(ttt)); which made it work, but it is sending it to another page, which is something I do not want. How I can make this work:
<form id="form3">
Tall:<input type="number" id="number"><br>
<input type="button" id="button3" value="plusse"><br>
</form>
<div id="felt3"></div>
and:
var number = document.getElementById("number");
var felt3 = document.getElementById("tall3");
var form3 = document.getElementById("form3");
var button3 = document.getElementById("button3");
var sum=0;
function addnumber(x){
var array = [];
array.push(x);
for (var i = 0; i < array.length; i++) {
sum=sum+array[i];
}
return sum;
}
button3.onclick=function(){
var ttt=Number(number.value);
felt3.innerHTML=addnumber(ttt);
}
If I understand your question correctly, then the solution here is to update the argument that you are passing to getElementById("tall3"), rewriting it to document.getElementById("felt3");.
Doing this will cause your script to aquire the reference to the div element with id felt3. When your onclick event handler is executed, the result of addnumber() will be assigned to the innerHTML of the valid felt3 DOM reference as required:
var number = document.getElementById("number");
// Update this line to use "felt3"
var felt3 = document.getElementById("felt3");
var form3 = document.getElementById("form3");
var button3 = document.getElementById("button3");
var sum=0;
function addnumber(x){
var array = [];
array.push(x);
for (var i = 0; i < array.length; i++) {
sum=sum+array[i];
}
return sum;
}
button3.onclick=function(){
var ttt=Number(number.value);
// Seeing that felt3 is now a valid reference to
// a DOM node, the innerHTML of div with id felt3
// will update when this click event is executed
felt3.innerHTML=addnumber(ttt);
}
<form id="form3">
Tall:<input type="number" id="number"><br>
<input type="button" id="button3" value="plusse"><br>
</form>
<div id="felt3"></div>

Display number of Input fields based on the value in database column

I have a database table with column name qty that holds an int.Now i want to display as many input fields as the value in qty.
So far i haved tried this using iavascript code . Here is my javascript code .
$(function() {
var input = $(<input 'type'="text" />);
var newFields = $('');
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n+1) {
if (n > newFields.length) {
addFields(n);
} else {
removeFields(n);
}
}
});
function addFields(n) {
for (i = newFields.length; i < n; i++) {
var newInput = input.clone();
newFields = newFields.add(newInput);
newInput.appendTo('#newFields');
}
}
function removeFields(n) {
var removeField = newFields.slice(n).remove();
newFields = newFields.not(removeField);
}
});
Just store the value in the textfield(hidden)
HTML:
<input type="hidden" id="quantitycount" value="4" />
<div class="textboxarea"></div>
Jquery:
Get the textbox value
var quantitycount=jQuery('#quantitycount').val();
var txthtml='';
for(var txtcount=0;txtcount<quantitycount;txtcount++){
txthtml+='<input type="text" id="txtbox[]" value="" />';
}
jQuery('.textboxarea').html(txthtml);
You can use entry control loops to loop for number of times
Now we can see number of textbox as per need, Just the value from db and store that in the textbox
You can try this
foreach($qty as $qt){
echo '<input type="text">';
}
To append the text fields you need a wrapper on your html form
use some wrapper as mentioned by #Rajesh: and append your text-fields to that wrapper as shown below
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n >0) {
for(var x=0;x<n;x++){
$('#textboxarea').append('<input type="text" name="mytext[]"/>');
}
});
similarly you can write your own logic to remove the text-fields also using jquery

Replacing a sub-string in JavaScript innerHTML

I have an HTML page which contains table rows like
<tr id="tp1">
<input type="checkbox" id="tc_">
</tr>
<tr id="tp2">
<input type="checkbox" id="tc_">
</tr>
The page contains input elements other than checkboxes as well
I have to change the values of all checkbox's id from tc_ to tc_1 ,tc_2 and so on.
I have thought of doing it as below
function startup(){
for(var i=0;i<3;i++)
{
var elem=document.getElementById("tp"+i);
var str=elem.innerHTML;
str.replace(/tc_,'tc_'+i); // how do I correctly use the arguments here?
elem.innerHTML=str;
//alert (""+str);
}
}
Thanks.
It isn't valid to have non-unique IDs in the first place. Any chance you can fix how the checkboxes are rendered so you don't have to do this?
That being said, I wouldn't do this by manipulating the HTML attributes. I would instead do this by manipulating the DOM properties of those input checkboxes:
// keep track of the current "new" checkbox ID suffix
var checkBoxIndex = 0;
for (var i = 0; i < 3; i++) {
// find the table row
var elem = document.getElementById("tp" + i);
// get the input elements within that row
var inputs = elem.getElementsByTagName("input");
// for each of the input elements...
for (var j = 0, k = inputs.length; j < k; j++) {
// if it's not a checkbox, skip it
if (inputs[j].type.toLowerCase() !== 'checkbox') {
continue;
}
// Alas, give the checkbox a new, unique ID
inputs[j].id = "tc_" + (checkBoxIndex++);
}
}
Also, hopefully you get an answer for your other question. This is a terrible workaround and I would hate to see it in production code.
The trick here is to select all the input elements of your rows using the appropriate CSS selector, then modify their ids:
function startup() {
for (var i = 0; i < 3;i++) {
var elem = document.getElementById("tp" + i);
var l = elem.querySelectorAll('td > input'); // Select "input"s in "td"s
Array.prototype.forEach.call(l, function (e, j) { // Apply to each element obtained
e.id = 'tc_' + j; // Modify the id
});
}
}
There's several good answers above but if you still want to change the id from tc_ to tc_ + i then you can do it like this.
<body>
<button id="tc_">1</button>
<button id="tc_">2</button>
<button id="tc_">3</button>
<script type="text/javascript">
for(var i=0;i<3;i++)
{
document.getElementById("tc_").id="tc_"+i;
}
</script>
</body>
Honestly though you shouldn't be doing it like this despite the fact this code works as other users have said it isn't valid to have non-unique id's.

dynamic arrays with input javascript

I am currently doing a school project where I have to use javascript to create a page where a user can key in multiple numbers from an input box.
After each number is entered there is a add button which then shows the number in another box below the input. So each number is displayed vertically down the page.
From there I need two more buttons. The first one to calculate which will add the numbers together and work out the average. The second one will clear the array to start again.
I believe I am ok with the last two buttons. What I am unsure of is how should the user input create the dynamic array which will then be displayed in the page. I have been able to get a single number input but I am missing the next step so the next number entered will dispay and allow me to build an array from which the calculations can be performed.
Please try this I think it will work for you
JAVA SCRIPT :
<script type="text/javascript">
var arr = new Array();
function addNum()
{
var temp = document.getElementById('a').value;
arr.push(temp);
document.getElementById('a').value = "";
getAvg();
}
function getAvg()
{
var sum = 0;
for(var i = 0; i < arr.length; i++){
sum += parseInt(arr[i]);
}
var avg = sum/arr.length;
document.getElementById('sum').value = sum;
document.getElementById('avg').value = avg;
}
function clearAll()
{
arr.length = 0;
document.getElementById('a').value = "";
document.getElementById('sum').value = "";
document.getElementById('avg').value = "";
}
</script>
HTML:
<table>
<tr><td><input type="text" id="a"></td>
<td>Sum :<input type="text" id="sum"></td>
<td>Avg :<input type="text" id="avg"></td></tr>
<tr><td><input type="button" value="add" onclick="addNum()"></td>
<td><input type="reset" value="reset" onclick="clearAll()"></td></tr>
</table
Easiest way would be to loop over the inputs showing the numbers and add each number that way, rather than trying to maintain an array that is updated from the first input.
Stick the displaying input elements into a container with an id, then you can do something simple like:
var container = document.getElementById("container-id"),
inputs = container.children,
total;
for (var x = 0, y = inputs.length; x < y; x++) {
total += parseInt(inputs[x].value, 10);
}
alert(total) //do something way better than alert!

Javascript for loop to change the name of textareas in a function

I have created 50 textareas with names def1,def2,def3.....,def50. In my body onLoad() function,I want the same value is set in all these textboxes.
Instead of writing the code 50 times, How can I write some Javascript code to set the value of the textarea, ie in a loop?
I suggest to read the MDC JavaScript guide, as loops and string concatenation are fairly basic operations:
for(var i = 1; i < 51; i++) {
var nameOfTextarea = 'def' + i;
// ...
}
I would give your textboxes ID's (not just names) if possible, and then do something like the following:
var namePrefix = "def";
for(var i = 1; i <= 50; ++i)
{
var textbox = getElementById(namePrefix + i);
// do something to textbox number i.
}
Try jquery for this:
<input type="text" id="t1"/>
<input type="text" id="t2"/>
<input type="text" id="t3"/>
The Jquery code:
var arr = [ "t1", "t2", "t3" ];
jQuery.each(arr, function() {
$("#"+this).val("hello");//$("#" + this).text("hello");
});
Here is the working demo
Try this.
var textareas = document.getElementsByTagName("textarea");
for(var i=0;i<textareas.length;i++){
if(textareas[i].id.indexOf("def") == 0){
textareas[i].value = textareas[i].id;
}
}
You can use tagname property but it will not work if you have some more textbox anywhere else in your page
function loader(){
for(var i=0;i<50;i++)
document.getElementsByName("def"+i)[0].value='Any Value';
}

Categories