The following block of code is not working.
instead of creating a list element with the text thats coming from the input, it just creates a text and appends it without creating a list element.
Can someone see where my mistake is?
var button = document.querySelector('#btn');
button.addEventListener('click', handleClick);
function handleClick(e) {
e.preventDefault();
var name=document.querySelectorAll('#item');
for (let i=0; i<name.length; i++) {
var x=name[i].value;
var item= document.createElement('li')
item.className="list-group-item";
var text= document.createTextNode(x);
var addList=item.appendChild(text);
var ul=document.getElementById('items').appendChild(addList);
console.log(document.getElementById('main').childNodes)
name[i].value='';
}
}
<div class="container">
<div id="main" class="card card-body">
<h2 class="title ">Create Contact
</h2>
<form id="addForm" class=" mb-3">
<input type="text" class="form-control mr-2 my-3" id="item" placeholder="First Name" required>
<input type="text" class="form-control mr-2 my-3" id="item" placeholder="Last Name" required>
<h6 id='warning' style="display:none">All fields are required.</h6>
<button id="btn" class="btn btn-dark">Create</button>
</form>
<h2 class="title">Items</h2>
<ul id="items" class="list-group">
<li class="list-group-item">x</li>
<li class="list-group-item" >y</li>
<li class="list-group-item" >z</li>
<li class="list-group-item" >g</li>
</ul>
</div>
</div>
var name=document.querySelectorAll('#item');
.querySelectorAll() is for getting more than one element.
# means id.
ID's must be unique within a document.
A button's default type is submit, which you don't want here. A
regular button is what you need.
See additional HTML, CSS, and JavaScript comments inline below:
// Get references to the elements you'll need just once:
let warning = document.getElementById("warning");
let fName = document.getElementById("fName");
let lName = document.getElementById('lName');
let list = document.getElementById("items");
// Set up event handler
document.getElementById("btn").addEventListener('click', handleClick);
function handleClick(){
// Check to see if required fields have data
if(fName.value == "" || lName.value == ""){
warning.classList.remove("hidden"); // Invalid! Show message
return; // Exit function
} else {
warning.classList.add("hidden"); // Valid! Hide message
}
// There's only two elements to worry about and each has a unique id
// so just do the work on each. A loop is overkill here.
// First name
var li= document.createElement('li')
li.className="list-group-item";
li.textContent = fName.value; // No need for a text node. Just set the text content
items.appendChild(li);
fName.value = "";
// Last Name
li= document.createElement('li')
li.className="list-group-item";
li.textContent = lName.value;
items.appendChild(li);
lName.value = "";
//console.log(document.getElementById('main').innerHTML)
}
/* CSS does all the layout and styling */
#warning { font-weight:bold; color:red; }
.hidden { display:none; }
<div class="container">
<div id="main" class="card card-body">
<h2 class="title ">Create Contact
</h2>
<form id="addForm" class=" mb-3">
<input type="text" class="form-control mr-2 my-3" id="fName" placeholder="First Name" required>
<input type="text" class="form-control mr-2 my-3" id="lName" placeholder="Last Name" required>
<!-- You need a regular button here. Not the default type, which is a submit. -->
<button type="button" id="btn" class="btn btn-dark">Create</button>
<!-- Heading elements (h1...h6) are to create sections of a document. You can't
have section 6 unless you've already had sections 1 - 5. Don't use heading
tags because of the way they make the text look. Style is CSS's job. -->
<div id='warning' class="hidden">All fields are required.</div>
</form>
<h2 class="title">Items</h2>
<ul id="items" class="list-group">
<li class="list-group-item">x</li>
<li class="list-group-item" >y</li>
<li class="list-group-item" >z</li>
<li class="list-group-item" >g</li>
</ul>
</div>
</div>
Related
I'm finding a strange behaviour in a popup FORM when I click on a BUTTON (that operates on some object using a JS code), and on a INPUT (used for submit): in both cases, the form closes, and it is an unexpected action.
Probably is due to something very easy and common that I'm not fixing, but i can't find it.
This is the HTML interested part:
<form name="contactform" id="contactform" class="contact-form">
<div class="contactform-container">
<div class="common">
<label for="name">Nome</label>
<input type="text" id="name" name="name" />
</div>
<div class="common">
<label for="name">Cognome</label>
<input type="text" id="familyName" name="familyName" />
</div>
<div class="common">
<label for="email">e-mail</label>
<input type="text" id="email" name="email" />
</div>
<div class="message">
<label for="message">Annotazioni</label>
<textarea name="message" id="message" class="message"></textarea>
</div>
<div class="passRow">
<fieldset class="validatePass">
<div class="formGroup">
<label class="formLabel"for="password">Password
<span class="passErr"></span>
</label>
<div class="passWrapper">
<input type="password"
id="password"
class="form-control input-md"
name="password"
placeholder="Enter your password">
<span class="showPass">
<i class="fas fa-eye-slash"></i>
</span>
</div>
<p class="progress">Livello di sicurezza</p>
<div id="progressBar">
<div></div>
</div>
<ul id="progressList">
<li>Un carattere minuscolo e uno maiuscolo</li>
<li>Un numero</li>
<li>Un carattere speciale tra "!,%,&,#,#,$,^,*,?,_,-"</li>
<li>Lunghezza minima: 8 caratteri</li>
</ul>
</div>
</fieldset>
</div>
<div class="securityCaptcha">
<p>Inserire il codice nei riquadri sottostanti</p>
<div class="first row">
<div class="refCheck">
<canvas class="valiCaptcha"></canvas>
</div>
<div class="refCheck">
<canvas class="valiCaptcha"></canvas>
</div>
<div class="refCheck">
<canvas class="valiCaptcha"></canvas>
</div>
<div class="refCheck last">
<canvas class="valiCaptcha"></canvas>
<button class="reloadButton">
<i class="fas fa-redo"></i>
</button>
</div>
</div>
<div class="second row">
<div class="refCheck">
<input type="text" name="" maxlength="1">
</div>
<div class="refCheck">
<input type="text" name="" maxlength="1">
</div>
<div class="refCheck">
<input type="text" name="" maxlength="1">
</div>
<div class="refCheck">
<input type="text" name="" maxlength="1">
</div>
</div>
</div>
<div class="contactArea">
<p>Compilare tutti i dati per la prenotazione.</p>
<input type="submit" name="submit" id="submit" value="send">
</div>
</div>
</form>
</div>
The BUTTON that create problem is the one with class reloadButton.
The INPUT is the one with id submit.
I think css aren't necessary.
Regarding the JS part:
let formEls = formPopup.querySelectorAll('.common, .message, .note');
let charCode = [];
const refreshButton = document.querySelectorAll('.reloadButton')[0];
const passInput = document.getElementById('password');
window.onload = function () {
document.querySelector('#reserveBtn').addEventListener('click', function () {
formPopup.classList.add('active');
});
getCode();
formPopup.querySelector('.closeButton').addEventListener('click', function () {
cleanForm();
formPopup.classList.remove('active');
});
formPopup.addEventListener('click', function (ev) {
if (ev.target.id == 'contactform-bg') {
cleanForm();
formPopup.classList.remove('active');
}
});
refreshButton.addEventListener('click', function (ev) {
charCode = [];
getCode();
});
passInput.addEventListener('keyup', function () {
passVal = passInput.value;
checkPass(passVal);
});
};
let cleanForm = function () {
formEls.forEach((item, i) => {
item.classList.remove('typing');
});
// console.log(window['contactform-bg'].innerHTML);
// console.log(document.getElementById('contactform').innerHTML);
// console.log(document.contactform.innerHTML);
document.contactform.name.value = '';
document.contactform.familyName.value = '';
document.contactform.email.value = '';
document.contactform.message.value = '';
passInput.value = '';
};
function getCode() {
let sChars = 'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,1,2,3,4,5,6,7,8,9,!,#,#,$,%,^,&,*,(,)';
let arrayChars = sChars.split(',');
for (var i = 0; i <= 3; i++) {
// trova un indice casuale tra 0 e la lunghezza dell'array
RefIndex = Math.floor(Math.random() * arrayChars.length);
// assegna il carattere estratto dall'array (strana indicazione del font come giapponese(??)
let char = arrayChars[RefIndex];
charCode[i] = char.toLowerCase;
createImgCaptcha(char, i);
}
}
I avoid to add the createImgCaptcha function because it just create CANVAS and doesn't have any impact on the matter.
Is there anyone able to explain to me why the FORM closes? I tried following the steps in JS but found no errors.
Thanks in advance.
Ok, I found the problems and fixed them.
There were little mistakes one different from another. So, I list them:
The "FORM close object": there was a missing '#' characer in the ref attribute, so I changed the HTML from to , adding also the type attribute for greater completeness.
The "class reloadButton": I finally read that a <button>Click to do something</button> is a default submit button. I didn't know... so, I just added the right type attribute to solve, in this way: <button class="reloadButton" type="button">.
The "submit button": in this case, I changed the prevent JS command: function stopEvent(event) { event.preventDefault();}.
Now, everything works correctly. Sorry if I bored you with these silly things; either way, it's always best to learn from mistakes.
Good Day,
I have created a simple form with three boxes to capture text data. I also have a button that duplicates the form to facilitate multiple entries. I want to be able to take that data and place into 3 arrays, one for each text box.
The code is below:
$(document).ready(function()
{
$("#add").click(function()
{
addThis = "<div class='row mb-3'><div class='col-12'><input type='text' name='fname[]' id='fname' class='form-control' placeholder='First Name'></div></div><div class='row mb-3'><div class='col-12'><input type='text' name='mname[]' id='mname' class='form-control' placeholder='Middle Name'></div></div><div class='row mb-3'><div class='col-12'><input type='text' name='lname[]' id='lname' class='form-control' placeholder='Last Name'></div></div>";
$("#form1").append(addThis);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card" id="form2">
<div class="card-body">
<form action="" id="form1" class="card-body">
<div class="row mb-3">
<div class="col-12">
<input type="text" name="fname[]" id="fname" class="form-control" placeholder="First Name">
</div>
</div>
<div class="row mb-3">
<div class="col-12">
<input type="text" name="mname[]" id="mname" class="form-control" placeholder="Middle Name">
</div>
</div>
<div class="row mb-3">
<div class="col-12">
<input type="text" name="lname[]" id="lname" class="form-control" placeholder="Last Name">
</div>
</div>
</form>
<form action="">
<div class="d-grid gap-2">
<div class="btn-group" role="group">
<button type="button" class="btn btn-primary" id="add">Add Another</button>
<button type="button" name="test" class="btn btn-success">TEST</button>
</div>
</div>
</form>
</div>
I want to eventually submit the data into the table, looping through the arrays for each instance of the form.
Could some one point me in the right direction please?
Heres a possible solution using fieldsets to group your name inputs.
See comments in jQuery JS so you know whats happening...
// our form as const object
const form = $('#form');
// on form submit pass event
$(form).on('submit', function(e) {
// stop event default behaviour
e.preventDefault();
// set entry as serialized array
let entry_arr_obj = $(this).serializeArray();
// set empty object for formatted entry data
let formatted_entry_obj = {};
// for each entry array obj values as key => object
$.each(entry_arr_obj, function(k, obj) {
// split object field name by underscore to create name_fieldset array containing fieldset id and name key
let name_fieldset = obj.name.split('_');
// set the set id from name_fieldset array
let fieldset = parseInt(name_fieldset[1]);
// set name key from name_fieldset array
let name = name_fieldset[0];
// if formatted_entry_obj does not have own property matching current fieldset id
if(!formatted_entry_obj.hasOwnProperty(fieldset)) {
// add fieldset id and empty object to formatted_entry_obj
formatted_entry_obj[fieldset] = {};
}
// add field name and field value to formatted_entry_obj current fieldset object
formatted_entry_obj[fieldset][name] = obj.value;
});
// log our entry object
console.log(formatted_entry_obj);
});
// on form add field set
$(form).on('click', '.add', function(e) {
// get all our fieldsets
let fieldsets = $('fieldset',form);
// last fieldset obj and id
let last_fieldset = fieldsets[fieldsets.length-1];
let last_fieldset_id = parseInt($(last_fieldset).data('set'));
// create new fieldset id
let new_fieldset_id = last_fieldset_id + 1;
// clone last fieldset and filter attributes
$(last_fieldset).clone().filter(function() {
// update data set attribute with new fieldset id
$(this).attr(
'data-set',
new_fieldset_id
// now filter children elements (cols)
).children().filter(function() {
// now filter children elements (inputs)
$(this).children().filter(function() {
// get child element name attr
let name_attr = $(this).attr('name');
// if we have name attr
if(name_attr) {
// explode the name attr value via underscore
let name_fieldset = name_attr.split('_');
// return updated name attribute with new fieldset name and empty value
return $(this).attr(
'name',
name_fieldset[0] + '_' + new_fieldset_id
).val(null);
}
// else return child element
return $(this);
});
// return child element
return $(this);
});
// return all of cloned elem
return $(this);
// then insert after last field set
}).insertAfter(last_fieldset);
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.2/dist/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container py-3">
<form id="form">
<fieldset data-set="1" class="form-row mb-3">
<div class="col-sm-4">
<input type="text" name="fname_1" placeholder="First Name" class="form-control form-control-sm" />
</div>
<div class="col-sm-4">
<input type="text" name="mname_1" placeholder="Middle Name" class="form-control form-control-sm" />
</div>
<div class="col-sm-4">
<input type="text" name="lname_1" placeholder="Last Name" class="form-control form-control-sm" />
</div>
</fieldset>
<button type="button" class="add btn btn-sm btn-primary btn-block">Add Fieldset</button>
<button type="submit" class="btn btn-sm btn-success btn-block">Submit</button>
</form>
</div>
I'm trying to do a live database search using ajax with a form input field.
The whole thing runs so far that i can select a text from the proposed list.
The corresponding event "livesearchSelect" is also addressed, the value of the input field is set. Unfortunately the set value is missing in the form.
I have no clue what is going on, someone can throw some hints at me pls ?
screenshot
html:
<form name="demoform" id="demoform" action="" method="post" >
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-4">
<input type="text" name="name" id="name" value="a value" class="form-control" >
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-4">
<input type="text" name="email" id="email" value="" class="form-control" >
</div>
</div>
<div class="form-group row">
<label for="search" class="col-sm-2 col-form-label">Live Search</label>
<div class="col-sm-4">
<input type="search" name="search" id="search" value="" class="form-control" oninput="livesearchResults(this, '/livesearch/Album');">
<ul class="list-group" id="search-results" style="display:none">
<li class="list-group-item">?</li>
</ul>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label"></label>
<div class="col-sm-4">
<input type="submit" name="submit" value="Submit" id="submit" class="btn btn-primary" />
</div>
</div>
</form>
javascript:
function livesearchResults(src, dest){
var results = document.getElementById(src.id + '-results');
var searchVal = src.value;
if(searchVal.length < 1){
results.style.display='none';
return;
}
var xhr = new XMLHttpRequest();
var url = dest + '/' + searchVal;
// open function
xhr.open('GET', url, true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var text = xhr.responseText;
results.style.display='inline';
results.innerHTML = text;
console.log('response from searchresults.php : ' + xhr.responseText);
}
}
xhr.send();
}
function livesearchSelect(src) {
var input_element = document.getElementById(src.parentElement.id.split("-")[0]);
input_element.defaultValue = src.text;
input_element.value = src.text;
}
php controller:
<?php
namespace controller;
use database\DBTable;
class livesearch extends BaseController {
public function index() {
echo "nothing here";
}
public function Album($input) {
$table = new DBTable('Album');
$results = $table->where('Title',$input.'%', 'like')->findColumnAll('Title', '', 6);
foreach ($results as $key => $value)
echo ''.$value.'';
}
}
Clicking an anchor element with an href attribute, even when blank, will load the linked page, which is what you see happening here.
One solution would be to prevent the default action for the link (by e.g. returning false in the handler or calling Event.preventDefault), but a better design would be to replace the <a> elements (which aren't actually links) with something more semantically appropriate. Given that the consumer expects a sequence of <li>, the simplest solution is to replace the <a> in the PHP controller with <li>. The result would still have a higher degree of coupling than is desirable; the HTML classes and click handler couple the results tightly to the specific search form, rather than representing the resource as its own thing.
Not that text is not a DOM-standard property of HTML elements; you should be using textContent or innerText instead.
I want to make validation for my input text form, that user cannot go further unless all input forms will be completed. i want to make it through every input that even if first is completed, user needs to complete another 2 etc. but at this moment i am only able to make it through the first one and have no idea how to iterate it through every input text.
My html:
<div class="write-to-us">
<div class="col-md-12 field">
<p>Write to us</p>
</div>
<div class="col-md-12 field">
<div class="my-form">
<label>Name</label>
<input type="text" name="subject" class="my-text-input">
<div class="label-error">Write your Name</div>
</div>
</div>
<div class="col-md-12 field">
<div class="my-form">
<label>Surname</label>
<input type="text" name="subject" class="my-text-input">
<div class="label-error">Write your surname</div>
</div>
</div>
<div class="col-md-12 field">
<div class="my-form">
<label">Question</label>
<textarea type="text" name="subject" class="my-text-input"></textarea>
</div>
</div>
<div>
<button class="my-button">Check it</button>
</div>
</div>
And my js code for iteration:
myFunction: function() {
var $formField = $('.write-to-us');
if (!$formField.exists()) {
return;
}
initValidation();
function initValidation() {
var errorMsg = $formField.find('.label-error');
var button = $formField.find('.my-button');
var input = $formField.find('input');
var inputContainer = $formField.find('.my-form')
button.click(function(event) {
if(!input.val().trim()) {
errorMsg.css('visibility', 'visible');
inputContainer.addClass('error');
event.preventDefault();
}
});
},
I guess that problem is with .find and should be some jQuery .each but i have no idea how to change it.
I would try doing something like this rather than find.
function initValidation() {
$('.my-button').click(function(){
$("input").each(function() {
var element = $(this);
if (element.val() == "") {
element.closest('.label-error').css('visibility', 'visible');
element.closest('.my-form').addClass('error');
}
});
});
}
UPDATE:
Using the code that colecmc provide(Thank you!!) I updated the codepen. I like how the date.now is added, but I would like to just do a an incremental increase. Im not sure how to apply that to this function I tried zer00ne's index incremental but am doing something wrong.
let cloneList = [],
index = 0; // index must be declared apart from function or else you will set it to the initial value every time the function is called.
document.getElementById('launch').onclick = function(event) {
event.preventDefault();
var addOnDiv = document.getElementById('addon');
var container = document.getElementById('add-components')
var clonedNode = addOnDiv.cloneNode(true);
var component = clonedNode.querySelector('input');
index++;
clonedNode.id = index+1;
cloneList.push(clonedNode.id);
component.id = `componentID_${clonedNode.id}`;
component.name = `componentName_${clonedNode.id}`;
container.appendChild(clonedNode);
}
Im having an issue with my form. Initially I had two forms on the page. However on submit only the info from the first form was written. I tried combining the forms. Now if i fill out the campaign and component inputs and submit it writes to the correct tables(good!). However the component section is supposed to be replicated. A campaign can have as many components as the user wants. I am using cloneNode and before I combined the table it added more component sections. Now that they are combined the function no longer works. Im confused if this is even the right approach for what Im doing. I included a copdpen that shows a stripped down version of what Im trying to do.
Basically I want to be able to press add component, add as many new components as I'd like fill them out and have then all written as records to the db. I need a way to differentiate all the clones (new ids or names?)
codepen: https://codepen.io/anon_guy/pen/VMZWWW?editors=1010
HTML:
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" id="form-event" class="form-horizontal">
<div class="col-sm-4">
<label>name</label>
<input type="text" name="name" value="name" placeholder="name" id="name" class="form-control" />
</div>
<div class="col-sm-4">
<label>address</label>
<input type="text" name="address" value="address" placeholder="address" id="address" class="form-control" />
</div>
<div class="col-sm-4">
<label>phone</label>
<input type="text" name="phone" value="phone" placeholder="phone" id="phone" class="form-control" />
<div class="text-danger"></div>
</div>
</div>
<div class="row">
<div class="add_component">
<button id='launch'>Add Component</button>
</div>
</div>
</div>
<div class="wrapper" id="add-components">
<div class="panel panel-default " id="addon">
<div class="panel-heading">
</div>
<div class="panel-body">
<div class="col-sm-6">
<label>component</label>
<input type="text" name="component" value="component" placeholder="component" id="component" class="form-control" />
</div>
</form>
</div>
</div>
</div>
JS:
document.getElementById('launch').onclick = function() {
var addOnDiv = document.getElementById('addon');
var container = document.getElementById('add-components')
var clonedNode = addOnDiv.cloneNode(true);
container.appendChild(clonedNode );
}
You will want to try something like this before appending to the container clonedNode.id = Date.now();
That will provide a way to differentiate all the clones by giving a unique id. You can take it a step further like this:
let cloneList = [];
document.getElementById('launch').onclick = function(event) {
event.preventDefault();
var addOnDiv = document.getElementById('addon');
var container = document.getElementById('add-components')
var clonedNode = addOnDiv.cloneNode(true);
var component = clonedNode.querySelector('input');
clonedNode.id = Date.now();
cloneList.push(clonedNode.id);
component.id = `componentID_${clonedNode.id}`;
component.name = `componentName_${clonedNode.id}`;
container.appendChild(clonedNode);
}
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" id="form-event" class="form-horizontal">
<div class="col-sm-4">
<label>name</label>
<input type="text" name="name" value="name" placeholder="name" id="name" class="form-control" />
</div>
<div class="col-sm-4">
<label>address</label>
<input type="text" name="address" value="address" placeholder="address" id="address" class="form-control" />
</div>
<div class="col-sm-4">
<label>phone</label>
<input type="text" name="phone" value="phone" placeholder="phone" id="phone" class="form-control" />
<div class="text-danger"></div>
</div>
</div>
<div class="row">
<div class="add_component">
<button id='launch'>Add Component</button>
</div>
</div>
</div>
<div class="wrapper" id="add-components">
<div class="panel panel-default " id="addon">
<div class="panel-heading">
</div>
<div class="panel-body">
<div class="col-sm-6">
<label>component</label>
<input type="text" name="component" value="component" placeholder="component" id="component" class="form-control" />
</div>
</form>
</div>
</div>
</div>
This is the closest I came to what I believe is your way of thinking by looking at your code. (I also removed some unnecessary steps in your code to make it a little bit cleaner). This is for if you must have different names and ID:s on your inputs. However, if you can manage to have the same for both (i.e. component_0, other_0 etc.), you can remove the "names" array and the "names" forEach.
When you want to add an input to your addon-div, just add the ID (and name if you decide to keep it), without the "_0", to the array/s as in the example.
Change the name to "otherName_0" and ID to "otherID_0" in your html and this should work.
var i = 1;
document.getElementById('launch').onclick = function(event) {
event.preventDefault();
var addOnDiv = document.getElementById('addon');
var container = document.getElementById('add-components')
var clonedNode = addOnDiv.cloneNode(true);
var ids = ['componentID', 'otherID'];
var names = ['componentName', 'otherName'];
ids.forEach(function(id) {
var currentInput = clonedNode.querySelector(`#${id}_0`);
currentInput.id = `${id}_${i}`;
});
names.forEach(function(name) {
var currentInput = clonedNode.querySelector(`input[name=${name}_0]`);
currentInput.name = `${name}_${i}`;
});
container.appendChild(clonedNode);
i++;
}