how to get the values from input fields dynamically - javascript

i have a page in my website that has a form that conatains inputs fields, i also have a button that creates more input fields incase the user needs to inputs more things. the problem now is that if the user makes a mistake and creates inputs feilds that he/she doe not need he can remove them but this creates a problem when inserting the value of the input fields in the database. i am using a for loop to get all the value of the input fields by id eg. id1, id2, id3 etc, but if the user removes one of the inputs field for example id2, i cant get id3 becuase the for loop will still run normally from 1 too the end and will not skip 2.
here is the code to create more input feilds:
let counter = 1;
document.getElementById("shownew").addEventListener("click", (e) => {
e.preventDefault();
// new_section.style.display = "flex";
new_section.insertAdjacentHTML('beforeend',
` <div class="lowerlayer2" id="close${counter}">
<button id="delete" onclick="deleteme(${counter})"><i class="fa fa-minus"></i></button>
<input type="text" placeholder="Word Type" id="wtype${counter}" />
<input type="text" placeholder="Synonym" id="syn${counter}" />
<input type="text" placeholder="Antonyms" id="anty${counter}" />
<textarea
cols="30"
rows="10"
placeholder="History & Etymology"
id="history${counter}"
></textarea>
<textarea
cols="30"
rows="10"
placeholder="Examples"
id="example${counter}"
></textarea>
<textarea
cols="30"
rows="10"
placeholder="Definition 1"
id="def1${counter}"
></textarea>
</div>`
);
counter++;
});
here is the code to delete the input feilds:
function deleteme(id) {
document.getElementById(`close${id}`).style.display="none";
document.getElementById(`close${id}`).innerHTML="";
counter--
}
here is the code to get the values from the values of input fields:
document.getElementById("wan").addEventListener("click", (e) => {
e.preventDefault();
type = "";
syn = "";
anty = "";
history = "";
example = "";
def1 = "";
for (let i = 0; i < counter; i++) {
type += document.getElementById(`wtype${i}`).value + "^";
syn += document.getElementById(`syn${i}`).value + "^";
anty += document.getElementById(`anty${i}`).value + "^";
history += document.getElementById(`history${i}`).value + "^";
example += document.getElementById(`example${i}`).value + "^";
def1 += document.getElementById(`def1${i}`).value + "^";
}
console.log(
type +
" . " +
syn +
" . " +
anty +
" . " +
history +
" . " +
example +
" . " +
def1
);
});

Related

Unable to generate a multiplication table with user input in JavaScript

