Validate dynamically generated input box with dynamic ID and name - javascript

I have a button that adds two input field onclick. Below is the code:
<button type="button" class="btn btn-warning btn-xs" id="additem">
Click here to add Items</button>
<form>
<div id="inputboxes"></div>
<input type="submit">
</form>
and JQuery is
var i = 1,
j = 1,
k = 1,
l = 1;
$("#additem").click(function () {
$("#inputboxes").append("<div class='form-group'><input type='text' id='iname" +
(j++) +
"' name='iname" +
(i++) +
"' class='form-control' placeholder='Enter Item Name' required='required'/></div> " +
"<div class='form-group'><input type='text' id='iprice" +
(k++) +
"' name='iprice" +
(l++) +
"' class='form-control' placeholder='Enter Item Price' required='required'/></div>");
})
How can i validate these dynamically added input boxes for empty and correct values on submitting the form?

You can do something like:
$('.form-group').each(function(){
var input = $(this).children('input');
if(input.val() == '' || input.val() == undefined){
// the errors you will give
}else{
if(input.attr('id').substring(0, 5) == 'iname'){
//function to validate your iname
}else if(input.attr('id').substring(0, 6) == 'iprice'){
//function to validate your iprice
}
}
});

Related

How can I replace a variable in one method from another method

I am working a project where I can add checkboxes but at first I make a textbox and then I press done and then the another button will replace that textbox with the value of that textbox.
When I have them in different methods the variable is not defined and when I put it in the same method it prints out in the console as twice the ids I need.
The first one below is the one that doubles the id - look at the console For both.
$("#addBtn").click(function() {
var lastField = $("#buildyourform div:last"); // Getting the id of #buildyourownform and getting the last div
var intId = (lastField && lastField.length && lastField.data("idx") + 1) || 1; // Changing the Id
const fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
fieldWrapper.data("idx", intId);
// console.log(intId);
var fName = $("<input type=\"text\" class=\"fieldname\" />");
var ftype = $("<input type=\"checkbox\" class=\"giannisCheckbox\" />");
fieldWrapper.append(ftype);
fieldWrapper.append(fName);
$("#buildyourform").append(fieldWrapper);
$("#doneBtn").click(function() {
// $("#yourform").remove();
$("#buildyourform div").each(function() {
var id = "checkbox" + $(this).attr("id").replace("field", "");
console.log(id);
var label = $("<label for=\"" + id + "\">" + $(this).find("input.fieldname").first().val() + "</label>");
fName.replaceWith(label);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" id="addBtn" value="Add" />
<input type="button" id="doneBtn" value="Done" />
<fieldset id="buildyourform"></fieldset>
$("#addBtn").click(function() {
var lastField = $("#buildyourform div:last"); // Getting the id of #buildyourownform and getting the last div
var intId = (lastField && lastField.length && lastField.data("idx") + 1) || 1; // Changing the Id
const fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
fieldWrapper.data("idx", intId);
// console.log(intId);
var fName = $("<input type=\"text\" class=\"fieldname\" />");
var ftype = $("<input type=\"checkbox\" class=\"giannisCheckbox\" />");
fieldWrapper.append(ftype);
fieldWrapper.append(fName);
$("#buildyourform").append(fieldWrapper);
});
$("#doneBtn").click(function() {
// $("#yourform").remove();
$("#buildyourform div").each(function() {
var id = "checkbox" + $(this).attr("id").replace("field", "");
// console.log(id);
var label = $("<label for=\"" + id + "\">" + $(this).find("input.fieldname").first().val() + "</label>");
fName.replaceWith(label);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" id="addBtn" value="Add" />
<input type="button" id="doneBtn" value="Done" />
<fieldset id="buildyourform"></fieldset>
Try this
let $buildyourform = $("#buildyourform");
$("#addBtn").click(function() {
let intId = $buildyourform.children().length + 1;
$("#buildyourform").append(`
<div class="fieldwrapper" id="field${intId}">
<input type="checkbox" class="giannisCheckbox" />
<input type="text" class="fieldname" />
</div>
`);
});
$("#doneBtn").click(function() {
$buildyourform.children().each(function() {
let $checkbox = $(this).find('.giannisCheckbox');
let $fieldname = $(this).find('.fieldname');
let id = "checkbox" + $(this).attr("id").replace("field", "");
$checkbox.attr('id', id);
$fieldname.replaceWith(`<label for="${id}">${$fieldname.val()}</label>`);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" id="addBtn" value="Add" />
<input type="button" id="doneBtn" value="Done" />
<fieldset id="buildyourform"></fieldset>

how to get the values from input fields dynamically

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
);
});

How to send a table html as a serialize array to database?

I want to send my javascript and dynamic table to my database as a text variable.
I explained whatever I did:
I used jquery to get the values
Then I stored HTML table values in a java script array
I converted javascript array to JSON format
I sent JSON array to a php script by JQuery AJAX
But, I don’t know how to send it to database?
Here is my code:
function readTblValues() {
var TableData = '';
$('#tbTableValues').val(''); // clear textbox
$('#tblDowntimes tr').each(function(row, tr) {
TableData = TableData +
$(tr).find('td:eq(1)').text() + ' ' // downtime
+
$(tr).find('td:eq(2)').text() + ' ' // equipment
+
$(tr).find('td:eq(3)').text() + ' ' // starttime
+
$(tr).find('td:eq(4)').text() + ' ' // finishtime
+
$(tr).find('td:eq(5)').text() + ' ' // descriptio
+
'\n';
});
$('#tbTableValues').html(TableData);
}
function storeAndShowTableValues() {
var TableData;
TableData = storeTblValues();
$('#tbTableValuesArray').html('<br>JS Array: <br>' + print_r(TableData));
}
function storeTblValues() {
var TableData = new Array();
$('#tblDowntimes tr').each(function(row, tr) {
TableData[row] = {
"DOWNTIME": $(tr).find('td:eq(1)').text(),
"equipment": $(tr).find('td:eq(2)').text(),
"startdowntime": $(tr).find('td:eq(3)').text(),
"finishdowntime": $(tr).find('td:eq(4)').text(),
"description": $(tr).find('td:eq(5)').text()
}
});
TableData.shift(); // first row will be empty - so remove
return TableData;
}
function convertArrayToJSON() {
var TableData;
TableData = $.toJSON(storeTblValues());
$('#tbConvertToJSON').html('<br>JSON array: <br>' + TableData.replace(/},/g, "},<br>"));
}
function sendTblDataToServer() {
var TableData;
TableData = $.toJSON(storeTblValues());
$('#tbSendTblDataToServer').val('JSON array to send to server: <br<br>' + TableData.replace(/},/g, "},<br>"));
$.ajax({
type: "POST",
url: "test.php",
data: "pTableData=" + TableData, // post TableData to server script
success: function(msg) {
// return value stored in msg variable
$('#tbServerResponse').html('Server Response:<br><br><pre>' + msg + '</pre>');
}
});
}
function print_r(arr, level) {
var dumped_text = "";
if (!level)
level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for (var j = 0; j < level + 1; j++)
level_padding += " ";
if (typeof(arr) === 'object') { //Array/Hashes/Objects
for (var item in arr) {
var value = arr[item];
if (typeof(value) === 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "' \n";
dumped_text += print_r(value, level + 1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>" + arr + "<===(" + typeof(arr) + ")";
}
return dumped_text;
}
<html>
<head>
</head>
<body>
<form name="data-entry" method="post" action="data-entry.php">
<input id="product-name" name="product-name" />
<input id="product-quantity" name="product-quantity" />
<input name="Downtime" id="Downtime" />
<input name="equipment" id="equipment" />
<input type='time' name='startdowntime' id='startdowntime' />
<input type='time' name='finishdowntime' id='finishdowntime' />
<input type='text' name='description' id='description' />
<input type="button" value="add rows" id="btnAdd" onclick="addDowntime(this)" />
<input type="button" value="remove rows" onclick="deleteSelected()" />
<table id="tblDowntimes" class="downtime">
<tr>
<th><input type="checkbox" id="chkAll" onclick="chkAll_click(this)" /></th>
<th>downtime</th>
<th>equipment</th>
<th>start-time</th>
<th>finih-time</th>
<th>description</th>
</tr>
</table>
<input type="button" value="1. Read Table Values" name="read" onClick="readTblValues()" />
<input type="button" value="2. Store values in JS Array" name="store" onClick="storeAndShowTableValues()" />
<input type="button" value="3. Convert JS Array to json" name="convert" onClick="convertArrayToJSON()" />
<input type="button" value="4. Send json array to Server" name="send" onClick="sendTblDataToServer()" />
<div id="tbTableValues"></div>
<div id="tbTableValuesArray"></div>
<div id="tbConvertToJSON"></div>
<div id="tbServerResponse"></div>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
and Here is my php code:
function processJSONArray() {
$tableData = stripcslashes($_POST['pTableData']);
$tableData = json_decode($tableData);
var_dump($tableData);
}
echo processJSONArray();
With aforementioned code, I manage to get the array in client side, but when I use this code that error is appeared (Undefined variable: tableData)
if(isset($_POST[‘submit’])){
echo $tableData;
}

I want to remove an array item when generated check box checked

I made a todolist which is taking value from input and add an item from array so when the given value shown in page i want to remove an item form array whn checkbox checked.
Html part :
<input type="text" id="field" placeholder="Type name" />
<button type="submit" onclick="insertitem()">Submit</button>
<p id="para"></p>
javascript part:
var list = [];
var input;
function insertitem() {
input = document.getElementById('field').value;
list.push(input);
DisplayItem(list);
document.getElementById('field').value='';
}
function DisplayItem(data) {
var contain = document.getElementById('para');
contain.innerHTML='';
for ( var i in data) {
contain.innerHTML +="<div><input id='box' onClick='remove()' type='checkbox' /><label>" + data[i] + "</label></div>";
}
}
function remove() {
var check = document.getElementById('box').value;
for ( var i in list) {
if (list[i]!= check) {
}
}
}
Try this with pure javascript :
Array.splice and Array.indexof()
Add with checkbox inside the label tag.
And click event change with remove(this).Then easly find the label
text and match with list array.
contain.innerHTML +="<div><label><input id='box' onClick='remove(this)' type='checkbox' />" + data[i] +
"</label></div>";
}
var list = [];
var input;
function insertitem() {
input = document.getElementById('field').value;
list.push(input);
DisplayItem(list);
document.getElementById('field').value='';
}
function DisplayItem(data) {
var contain = document.getElementById('para');
contain.innerHTML='';
for ( var i in data) {
contain.innerHTML +="<div><label><input id='box' onClick='remove(this)' type='checkbox' />" + data[i] +
"</label></div>";
}
}
function remove(that) {
var check = that.parentElement.textContent;
//that.remove() if you need remove clicked box
for ( var i in list) {
if (list[i] == check) {
list.splice(list.indexOf(check),1);
}
}
console.log(list)
}
<input type="text" id="field" placeholder="Type name" />
<button type="submit" onclick="insertitem()">Submit</button>
<p id="para"></p>
var list = [];
var input;
function insertitem() {
input = document.getElementById('field').value;
list.push(input);
DisplayItem(list);
document.getElementById('field').value='';
}
function DisplayItem(data) {
var contain = document.getElementById('para');
contain.innerHTML='';
for ( var i in data) {
contain.innerHTML +="<div id='remove" + i + "'><label for='box" + i + "'><input id='box" + i + "' onClick='remove(" + i + ")' type='checkbox' />" + data[i] + "</label></div>";
}
}
function remove(targetId) {
var check = document.getElementById('box' + targetId).checked;
if(check){
console.log('Remove box' + targetId);
document.getElementById('remove' + targetId).innerHTML='';
}
}
<input type="text" id="field" placeholder="Type name" />
<button type="submit" onclick="insertitem()">Submit</button>
<p id="para"></p>
I just modified your JavaScript to pass an ID with a number to set each label apart from each other..

how to build dynamic form builder with jquery

I want to develop a dynamic form builder with jquery where users can build their own form and change form name, input type, size etc. I know there are some cool drag and drop online form builders but i want to develop a very simple form builder .
I already have started to develop this and i am facing some issues.
when user will click on the label(input field) it create an input field dynamically with jquery with edit and delete button.
The code below is appending input field in a div which is empty right now.
$(document).ready(function() {
$(".text").click(function(){
$("#textInput").append('<input class="form-control" type="text">' + '<input class="btn btn-default" type="button" value="Edit" id="editbtn"><input class="btn btn-default" type="button" value="Delete" >' ).show().css('display', 'block')});
});
.items {
border: 1px solid lightgray;
display: none;
padding: 0 10px 10px 10px;
}
<div class="items" id="textInput">
<h3>Your Form</h3>
<hr>
</div>
On clicking the text input i want to display a table or modal where user can save changes to input field first of all the edit button is not working and secondly how to edit and save changes to input field(how the process will work).
This is what i want to achieve
I have been working on dynamic form builder and borrowed ideas from some excellent open-source solutions.
They do it in this way:
describe form structure as JSON in the backend.
then use one of the following libraries to render JSON to form in the frontend.
jsonform/jsonform
source code: jsonform/jsonform
example:
rjsf-team/react-jsonschema-form
source code: https://github.com/rjsf-team/react-jsonschema-form
I'd suggest you to look at schema-to-form libraries (for example some of those described in here How to Create a form from a json-schema?).
There are multiple benefits of using such libraries, some of which are flexible layout capabilities, as well as validation hooks.
What is more, your editor has to work with JSON structure only and rendering a form from it is not your main headache.
I did this using JQuery, HTML and Bootstrap
the form was built to be as dynamic as possible and built also to me modified
there is a script to submit the form via ajax
function d(object) {
const id = $(object).data('check');
$('#' + id).remove();
}
//picks and submits form inputs
$(document).ready(function() {
$('form.myForm').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
}
});
return false;
});
});
$(function() {
//here i will populate the appendi field if the user selects file
//the user should select the file type
$('#type').on('change', function() {
let type = $("#type option:selected").val();
var add;
if (type === 'file') {
//here i will append the new option in the appendi part
add = "<label for=\"\">What type of file?</label>";
add += "<select name=\"image_type\" id=\"\" class=\"form-control\">";
add += "<option value=\"all\">All</option>";
add += "<option value=\"image\">Image</option>";
add += "<option value=\"document\">Document</option>";
add += "</select>";
$('#appendi').html(add);
}
if (type === 'radio' || type === 'checkbox') {
//here i will append the new option in the appendi part
add = "<label for=\"\">Enter the names of the option separated by a comma (,)</label>";
add += "<textarea col=\"\" class=\"form-control\" row=\"\" name=\"options\" required></textarea>";
$('#appendi').html(add);
}
if (type === 'paragraph' || type === 'text') {
$('#appendi').empty();
}
})
})
$(document).ready(function() {
$('form.myInput').on('submit', function() {
var that = $(this),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
addBody(data);
return false;
});
});
function addBody(data) {
//first thing first is to generate an outer shell
let id_tag = "shell_" + generateId(8);
let shell1_open = "<div class='form-group' " + "id = '" + id_tag + "'>";
shell1_open += "<button type='button' onclick='d(this)' id=\"delete\" data-check='" + id_tag + "'><i class=\"fa-minus-square\">remove</i></button>"
let shell1_close = "</div>";
let shell2, label, shell2_close;
if (data.type === 'text' || data.type === 'date' || data.type === 'file' || data.type === 'email') {
shell2 = "<input type='";
shell2 += data.type + "'";
shell2_close = ">";
}
if (data.type === 'paragraph') {
shell2 = "<textarea";
shell2_close = "></textarea>";
}
if (data.type === 'radio') {
let myArr = data.options.split(",");
shell2 = '';
let name = 'input_' + generateId(5) + '_' + data.name.replace(/\s+/g, '');
for (let i = 0; i < myArr.length; i++) {
shell2 += "<input type='radio'";
shell2 += "value ='" + myArr[i] + "'";
shell2 += "name ='" + name + "'";
//add a class to it
shell2 += " class = 'form-control'";
if (data.required === 'yes') {
shell2 += " required";
}
shell2 += ">" + myArr[i];
}
shell2_close = "";
}
if (data.type === 'checkbox') {
let myArr = data.options.split(",");
shell2 = '';
for (let i = 0; i < myArr.length; i++) {
shell2 += "<input type='checkbox'";
shell2 += "value ='" + myArr[i] + "'";
shell2 += " name='" + 'input_' + generateId(5) + '_' + data.name.replace(/\s+/g, '') + "'";
//add a class to it
shell2 += " class = 'form-control'";
if (data.required === 'yes') {
shell2 += " required";
}
shell2 += ">" + myArr[i];
}
shell2_close = "";
}
if (data.image_type) {
if (data.image_type === 'all') {
shell2 += " accept";
}
if (data.image_type === 'image') {
shell2 += " accept='.jpeg, .png'";
}
if (data.image_type === 'document') {
shell2 += " accept='.pdf, .xls, .docx'";
}
}
if (data.type !== 'radio' && data.type !== 'checkbox') {
if (data.required === 'yes') {
shell2 += " required";
}
/**
* after thinking i decided to map the name the user chose to the placeholder/label
* and squash the name to get the input name, so to remove whitespaces
* also i'll append input_ to all input names
*/
shell2 += " name='" + 'input_' + generateId(5) + '_' + data.name.replace(/\s+/g, '') + "'";
//add a class to it
shell2 += " class = 'form-control'";
//add placeholder
shell2 += " placeholder = '" + data.name + '\'';
}
$('#main-form-body').append(shell1_open + shell2 + shell2_close + shell1_close)
//console.log(shell1_open + shell2 + shell2_close +shell1_close);
}
function dec2hex(dec) {
return dec.toString(16).padStart(2, "0")
}
// generateId :: Integer -> String
function generateId(len) {
var arr = new Uint8Array((len || 40) / 2)
window.crypto.getRandomValues(arr)
return Array.from(arr, dec2hex).join('')
}
<html>
<head>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
Add input
</button>
<form action="" method="post" class="myForm">
<div id="main-form-body">
</div>
<button type='submit'>Submit</button>
</form>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Add form input</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<form action="" method="get" class="myInput">
<!-- Modal body -->
<div class="modal-body">
<div class="form-group">
<label for="">What should this be called?</label>
<input type="text" name="name" class="form-control">
</div>
<div class="form-group">
<label for="">What type of data will it hold?</label>
<select name="type" id="type" class="form-control">
<option value="text">Text</option>
<option value="paragraph">Paragraph</option>
<option value="file">File</option>
<option value="radio">Radio</option>
<option value="checkbox">Checkbox</option>
<option value="date">Date</option>
</select>
</div>
<div class="form-group" id="appendi">
</div>
<div class="form-group">
<label>Should it be a required field?</label>
<select name="required" id="" class="form-control">
<option value="yes">yes</option>
<option value="no">no</option>
</select>
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Add</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</html>
enter image description hereYou can use this form builder..
it's available in github
https://github.com/vimal33329/Formbuilder
live url link
https://vimal33329.github.io/Formbuilder/
if you already familiar with github use git clone below code
https://github.com/vimal33329/Formbuilder.git
or download source file by clicking below link...
https://github.com/vimal33329/Formbuilder/archive/refs/heads/main.zip
Form with report
Create form, Build form, Enable or disable Form Submission, Dynamic Option creating,
View Form Report in report page, Drag and Drop position changing...
https://vimal-form.herokuapp.com
enter image description here
enter image description here
enter image description here
enter image description here

Categories

Resources