I just started learning coding. and i was trying to apply the OOP pradigm to an example.
I am trying to create an object (the character here) and assign its properties as the values input within the html file.
the error that keeps appearing is 'javascript.js:14 Uncaught TypeError: Cannot read properties of null (reading 'value') .
<body>
<label for="namebox">Character Name</label>
<input type="text" name="" id="namebox">
<label for="agebox">Age</label>
<input type="text" name="" id="agebox">
<label for="humanclass">Human</label>
<label for="majinclass">Majin</label>
<input type="radio" name="class1" id="humanclass">
<input type="radio" name="class1" id="majinclass">
<input type="button" value="Create Character" id="creationbtn" onclick='char1.identify()'>
<input type="reset" value="Cancel">
</body>
class Charcreation {
constructor(name, age, charclass) {
this.name = name;
this.age = age;
this.class = charclass;
}
identify() {
console.log('my name is ' + this.name + ' and i am a ' + this.age + ' years old ' + this.class)
}
}
charname = document.getElementById("namebox").value;
charage = document.getElementById('agebox').value;
charselection = document.getElementByName('class1').value;
charclass =
function getClass() {
for (i == 0; i < charselection.length; i++) {
if (charselection[i].checked)
return charselection[i];
}
}
char1 = new Charcreation(charname, charage, charclass())
char1.identify();
Thanks in advance
There are a few errors in your code as #Chris G points out plus some others. Here's an update to your code with corrections to get a successful output for your char1.identify(); method.
I've added some CSS styling that's not necessary to the output.
When the user clicks on the #creationbtn button, code execution needs to retrieve values of the form controls each time. Your original code is retrieving values of the input controls when the page is loaded and not each time the button is clicked.
class Charcreation {
constructor(name, age, charclass) {
this.name = name;
this.age = age;
this.class = charclass;
}
identify() {
var identityText = 'my name is ' + this.name + ' and i am a ' + this.age + ' years old ' + this.class;
//console.log(identityText);
document.querySelector("#identity").textContent = identityText;
}
}
function createIdentity() {
var charname = document.getElementById("namebox").value;
var charage = document.getElementById('agebox').value;
var charselection = document.getElementsByName('class1');
var charclass =
function getClass() {
for (i = 0; i < charselection.length; i++) {
if (charselection[i].checked) {
var labelElem = document.querySelector("label[for=" + charselection[i].id + "]");
if (labelElem) {
return labelElem.textContent;
}
}
}
}
var char1 = new Charcreation(charname, charage, charclass());
char1.identify();
}
#character-form {
display: grid;
width: 15rem;
}
.radio-control {
display: grid;
grid-auto-flow: column;
padding: .5rem 0;
width: fit-content;
}
.radio-control input {
margin: 0 .5rem;
}
<div id="character-form">
<label for="namebox">Character Name</label>
<input type="text" name="" id="namebox">
<label for="agebox">Age</label>
<input type="text" name="" id="agebox">
<span class="radio-control">
<label for="humanclass">Human</label>
<input type="radio" name="class1" id="humanclass">
</span>
<span class="radio-control">
<label for="majinclass">Majin</label>
<input type="radio" name="class1" id="majinclass">
</span>
<input type="button" value="Create Character" id="creationbtn" onclick='createIdentity()'>
<input type="reset" value="Cancel">
<span id="identity"></span>
</div>
the error that keeps appearing is 'javascript.js:14 Uncaught TypeError: Cannot read properties of null (reading 'value') .
Have you made sure that the script is firing after the DOM gets rendered?
It's possible that it is running before the actual HTML has been rendered and that is why .getElementById("namebox") is returning null.
There are probably other ways to ensure this, but the easiest I know of is just put the script inside of the footer instead of the header.
Related
My goal is that only 15 quantities of input elements can be accepted, once the user enters 16 it should say that only 15 input elements is allowed. However I don't know how will I do this. I tried putting condition inside for but it is not not working. I am a little bit confused on this
Here is my HTML code
<div class="form-group">
<label> Quantity: </label>
<input class="form-control" name="quantity" type="number" id="get_Elem"
required>
<br>
<input type="button" id="sb_add_ctrl" name="is_Sub" class="btn btn-
primary" value="Add Control Number">
</div>
<div class="form-group" name="parent" id="parent"></div>
Here is my JS code
$(document).on('click', '#sb_add_ctrl', function() {
var element = $('#get_Elem').val();
var input;
var parent = $(document.getElementById("parent"));
var value = $('#sel_control_num').val();
functionPopulate(parent);
if (isNaN(element)) {
return;
}
for (var i = 0; i < element; i++) {
if(should I do it here??){
}
value = value.replace(/(\d+)$/, function(match, element) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});
document.getElementById("parent").style.padding = "5px 0px 0px 0px";
document.getElementById("parent").innerHTML += '<br><input type="text"
value="' + value +
'" class="form-control" name="get_Input_show[]" required>'
}
});
You can check if the element value is < 16 if yes then only add html else show error message.
Demo Code :
$(document).on('click', '#sb_add_ctrl', function() {
var element = $('#get_Elem').val();
var input;
//var value = $('#sel_control_num').val();
var value = 12;
//functionPopulate(parent);
if (isNaN(element)) {
return;
}
//check if elemnt value if < 16
if (element < 16) {
$("#parent").empty() //empty div
for (var i = 0; i < element; i++) {
/* value = value.replace(/(\d+)$/, function(match, element) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});*/
document.getElementById("parent").style.padding = "5px 0px 0px 0px";
document.getElementById("parent").innerHTML += '<br><input type="text" value = "' + value + '" class="form-control" name="get_Input_show[]" required>';
}
} else {
alert("only 15") //show error
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label> Quantity: </label>
<input class="form-control" name="quantity" type="number" id="get_Elem" required>
<br>
<input type="button" id="sb_add_ctrl" name="is_Sub" class="btn btn-
primary" value="Add Control Number">
</div>
<div class="form-group" name="parent" id="parent"></div>
There are two ways in which you can restrict it
You can use maxLength property of an input tag, which will restrict the user to input the 16th character.
You can keep checking the value in the input field and show error if the length is more than 15 character. To do this you can use onkeypress event on input, like
HTML
<input type="text" id="test" onkeypress="test()" />
JS:
<script>
function test() {
alert('Hi')
}
</script>
Here is my Javascript code:
$('#sb_add_ctrl').click(function() {
var value = $('#sel_control_num').val();
for (var i = 1; i <= 5; i++) {
value = value.replace(/(\d+)$/, function(match, n) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});
$('#parent')[0].innerHTML += '<br>' + value;
}
})
Here is my HTML code:
<div><label> Control Number </label>
<input name="get_control_num" style="text-transform:uppercase"
class="form-control" id="sel_control_num" readonly>
</div>
<div class="form-group">
<label> Quantity </label>
<input class="form-control" name="quantity" type="number"
/>
<br>
<button type="button" id="sb_add_ctrl" class="btn btn-primary"> Add
Control Number </button>
</div>
<div class="form-group" id="parent"></div>
What I want to do is get the existing class of the input and show the data that is in innerHTML into an input element .I can't think of a proper solution cause I am still a beginner in javascript/jquery, I tried the other methods in jquery but still it doesn't work thanks for the help
This is my first post and I have searched for days and can not find a solution for this problem.
I have a custom menu in sheets that pops up a .showModalDialog html. A user fills that out with information and clicks submit. This runs a function in the back end that creates folders/files and adds the user data to various sheets etc.
All this is working I have a Ui.alert that I am using to check the data entered is correct and for some reason the function is being trigger twice and the UI.alert is popping up again as a result. I have a fail safe that checks if one of the fields exists so it doesn't write again but the pop up is a really bad user experience.
Any help would be much appreciated.
Function to create custom menu:
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('TOA - Menu')
.addItem('Add New Account', 'addAccount')
.addItem('Update Brand', 'updateBrand')
.addItem('Go Live', 'goLive')
.addToUi();
}
Function to bring up form:
function addAccount() {
const html = HtmlService.createHtmlOutputFromFile('newAccount')
.setTitle('Add New Account')
.setWidth(1000)
.setHeight(800);;
SpreadsheetApp.getUi()
.showModalDialog(html, 'Add New Account');
}
Code for the form:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
#itemDisplay {
display: none;
}
#modDisplay {
display: none;
}
#priceDisplay {
display: none;
}
#businessTypeDisplay {
display: none;
}
</style>
</head>
<body>
<h1>
Add New Account
</h1>
<form id="myForm" onsubmit="handleNewAccountFormSubmit(this);">
<div>
<label for="newBrand">Brand:</label>
<input name="newBrand" type="text" placeholder="Brand Name" required>
</div>
<div>
<p>Location</p>
<label for="country">Country:</label>
<select name="country" id="" onchange="" required>
<option value="" disabled selected>Select Country</option>
<option value="US">US</option>
</select>
<label for="state">State/Province:</label>
<input name="state" type="text" placeholder="State or province" required>
<label for="city">City:</label>
<input name="city" type="text" placeholder="City" required>
<div>
<label for="businessType">Business Type:</label>
<select name="businessType" id="businessTypeSelect" onchange="businessOtherDisplay(this.value);" required>
<option value="" disabled selected>Select Request Reason</option>
<option value="americanDiner">American Diner</option>
<option value="pizzaParlor">Pizza Parlor</option>
<option value="coffeeShop">Coffee Shop</option>
<option value="candyShop">Candy Store</option>
<option value="iceCreamParlor">Ice Cream Parlor</option>
<option value="burgerShop">Burger Shop</option>
<option value="otherNon_AmericanDiner">Other non-American Diner (Foreign servings)</option>
<option value="other">Other (not listed above)</option>
</select>
</div>
<div id="businessTypeDisplay">
<label for="businessTypeOther">Business Type Other:</label>
<input name="businessTypeOther" type="text" placeholder="Business type if not listed above">
</div>
<div>
<label for="integration">Integration:</label>
<select name="integration" required>
<option value="" disabled selected>Select Request Reason</option>
<option value="square">Square</option>
<option value="clover">Clover</option>
<option value="cloverPilot">Clover Pilot</option>
<option value="stripe">Stripe</option>
<option value="gPay">GPAY</option>
<option value="others" >Others</option>
</select>
</div>
<label for="menuSource">File Attachment/Source:</label>
<input name="menuSource" type="text" placeholder="Path to menu" required url>
<div>
<p>Do you need an item hidden/disabled?</p>
<label for="yes">Yes</label>
<input name="disableItemOption" type="radio" value="yes" onclick="showItem()">
<label for="no">No</label>
<input name="disableItemOption" type="radio" value="no" checked onclick="hideItem()">
</div>
<div id="itemDisplay">
<label for="itemDisable">Which item(s) should be disabled?</label>
<textarea id="disabledItem" name="itemDisable" cols="40" rows="5"></textarea>
</div>
<div>
<p>Do you need a modifier hidden/disabled?</p>
<label for="yes">Yes</label>
<input name="disableModOption" type="radio" value="yes" onclick="showMod()">
<label for="no">No</label>
<input name="disableModOption" type="radio" value="no" checked onclick="hideMod()">
</div>
<div id="modDisplay">
<label for="modDisable">Which modifier(s) should be disbaled?</label>
<textarea id="disabledMod" name="modDisable" cols="40" rows="5"></textarea>
</div>
<div>
<p>Do you need to update a price?</p>
<label for="yes">Yes</label>
<input name="updatePrice" type="radio" value="yes" onclick="showPrice()">
<label for="no">No</label>
<input name="updatePrice" type="radio" value="no" checked onclick="hidePrice()">
</div>
<div id="priceDisplay">
<label for="priceUpdate">Which item/modifier needs a price update?</label>
<textarea id="updatedPrice" name="priceUpdate" cols="40" rows="5" priceUpdate></textarea>
</div>
<div>
<label for="otherUpdates">Any other information needed on the menu?</label>
<input name="otherUpdates" type="text" placeholder="List other instructions here">
</div>
<div>
<label for="specialInstructions">Are there special instructions/notes for this brand?</label>
<input name="specialInstructions" type="text" placeholder="List special instructions here">
</div>
<input id="submitButton" type="submit" value="Submit">
<input type="button" value="Cancel" onclick="google.script.host.close()">
</div>
</form>
<script>
function handleNewAccountFormSubmit(formObject) {
document.getElementById('submitButton').disabled=true;
google.script.run.withSuccessHandler().processNewAccountForm(formObject);
}
function disableSubmit() {
document.getElementById('submitButton').disabled=true;
document.getElementById('submitButton').value='Sending...';
}
function showItem(){
document.getElementById('itemDisplay').style.display ='block';
document.getElementById('disabledItem').required = true;
};
function hideItem(){
document.getElementById('itemDisplay').style.display = 'none';
document.getElementById('disabledItem').required = false;
};
function showMod(){
document.getElementById('modDisplay').style.display ='block';
document.getElementById('disabledMod').required = true;
};
function hideMod(){
document.getElementById('modDisplay').style.display = 'none';
document.getElementById('disabledMod').required = false;
};
function showPrice(){
document.getElementById('priceDisplay').style.display ='block';
document.getElementById('updatedPrice').required = true;
};
function hidePrice(){
document.getElementById('priceDisplay').style.display = 'none';
document.getElementById('updatedPrice').required = false;
};
function businessOtherDisplay(value) {
if(value === "other") {
document.getElementById('businessTypeDisplay').style.display = 'block';
} else {
document.getElementById('businessTypeDisplay').style.display = 'none';
};
};
</script>
</body>
</html>
And the code to handle the logic
function processNewAccountForm(formObject) {
const ui = SpreadsheetApp.getUi();
const ass = SpreadsheetApp.getActiveSpreadsheet();
const ss = ass.getActiveSheet();
const timestamp = Utilities.formatDate(new Date(), "GMT+8", "MM/dd/yyyy HH:mm:ss");
const userEmail = Session.getActiveUser().getEmail();
const brandName = formObject.newBrand;
// Add alert to check data entered is correct
const response = ui.alert('Please confirm the following information is correct:',
'ššæš®š»š± š”š®šŗš²: ' + formObject.newBrand +
'\nšš¼šš»ššæš: ' + formObject.country +
'\nš¦šš®šš²: ' + formObject.state +
'\nšš¶šš: ' + formObject.city +
'\nšššš¶š»š²šš š§šš½š²: ' + formObject.businessType +
'\nšš»šš²š“šæš®šš¶š¼š»: ' + formObject.integration +
'\nšš¶š¹š² š¦š¼ššæš°š²: ' + formObject.menuSource +
'\nšš¼ šš¼š š»š²š²š± š®š» š¶šš²šŗ šµš¶š±š±š²š»/š±š¶šš®šÆš¹š²š±?: ' + formObject.disableItemOption +
'\nšŖšµš¶š°šµ š¶šš²šŗ(š) ššµš¼šš¹š± šÆš² š±š¶šš®šÆš¹š²š±?: ' + formObject.itemDisable +
'\nšš¼ šš¼š š»š²š²š± š® šŗš¼š±š¶š³š¶š²šæ šµš¶š±š±š²š»/š±š¶šš®šÆš¹š²š±?: ' + formObject.disableModOption +
'\nšŖšµš¶š°šµ šŗš¼š±š¶š³š¶š²šæš ššµš¼šš¹š± šÆš² š±š¶šš®šÆš¹š²š±?: ' + formObject.modDisable +
'\nšš¼ šš¼š š»š²š²š± šš¼ šš½š±š®šš² š® š½šæš¶š°š²?: ' + formObject.updatePrice +
'\nšŖšµš¶š°šµ š¶šš²šŗ/šŗš¼š±š¶š³š¶š²šæ š»š²š²š±š š® š½šæš¶š°š² šš½š±š®šš²?: ' + formObject.priceUpdate +
'\nšš»š š¼ššµš²šæ š¶š»š³š¼šæšŗš®šš¶š¼š» š»š²š²š±š²š± š¼š» ššµš² šŗš²š»š?: ' + formObject.otherUpdates +
'\nššæš² ššµš²šæš² šš½š²š°š¶š®š¹ š¶š»šššæšš°šš¶š¼š»š/š»š¼šš²š š³š¼šæ ššµš¶š šÆšæš®š»š±?: ' + formObject.specialInstructions
, ui.ButtonSet.YES_NO);
if(response === ui.Button.YES) {
var lock = LockService.getScriptLock();
lock.waitLock(60000);
try {
const brandColumn = ss.getRange('D:D');
const brandValues = brandColumn.getValues();
let i = 1;
// Check for exisiting brand name
for(i=1; i < brandValues.length; i++) {
if(brandValues[i].toString().toLowerCase().trim() == brandName.toString().toLowerCase().trim() && ss.getRange(i+1,5).getValue() == 'New Brand'){
ui.alert("Brand name already created");
return;
}
};
// Create folder and PDF with build instructions
const parentFolder = DriveApp.getFolderById("RemovedfolderID");// how does this work with Shared drives? Create and move?
// const parentFolder = DriveApp.getFolderById("RemovedfolderID"); < ---- Team drive ID (notworking..) My folder -> RemovedfolderID
const newFolder = parentFolder.createFolder(brandName);
const docFile = newFolder.createFile(brandName+'.pdf',
'ššæš®š»š± š”š®šŗš²: ' + formObject.newBrand +
'\nšš¼šš»ššæš: ' + formObject.country +
'\nš¦šš®šš²: ' + formObject.state +
'\nšš¶šš: ' + formObject.city +
'\nšššš¶š»š²šš š§šš½š²: ' + formObject.businessType +
'\nšš»šš²š“šæš®šš¶š¼š»: ' + formObject.integration +
'\nšš¶š¹š² š¦š¼ššæš°š²: ' + formObject.menuSource +
'\nšš¼ šš¼š š»š²š²š± š®š» š¶šš²šŗ šµš¶š±š±š²š»/š±š¶šš®šÆš¹š²š±?: ' + formObject.disableItemOption +
'\nšŖšµš¶š°šµ š¶šš²šŗ(š) ššµš¼šš¹š± šÆš² š±š¶šš®šÆš¹š²š±?: ' + formObject.itemDisable +
'\nšš¼ šš¼š š»š²š²š± š® šŗš¼š±š¶š³š¶š²šæ šµš¶š±š±š²š»/š±š¶šš®šÆš¹š²š±?: ' + formObject.disableModOption +
'\nšŖšµš¶š°šµ šŗš¼š±š¶š³š¶š²šæš ššµš¼šš¹š± šÆš² š±š¶šš®šÆš¹š²š±?: ' + formObject.modDisable +
'\nšš¼ šš¼š š»š²š²š± šš¼ šš½š±š®šš² š® š½šæš¶š°š²?: ' + formObject.updatePrice +
'\nšŖšµš¶š°šµ š¶šš²šŗ/šŗš¼š±š¶š³š¶š²šæ š»š²š²š±š š® š½šæš¶š°š² šš½š±š®šš²?: ' + formObject.priceUpdate +
'\nšš»š š¼ššµš²šæ š¶š»š³š¼šæšŗš®šš¶š¼š» š»š²š²š±š²š± š¼š» ššµš² šŗš²š»š?: ' + formObject.otherUpdates +
'\nššæš² ššµš²šæš² šš½š²š°š¶š®š¹ š¶š»šššæšš°šš¶š¼š»š/š»š¼šš²š š³š¼šæ ššµš¶š šÆšæš®š»š±?: ' + formObject.specialInstructions,
MimeType.PDF);
const fileURL = docFile.getUrl();
// add header row to spreadsheet
// Create Spreadsheet in Brand folder. Activity log.
const name = brandName + " Activity Log";
const id = newFolder.getId();
const resource = {
title: name,
mimeType: MimeType.GOOGLE_SHEETS,
parents: [{id: id}]
};
const fileJson = Drive.Files.insert(resource);
const fileId = fileJson.id;
const lastRow = ss.getLastRow();
const newEntry = [
lastRow,
timestamp,
timestamp,
formObject.newBrand,
'New Brand',
formObject.businessType,
formObject.integration,
'=HYPERLINK("'+formObject.menuSource+'")',
userEmail,
fileURL,
,
,
,
,
formObject.city,
formObject.state,
formObject.country,
fileId
];
const newSheet = SpreadsheetApp.openById(fileId);
const sheetRange = newSheet.getSheetByName("Sheet1").getRange(1,1,1,18);
const headers = [
['šš»š±š²š
',
'ššæš®š»š± š¼šæš¶š“š¶š»š®š¹ š°šæš²š®šš² š±š®šš²',
'š§š¶šŗš² šš»',
'ššæš®š»š± š”š®šŗš²',
'š„š²š¾šš²šš šæš²š®šš¼š»',
'šššš¶š»š²šš ššš½š²',
'šš»šš²š“šæš®šš¶š¼š»',
'š š²š»š š¦š¼ššæš°š²',
'ššæš²š®šš²š± šÆš:',
'š š²š»š šš»šššæšš°šš¶š¼š»š',
'šššš¶š“š»š²š± šš¼?',
'š§š¶šŗš² š¢šš',
'šš¼šŗš½š¹š²š
š¶šš š„š®šš¶š»š“',
'šš¼ š¹š¶šš² š±š®šš² š®š»š± šš¶šŗš²',
'šš¶šš',
'š¦šš®šš²/š£šæš¼šš¶š»š°š²',
'šš¼šš»ššæš',
'šš°šš¶šš¶šš šš¼š“']
];
sheetRange.setValues(headers);
// Add data to last row in main tracker
ss.appendRow(newEntry);
// Copy data to spreadsheet brand
const activitySheet = newSheet.getSheetByName("Sheet1")
activitySheet.appendRow(newEntry);
// Flush changes before releasing lock
SpreadsheetApp.flush();
} catch(e) {
ui.alert("System is Busy, Please try again in a moment.");
return
} finally {
lock.releaseLock();
return
}
} else {
// action to take if info is incorrect? or No is clicked
};
};
I know that multiple triggers have been a known issue as per posts from Cooper and others here and here but I can't seem to be able to adopt them for my solution.
Thanks in advance for any ideas.
These are the changes I'd make to the dialog:
<input id="btn1" type="button" value="Submit" onClick="handleNewAccountFormSubmit(this.parentNode);" />
<input type="button" value="Cancel" onclick="google.script.host.close()">
</div>
</form>
<script>
function handleNewAccountFormSubmit(formObject) {
document.getElementById('btn1').disabled=true;
google.script.run.processNewAccountForm(formObject);
}
I'm not saying that your way is wrong. That's just the way I would try to do it. But realistically it's a fairly large dialog and your just going to have to dig in and figure it out. If I were doing it and I was having a lot of problems I'd probably start with a simpler version and get it to work and then slowly add more features.
This is actually a fairly difficult time two write code in the middle of a transition between two runtimes. I've just noticed that I've lost my content assist in some areas in ES5 but they now work in ES6 so things can be difficult to deal with.
To do checking on required fields and a custom method of alerting users that required fields are missing, I'm trying to get an array of elements in a form, and have been hunting but not finding a good method.
Is there some variation of
document.getElementById(form).elements;
that would return all the required elements of an array, or a way to test if a given element is required... something akin to either
var my_elements = document.getElementById(form).required_elements;
or
var my_elements = document.getElementById(form).elements;
for (var this_element in my_elements){
if (this_element.attributes["required"] == "false"){
my_elements.splice(this_element, 1);
}
}
Try querySelectorAll with an attribute selector:
document.getElementById(form).querySelectorAll("[required]")
var requiredElements = document.getElementById("form").querySelectorAll("[required]"),
c = document.getElementById("check"),
o = document.getElementById("output");
c.addEventListener("click", function() {
var s = "";
for (var i = 0; i < requiredElements.length; i++) {
var e = requiredElements[i];
s += e.id + ": " + (e.value.length ? "Filled" : "Not Filled") + "<br>";
}
o.innerHTML = s;
});
[required] {
outline: 1px solid red;
}
<form id="form">
<input required type="text" id="text1" />
<input required type="text" id="text2" />
<input type="text" id="text3" />
<input type="text" id="text4" />
<input required type="text" id="text5" />
</form>
<br>
<button id="check">Check</button>
<br>
<div id="output">
Required inputs
</div>
I want to validate the dynamically added fields of the form(present in the templates/appname) in django. I am adding those fields with the help of the javascript (addInput.js - stored at a place mentioned as source in the script tag) which also has the logics for removing those fields as well as validating those fields values. But when I click send_invites button, it directs me again to app/register when I first want that it should go to the validateEmail() function if everything is fine then it should redirect to app/register.
var counter = 1;
var limit = 5;
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " Email Addresses");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<p id = 'remove" + counter + "'>Email Address " + (counter + 1) + " : " + "<input type = 'text' name ='myInputs[]'></p>";
document.getElementById(divName).appendChild(newdiv);
counter++;
alert(counter + "add");
}
}
function removeInput(divName) {
if (counter == 1) {
alert("You have reached the limit of removing Email Addresses");
} else {
counter--;
var olddiv = document.getElementById("remove" + counter);
alert(counter + "remove");
olddiv.parentNode.removeChild(olddiv);
}
}
function validateEmail(divName) {
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-]+.)+([a-zA-Z0-9]{2,4})+$/;
console.log("cmn");
alert("cmn");
for (i = 0; i < counter; i++) {
var email = $("#remove" + i).val();
alert(email);
// return true;
}
return true;
}
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<br>
<h1 class="page-header">
Send Invites
</h1>
<form method="POST" onsubmit="return validateEmail('dynamicInput')" action="/app/register/">
<div id="dynamicInput">
<p id='remove0'>Email Address 1 :
<input type="text" name="myInputs[]">
</p>
</div>
<br>
<br>
<input type="button" value="Add another Email Address" onClick="addInput('dynamicInput');">
<input type="button" value="Remove Email Address Field " onClick="removeInput('dynamicInput');">
<br>
<br>
<input type="submit" value="Send Invites">
<input type='hidden' name='csrfmiddlewaretoken' value='xyz' />
</form>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
<!-- /#page-wrapper -->
</div>
<!-- /#wrapper -->
</div>
<style>
a.active {
background-color: #eee;
}
</style>
But why is this not happening? other two javascript functions addInput and removeInput are working fine. Only validateEmail is not getting called, for which I am even calling alert and console.log but nothing is getting displayed. Please help. I am new to javascript.
Running the code, clicking the button, you get the following error in the console.
Uncaught SyntaxError: Invalid regular expression:
/^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-]+.)+([a-zA-Z0-9]{2,4})+$/:
Unterminated group
Looking at the code you have an extra (
/^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-]+.)+([a-zA-Z0-9]{2,4})+$/;
^
So you are either missing a closing ) or you have the extra (. My guess is you are missing a ) before the +. Look at wherever you found the reg exp and see what it should be.