I have a page which prompts the user to enter a positive integer from 1 to 9, then the javascript code will generate a multiplication table from the input value all the way to 9. I am getting an error in which I cannot retrieve the value and do a multiplication with it.
function timesTable()
{
var values = document.getElementById('value1');
var showTables = '';
for (var i=1; i<9; i++) {
showTables += values + " x " + i +" = "+ values*i + "\n";
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
<label>Enter an integer from 1 to 9 : </label>
<input type="text" size=20 id=value1 name="value">
<button onclick="timesTable()">Generate times table</button><br> <br>
<p id="tables"></p>
Expected result:
You have to take the value of the element not the element itself
var values = document.getElementById('value1').value;
function timesTable()
{
var values = document.getElementById('value1').value;
var showTables = '';
for (var i=1; i<9; i++) {
showTables += values + " x " + i +" = "+ values*i + "<br>";
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
<label>Enter an integer from 1 to 9 : </label>
<input type="text" size=20 id=value1 name="value">
<button onclick="timesTable()">Generate times table</button><br> <br>
<p id="tables"></p>
You are trying to multiply the element itself. What you actually want is the value.
function timesTable()
{
var values = document.getElementById('value1').value;
var showTables = '';
for (var i=1; i<9; i++) {
showTables += values + " x " + i +" = "+ values*i + "\n";
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
<label>Enter an integer from 1 to 9 : </label>
<input type="text" size=20 id=value1 name="value">
<button onclick="timesTable()">Generate times table</button><br> <br>
<p id="tables"></p>
the javascript line in which you are trying to find value, is wrong as it will return the whole DOM and it's attributes and property.
You just have to find it's value, replace you line
var values = document.getElementById('value1');
with
var values = document.getElementById('value1').value;
This does what you want.
Note that if the user enters something unexpected, it may still fail. You can use an input of type="number" to require an integer (at least in some browsers.)
const userValue = document.getElementById("value1").value;
const p_tables = document.getElementById("tables");
let outputHtml = "";
for(let i = 1; i < 10; i++){
outputHtml += userValue + " x " + i + " = " + userValue * i + "<br/>";
}
p_tables.innerHTML = outputHtml;
you are using input field as text for table generation its better to use Number as input type and to get the value of input field you have to use value function as used in above code and for line break use
<\br>(please ignore '\').
function timesTable()
{
var values = document.getElementById('value1').value;
var showTables = '';
for (var i=1; i<=9; i++) {
showTables += values + " x " + i +" = "+ values*i + "<br>";
}
document.getElementById('tables').innerHTML = showTables;
}
<label>Enter an integer from 1 to 9 : </label>
<input type="Number" size=20 id=value1 name="value">
<button onclick="timesTable()">Generate times table</button><br> <br>
<p id="tables"></p>

Javascript remove text input dynamically

Hi i have the following code..where we can add text input dynamically
what i would like to do is add text input and option to remove text input except the default first one
the add text input is working but not the remove text input
https://jsfiddle.net/ob8n48cg/20/
<script>
var counter = 1;
var limit = 3;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
function removeInput(divName){
var newdiv = document.removeElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).removeChild(newdiv);
}
</script>
<form method="POST">
<div id="dynamicInput">
Entry 1<br><input type="text" name="myInputs[]">
</div>
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
<button onclick="removeInput('dynamicInput');">Remove Input</button>
</form>
Try this
var counter = 1;
var limit = 3;
function addInput(divName){
if (counter === limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
function removeInput(event,divName){
event.preventDefault()
var parent = document.getElementById(divName)
parent.removeChild(parent.lastElementChild)
counter--
}
<form>
<div id="dynamicInput">
<div>
Entry 1<br><input type="text" name="myInputs[]">
</div>
</div>
<input type="button" value="Add another text input" onclick="addInput('dynamicInput');">
<button onclick="removeInput(event,'dynamicInput');">Remove Input</button>
</form>
When you run your code, make sure to check the console window in the browser, checking that shows you have an error in your removeInput function:
(index):75 Uncaught ReferenceError: newdiv is not defined
at removeInput ((index):75)
at HTMLButtonElement.onclick ((index):87)
removeInput # (index):75
onclick # (index):87
Make sure to define newdiv in the remove function as well as the add function!

how to serialize a form under specific conditions

Taka a look at this fiddle here this is a form where a business user enters the offered services.I sent the data with ajax and by serializing the form.
Click edit and add(plus sign) a service...in the example an input is added where it's name attribute value is of this **form= form[5]...**contrast with this with the form of the name attribute value in the other inputs...only the newly added services have the name attribute like this and the reason for that is to serialize only these...and not the others already present in the DOM/stored in the DB.
And now my problem:
Imagine that the user goes to edit the already registered services(or that he goes to edit them and add a new one)...at this case the already registered services wont'be serialized cause of the form the name attribute value has...(and the reason for this is explained above).
What can I do in this case?Sometimes I must serialize only part of a form and sometimes whole of the form.If all the inputs have name attribute value of form[1....] then along with the newly added input...already registered services will be serialized again.
Thanks for listening.
Code follows(you can see it in the fiddle too)
$('.editservices').click(function() {
//console.log(('.wrapper_servp').length);
originals_ser_input_lgth = $('.services').length;
var originals = [];
$('.show_price')
// fetch only those sections that have a sub-element with the .value
class
.filter((i, e) => $('.value', e).length === 1)
// replace content in remaining elements
.replaceWith(function(i) {
var value = $('.value', this).data('value');
var fieldsetCount = $('#serv').length;
var index = fieldsetCount + i;
return '<div class="show_price"><p id="show_p_msg">Price
visibility</p></div>' + '\
<div class="show_p_inpts">' +
'<input class="price_show"' + (value == 1 ? "checked" : "") + '
type="radio" name="form[' + index + '][price_show]" value="1">yes' +
'<input class="price_show"' + (value == 0 ? "checked" : "") + '
type="radio" name="form[' + index + '][price_show]" value="0">no' +
'</div>'; // HTML to replace the original content with
});
$('#buttons').removeClass('prfbuttons');
$('#saveserv').addClass('hideb');
$('.actionsserv').removeClass('actionsserv');
priceavail = $(".price_show:input").serializeArray();
});
$('#addser').on('click', function() {
$('#saveserv').css('border','2px solid none');
var serviceCount = $('input.services').length + 1;
var serv_inputs = '<div class="wrapper_servp"><div class="serv_contain">\n\
<input placeholder="service" class="services text" name="form[' + serviceCount + '][service]" type="text" size="40"> \n\
<input placeholder="price" class="price text" name="form[' + serviceCount + '][price]" type="text" size="3"></div>';
var p_show = '<div class="show_p">' +
'<p id="show_p_msg">Price visibility;</p>' +
'<span id="err_show_p"></span><br>' +
'</div>';
var inputs = '<div class="show_p_inpts">' +
'<input class="price_show" type="radio" name="form[' + serviceCount + '][price_show]" value="1">yes' +
'<input class="price_show" type="radio" name="form[' + serviceCount + '][price_show]" value="0">no' +
'</div></div>';
$('.wrapper_servp').last().after(serv_inputs + p_show + inputs);
$('#saveserv').removeClass('hideb');
$('#remser').css('display', 'inline');
});
$('#cancelserv').click(function(e) {
e.preventDefault();
//var newinputs = $('.wrapper_servp').length;
//var inp_remv = newinputs - originals_ser_input_lgth;
//$('.wrapper_servp').slice(-inp_remv).remove()
$('.show_p_inpts')
.filter((i, e) => $('.price_show:checked', e).length === 1)
.replaceWith(function(i) {
var value = $('.price_show:checked').attr('value');
return '<span data-value="' + value + '" class="value">' + (value == 1 ? "yes" : "no") + '</span>'
});
});
var groupHasCheckedBox = function() {
return $(this).find('input').filter(function() {
return $(this).prop('checked');
}).length === 0;
},
inputHasValue = function(index) {
return $(this).val() === '';
};
$('#saveserv').click(function(e) {
e.preventDefault();
//from here
var $radioGroups = $('.show_p_inpts');
$('.show_p_inpts').filter(groupHasCheckedBox).closest('div').addClass("error");
$('.services, .price').filter(inputHasValue).addClass("error");
//to here
var $errorInputs = $('input.services').filter((i, e) => !e.value.trim());
if ($errorInputs.length >= 1) {
console.log($errorInputs);
$('#err_message').html('you have to fill in the service'); return;
}
if ($('input.price').filter((i, e) => !e.value.trim()).length >= 1) {
$('#err_message').html('you have to fill in the price'); return;
}
});
var IDs=new Array();
$('body').on('click', '#remser', function(e){
var inputval=$('.services:visible:last').val();
if(inputval!=='')
{r= confirm('Are you sure you want to delete this service?');}
else
{
$('.wrapper_servp:visible:last').remove();
}
switch(r)
{
case true:
IDs.push($('.services:visible:last').data('service'));
$('.wrapper_servp:visible:last').addClass('btypehide');
if($('.serv_contain').length==1)$('#remser').css('display','none');
$('#saveserv').removeClass('hideb').css('border','5px solid red');
//originals.servrem=true;
break;
case false:var i;
for(i=0;i<originals.ser_input_lgth;i++)
{
$('input[name="service'+i+'"]').val(services[i].value);
$('input[name="price'+i+'"]').val(prices[i].value);//εδω set value
}
$('.services').slice(originals.ser_input_lgth).remove();
$('.price').slice(originals.ser_input_lgth).remove();
$('.openservices').addClass('hide').find('.services,.price').prop('readonly', true);
var text='<p class="show_price">Θες να φαίνεται η τιμή;<span data-value="'+ show_pr_val.value +'" class="value">' +(show_pr_val.value==1 ? 'yes':'no') + '</span></p>';
$('.show_p_inpts').remove();
$('.show_price').replaceWith(text);;
break;
}
});
I have an Idea for you. What you can do is when you show the currently existed value in you html instead of giving name attribute just give data-name attribute. I.e
Change this
<input class="services text" data-service="21" size="40" value="hair" type="text" name="service0" readonly="">
To This
<input class="services text" data-service="21" size="40" value="hair" type="text" data-value="hair" data-name="service0" readonly="">
Now when user update this values you can bind an event in jQuery like below.
$(document).ready(function(){
$(".services input").on("change paste keyup", function() {
if($(this).val() === $(this).attr("data-value"))
{
$(this).removeAttr("name");
}else{
$(this).attr("name",$(this).attr("data-name"));
}
});
});
By this way you can give name attribute to only those elements whose values are changed. Now each time you can serialize the whole form and it will only get the value of changed elements.
Don't forget to give unique class to already existed elements so you can bind on change event. Hope its clear to you.

JavaScript For Loop Round Form Input Fields

I'm currently working on creating an expenses form and am writing a function to validate the entered data.
I allow for 6 expense amounts to be entered and a description on each and onClick of the submit button I am trying to write a for loop that will loop round the amount fields, check if they are numeric and, if they are, then check to ensure a description has been entered.
The form basically looks like:
<form action="##" name="myForm" id="myForm" method="post">
<input type="text" name="otherExpenseDesc1" id="otherExpenseDesc1">
<input type="text" name="otherExpenseAmount1" id="otherExpenseAmount1">
<input type="text" name="otherExpenseDesc2" id="otherExpenseDesc2">
<input type="text" name="otherExpenseAmount2" id="otherExpenseAmount2">
<input type="text" name="otherExpenseDesc3" id="otherExpenseDesc3">
<input type="text" name="otherExpenseAmount3" id="otherExpenseAmount3">
<input type="text" name="otherExpenseDesc4" id="otherExpenseDesc4">
<input type="text" name="otherExpenseAmount4" id="otherExpenseAmount4">
<input type="text" name="otherExpenseDesc5" id="otherExpenseDesc5">
<input type="text" name="otherExpenseAmount5" id="otherExpenseAmount5">
<input type="text" name="otherExpenseDesc6" id="otherExpenseDesc6">
<input type="text" name="otherExpenseAmount6" id="otherExpenseAmount6">
<input type="submit" name="formSubmitBtn" value="SUBMIT" onClick="checkForm();">
</form>
And the javascript I have at the moment is:
function checkForm() {
var errMsg = "";
var otherExpense1 = document.getElementById('otherExpenseAmount1').value;
var otherExpenseDesc1 = document.getElementById('otherExpenseDesc1').value;
var otherExpense2 = document.getElementById('otherExpenseAmount2').value;
var otherExpenseDesc2 = document.getElementById('otherExpenseDesc2').value;
var otherExpense3 = document.getElementById('otherExpenseAmount3').value;
var otherExpenseDesc3 = document.getElementById('otherExpenseDesc3').value;
var otherExpense4 = document.getElementById('otherExpenseAmount4').value;
var otherExpenseDesc4 = document.getElementById('otherExpenseDesc4').value;
var otherExpense5 = document.getElementById('otherExpenseAmount5').value;
var otherExpenseDesc5 = document.getElementById('otherExpenseDesc5').value;
var otherExpense6 = document.getElementById('otherExpenseAmount6').value;
var otherExpenseDesc6 = document.getElementById('otherExpenseDesc6').value;
for (i=1; i<7; i++) {
expenseNo = 'otherExpense' + i;
expenseDescNo = 'otherExpenseDesc' + i;
if (expenseNo != "") {
if (isNaN(expenseNo)) {
alert(expenseNo + ' is not a number');
errMsg = errMsg + 'The amount must be a number.<br />';
document.getElementById('otherExpenseAmount' + i).style.border = '2px sold #990000';
} else {
alert('otherExpenseAmount' + i + ' is a number');
document.getElementById('otherExpenseAmount' + i).style.border = '2px sold #990000';
}
}
}
if (errMsg != "") {
showDialog('alert', 'OK', '', errMsg, '');
}
}
When I'm submitting the form with valuesin a couple of the fields it still displays an alert for each otherExpenseAmount item saying that it is not numeric, although it is, and the border style doesn't change.
Any idea where I'm going wrong?
You're trying to access a variable with a string. You should change your code to utilise arrays, something like this:
jsFiddle
function checkForm() {
var errMsg = "";
var otherExpense = [];
otherExpense.push(document.getElementById('otherExpenseAmount1').value);
otherExpense.push(document.getElementById('otherExpenseAmount2').value);
otherExpense.push(document.getElementById('otherExpenseAmount3').value);
otherExpense.push(document.getElementById('otherExpenseAmount4').value);
otherExpense.push(document.getElementById('otherExpenseAmount5').value);
otherExpense.push(document.getElementById('otherExpenseAmount6').value);
// 0-based index for arrays
for (i=0; i<6; i++) {
if (otherExpense[i] != "") {
if (isNaN(otherExpense[i])) {
alert('otherExpense ' + (i + 1) + ' is not a number (=' + otherExpense[i] + ')');
errMsg = errMsg + 'The amount must be a number.<br />';
document.getElementById('otherExpenseAmount' + (i + 1)).style.border = '2px sold #990000';
} else {
alert('otherExpenseAmount' + (i + 1) + ' is a number');
document.getElementById('otherExpenseAmount' + (i + 1)).style.border = '2px sold #990000';
}
}
}
if (errMsg != "") {
alert(errMsg);
//showDialog('alert', 'OK', '', errMsg, '');
}
return false;
}
Your problem is on these lines; you're setting the border to be the same, regardless of the condition (easy mistake to make).
if (isNaN(expenseNo)) {
alert(expenseNo + ' is not a number');
errMsg = errMsg + 'The amount must be a number.<br />';
document.getElementById('otherExpenseAmount' + i).style.border = '2px sold #990000';
// -----------------------------------------------------------------------------^^^^^^
} else {
alert('otherExpenseAmount' + i + ' is a number');
document.getElementById('otherExpenseAmount' + i).style.border = '2px sold #990000';
// -----------------------------------------------------------------------------^^^^^^
}
Suggestion
I hate to be that guy.
Have you considered adopting jQuery? It's perfectly designed for tasks such as this.
Utilising methods such as filter and simple selectors, it's easy to determine whether all inputs fulfil your requirements. Here's an example:
// select all inputs with a class of "number"
// then filter those inputs, selecting only those where the value is "not a number"
// if there is a length, i.e. more than 0 were found, alert a message
if ($('input.number').filter(function() { return isNaN(this.value); }).length) {
alert('Please ensure all numbers are valid');
}
This would obviously require you to make small amendments to your HTML, by adding the number class to the required elements, but it's a small sacrifice to make.
jsFiddle demo

how to control for loop

this is my code......initially alltextboxes is showing...if i click the next or prev button it works properly....but i want only two textboxes per each click so initialy should show two text box ..........how i get it........how to solve......
see for full code:http://jsfiddle.net/sankarss/gAVZ8/22/
function starts(values)
{
maximum=values;
var form = document.forms[0];
var container = $("#sankar");
container.empty();
for (var i = 0; i < maximum; i++)
container.append('<fieldset style="width: 250px; height: 80px;"><legend>Files of ' +(i + 1) + ' / ' + maximum + '</legend><input type="text" name="name' + i + '" /><br /><br /><input type="text" name="topic' + i + '" /></fieldset>');
goto(form, 0);
}
Simply put this code under the for() line:
if(i>=2){
continue;
}
Ad#m

Categories

Resources