How to make automatic input line appender in js? - javascript

I'm having an HTML page with an input line and a submit button.
I'm wanting to automatically generate a new line under the line if we change the first line content.
Before searching for this, I just made a second button named "Add new line" (explicit).
HTML part
print '<input type="button" id="addLineButton" value="Ajouter ligne"/>';
print '<input type="submit" id="valider" value="Rechercher"/>';
JS part
$("#addLineButton").click(function(e){
e.preventDefault();
var newLine = "";
document.getElementById("nbLines").textContent = Number(document.getElementById("nbLines").textContent) + 1;
var nbLines = Number(document.getElementById("nbLines").textContent);
newLine += "<input type='text' id='line"+nbLines+"' placeholder='Ref article'/><input type='number' id='qty"+nbLines+"' placeholder='Qté étiquettes'/><br>"
$("#zoneOF").append(newLine);
});
$("#zoneOF") is a div, and nbLines is a label which is used to count how many lines we already have.
I'm then searching (but not founding because I don't know how to formulate it clearly) what can I do to remove my addLineButton and automate the line adding (surely with on change event).
I wouldn't be surprised if you didn't understood sthg, then don't hesitate to ask me to reformulate.
Thank you in advance.

Ok I resolved it, by simply making my code recursive.
$(document).ready(function(){
var newLine = "";
document.getElementById("nbLines").textContent = Number(document.getElementById("nbLines").textContent) + 1;
var nbLines = Number(document.getElementById("nbLines").textContent);
newLine += "<input type='text' id='line"+nbLines+"' placeholder='Ref article'/><input type='number' id='qty"+nbLines+"' placeholder='Qté étiquettes'/><br>"
$("#zoneOF").append(newLine);
$('#line'+nbLines).on('change', function() {
setNewLine();
});
function setNewLine() {
var newLine = "";
document.getElementById("nbLines").textContent = Number(document.getElementById("nbLines").textContent) + 1;
var nbLines = Number(document.getElementById("nbLines").textContent);
newLine += "<input type='text' id='line"+nbLines+"' placeholder='Ref article'/><input type='number' id='qty"+nbLines+"' placeholder='Qté étiquettes'/><br>"
$("#zoneOF").append(newLine);
$('#line'+nbLines).on('change', function() {
setNewLine();
});
}
I make a new line at the document creation, and I put the on change event on it. The on change calls a function which creates a new line, and the function calls herself when the on change event is triggered on the new line.

Related

getElementByID.onchange not working after i update html with = innerHTML

My starting html looks like this:
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name ="name1"><br>
and i have a variable that captures the html:
var html = "<label> Names: </label><br><input type=\"text\" class=\"form-control name\" placeholder=\"name1\" id=\"name1\" name =\"name1\"><br>"
Then I have an onchange operator that performs a couple functions when the first row has text in it. the .onchange is picked up fine the first time and the subsequent functions are run. I end up with an additional row:
for (n = 1; n < inputLength+1 ; ++n) {
var test2 = document.getElementById(dude+n);
test2.onchange = forFunction
}
function forFunction() {
for (m = 1; m < inputLength+1 ; ++m) {
var test = document.getElementById(dude+m)
if (test.value != "") {
var txt = "<input type=\"text\" class=\"form-control name\" placeholder="+dude+(m+1)+" id="+dude+(m+1)+" name="+dude+(m+1)+"><br>";
document.getElementById('group_names').innerHTML = updateHTML(txt);
//function updateHTML(txt)
}
}
}
var html = "<label> Names: </label><br><input type=\"text\" class=\"form-control name\" placeholder=\"name1\" id=\"name1\" name =\"name1\"><br>"
function updateHTML(txt) {
html = html + txt;
return html;
}
The issue is that after all that completes i end up with two input rows as desired: name1 and name2. However, when i enter text in those fields for a second time, the .onchange is not picked up. but the elements are there in the html when i inspect and view the html.
Also, when i
console.log(inputFormDiv.getElementsByTagName('input').length);
the length of the inputs increases from 1 to 2 after i first run functions (upon the first time i change the value in my input field) so that is getting recognized correctly, just not the .onchange.
thoughts?
The onchange will only work if added to the attribute on the html and the user clicks out of a textbox e.g:
<input onchange="forFunction()" type="text" class="form-control name" placeholder="name1" id="name1" name ="name1">
To add the onchange event in JavaScript code. Add the change event to the addEventListener e.g:
var test2 = document.getElementById(dude+n);
test2.addEventListener('change', forFunction, false)
However if you want the event to fire whilst the user is types a key then use the keypress event. e.g:
var test2 = document.getElementById(dude+n);
test2.addEventListener('keypress', forFunction, false
A basic example: https://jsfiddle.net/xrL6y012/1/
Instead of .innerHTML = html + text do .insertAdjacentHTML('beforeend', text), that way you keep the original html (and events binding).
Edit: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
I had the same problem, it seems like modifying the HTML will never work, regardless of how you do it (.innerHTML or .insertAdjacentHTML()).
The only way that worked for me is to append a child instead of editing the HTML, like so:
const span = document.createElement('span');
span.innerHTML = 'text and <b> html stuff </b>';
initialElement.appendChild(span);
And if you actually need to insert just pure text, then this works:
initialElement.append('just text');
Hope that helps.

Add element works but clears input value

I have a script below that adds an element to my form, another text input field. It adds the new text input field but if I type something into the first one then add a new field it removes the input text from the first one.
I cant see where im going wrong here, im fairly new to JavaScript so please go easy :)
function addAnother() {
var id = 1;
var elemebt = document.getElementById('quest');
var number = elemebt.getElementsByTagName('*').length;
var add = number + 1;
var element = '<input type="text" name="question[]" id="quest'+ add +
'" placeholder="Example: What previous experiance do you have?" class="form-control" id="cloan"><a id="name'+
add +'" onClick="removeEle('+ add +')">Remove</a>';
document.getElementById('quest').innerHTML += element;
}
In JavaScript, the following two statements are practically identical:
str = str + ' more text ';
str += ' more text ';
The key point here is that in the end, the value of str is COMPLETELY OVERWRITTEN.
In your case, that means the innerHTML of the "quest" element is overwritten and the browser completely recreates it's children nodes, thus reseting any state and input values.
To overcome this, you can use the appendChild method but you first need to create the element to append. The easiest way to do that given you have a string of your HTML is to inject that string into a dummy element using the innerHTML property:
var target = document.getElementById('target');
var tDiv = document.createElement('div');
var htmlString = '<input type="text"></input>';
tDiv.innerHTML = htmlString;
target.appendChild(tDiv.children[0]);
<div id="target">Keep my content safe!</div>

Javascript function for form created using Javascript

I have a script which adds a new form when a button is clicked to a HTML page with the code as following:
<script>
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter == limit) {
alert("Max number of forms, " + counter );
}
else
{
var newdiv = document.createElement('div');
newdiv.innerHTML = "<form name='frmMain' action='prelucrare.php' method='POST'><div class='slot' id='dynamicInput' align='center'> Masina " + (counter +1 ) + "<table border='1'><tr><td align='right'><label for='marca'>Marca:</label></td><td colspan='2' align='left'>"
+ "<select id='marc' name='marc'><option selected value=''></option>"
+ "<tr><td align='right'><label for='motorizare1'> Motorizare:</label></td> <td><input type='range' name='motorizare1[]Input' min='0.6' max='5' step='0.1' value=2 id=motor1 oninput='outputUpdate1(value)'></td><td><output for=motorizare1 id=moto1>2</output></td></tr>"
+ "</div></form>"
;
}
document.getElementById(divName).appendChild(newdiv);
counter++;
}
</script>
<input type="button" value="Adauga" onClick="addInput('dynamicInput');">
And I have the script bellow which changes the value from the slider.
<script>
function outputUpdate1(mot1) {
document.querySelector('#moto1').innerHTML = mot1;
}
</script>
My problem is that the JS code only changes the input for the first form, even if the slider is activated from another form. In short, the slider should return the value in the form from which it is activate; not only in the first form added.
Thank you!
Going along with my comment, the problem is stemming from the id value being the same across all of your output elements (moto1). You've actually got all the variables you need to make them unique since you're tracking a count of the number of forms on the page (your counter variable). You can use this in place of your current output HTML:
"<input type='range' name='motorizare1[]Input' min='0.6' max='5' step='0.1' value=2 id='motor_" + counter + "' oninput='outputUpdate1(value)'/>"
"<output for=motorizare1 id='moto_" + counter + "'>"
You can update your function to parse out the correct index for the output you want to update since they should be in sync if you use the HTML above:
function outputUpdate1(mot) {
// Get the counter part of the range element's id
var index = mot.id.split('_')[1];
document.querySelector('#moto_' + index).innerHTML = mot;
}
You may need to make some tweaks to code you haven't provided in the question, but that's one way of making the id values unique and how to access them without knowing the exact id ahead of time.

Split 10 digit number in div into 3,3,4 with jQuery using split or length

Using Digital Bush's maskedInput plugin to format a phone number and then breaking that phone number out of the mask and into a div. I need to split that divs content into 3,3,and 4... i.e. I need to break it into 3 inputs (which will eventually be hidden) to send that back to the server. So far I have everything working except the split and I may be using that wrong instead of breaking it up using length.
Here is a working fiddle of what I have right now:
JS FIDDLE
I have this right here:
<input id="txtPhoneNumber" name="FancyPhoneNumber" class="required phone" type="text" />
<div id="txtHiddenPhoneNumber2"></div>
Which takes the users input and puts the stripped down value (10 numbers) into a div. Then I am taking that div and putting it into three input fields.
$("#txtPhoneNumber").mask("(999) 999-9999");
$("#txtPhoneNumber").blur(function () {
$("#txtHiddenPhoneNumber").val("");
var charArray = $(this).val().split("");
var phoneNumber = "";
$.each(charArray, function(index, value) {
if (!isNaN(value) && value != " ") {
phoneNumber = phoneNumber + value;
}
});
$("#txtHiddenPhoneNumber2").append("<div>"+phoneNumber+"</div>")
var data =$('#txtHiddenPhoneNumber2').text();
var arr = data.match(/.{3}/g);
$("#txtHiddenPhoneNumber2").html("<input type=\"text\" value='"+arr[0] +"'>" + "<input type=\"text\" value='"+arr[1]+"'>" + "<input type=\"text\" value='"+arr[2] +"'>");
});
It's working as I need only it is not sending the last digit to the last input field which is being populated with arr[2]. I assume I am trying to use split wrong. Any ideas?
Try this code
$(document).ready(function() {
$("#txtPhoneNumber").mask("(999) 999-9999");
$("#txtPhoneNumber").blur(function () {
$("#txtHiddenPhoneNumber").val("");
var data =$("#txtPhoneNumber").val();
var arr = data.match(/\d{3,4}/g);
$("#txtHiddenPhoneNumber2").html("<input type=\"text\" value='"+arr[0] +"'>" + "<input type=\"text\" value='"+arr[1]+"'>" + "<input type=\"text\" value='"+arr[2] +"'>");
});
});

Maintaing Input Values in Dynamically Generated Fields

I have the following JavaScript which generates text-inputs dynamically and inserts them into a div. This code works fine, but if I type text into the field, then click the button to add another field I lose the text I typed in the first field.
I made a jFiddle - but for some reason it's not working. The same code works fine in my browser though.
Here's the function in question:
var optCount = 0;
function addOption(type){
var cont = document.getElementById('new'+type+'Opts');
cont.innerHTML = cont.innerHTML + "<span style='display:block;' id='opt" + optCount + "'><input type='text' style='width:80%;' />[x]<br /></span>";
optCount++;
return false;
}
How can I maintain the values of the existing fields when adding additional fields?
Don't replace the entire contents of the div every time. Instead, just create the new option and append it.
var cont = document.getElementById("new"+type+"Opts");
var span = document.createElement('span');
span.className = 'block';
span.id = "opt" + optCount;
span.innerHTML = "<input type='text' class='width80' />[x]<br />";
optCount++;
cont.appendChild(span);
http://jsfiddle.net/ExplosionPIlls/PBp4g/5/

Categories