Jquery event handling when a checkbox is clicked - javascript

edit Updated full code :
I'm working on my first Javascript case i'm stuck here :
I have the following :
$(document).ready(function()
{
$('input, select').on('focus' ,swapPersonClass);
//Blur = Bind an event handler to the “blur” JavaScript event, or trigger that event on an element.
$('input, select').on("change", updateCart);
}
);
// Functions
var swapPersonClass = function()
{
var expression = $(this).attr('id');
switch(expression)
{
case "fullname":
break;
case "email":
$("#arm").removeClass().addClass("pointemail");
break;
case "countpizzas":
$("#arm").removeClass().addClass("pointamount");
break;
default:
$("#arm").removeClass().addClass("pointothers");
}
};
var updateCart = function () {
var change = $(this).attr('id');
console.log(change);
$('input, select').each(function ()
{
switch (change)
{
case "fullname":
$("#displayname").text($('#fullname').val() + ',');
break;
case "countpizzas":
aantalpizzas = $("#countpizzas").val();
if (aantalpizzas > 1) {
$('.plural').show();
} else {
$('.plural').hide();
};
$("#displayamount").text(aantalpizzas);
console.log(aantalpizzas);
break;
case "pizzatype":
PrijsPizza = $("#pizzatype option:selected").data("price");
console.log(PrijsPizza);
break;
case "YesOption":
$("#toppings").show();
break;
case "NoOption":
$("#toppings").hide();
break;
case "toppings":
updateTopping();
break;
};
$("#currenttotal").text(aantalpizzas * PrijsPizza );
});
};
var updateTopping = function ()
{
$(".chk_topping").change(function()
{
var selected_topping = $(this).attr('data-value');
switch(selected_topping)
{
case "salami":
$("#currenttotal").text(aantalpizzas * PrijsPizza );
PrijsTopping += 0.30;
break
}
});
};
var PrijsTopping = 0.30;
var aantalpizzas = 0;
var PrijsPizza = 0;
<!DOCTYPE html>
<html>
<head>
<title>Forms</title>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Lobster">
<link href='http://fonts.googleapis.com/css?family=Droid+Sans:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="assets/css/reset.css"/>
<link rel="stylesheet" href="assets/css/screen.css" type="text/css"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div id="container">
<header>
<h1>Pizza Palace</h1>
</header>
<aside>
<h2><span>Order details</span></h2>
<div id="total">
<p>Your current order total: € <strong id="currenttotal">0</strong></p>
</div>
<p><strong id="displayname"></strong> you are ordering <strong id="displayamount"></strong> pizza<span
class="plural">s</span></p>
<h3>Chosen toppings:</h3>
<div id="toppingmessage">
<p>No toppings selected</p>
<ul>
<li class="hide">Salami</li>
<li class="hide">Olives</li>
<li class="hide">Ansjovis</li>
</ul>
</div>
<h3>Your discount: </h3>
<p id="displaydiscount"></p>
</aside>
<form action="#" method="post">
<figure id="arm"></figure>
<figure id="face"></figure>
<fieldset class="personbody">
<form>
<div>
<label for="fullname">Full Name
<input id="fullname" name="fullnames" type="text" required autofocus>
</label>
</div>
<div>
<label for="email">Email
<input id="email" name="email" type="email" placeholder="Enter Your email" required>
</label>
</div>
<div>
<label for="howmany">How many pizzas would you like?<br><br>
<input id="countpizzas" name="countpizzas" type="number" min="1" max="3" step="1" value="0" required>
</label>
</div>
<div>
<label for="pizzatype">Which type of pizza would you like ? <br>
<select id="pizzatype"name="pizzatype">
<option data-price="4" value="S">Small</option>
<option data-price="5.5" value="M">Medium</option>
<option data-price="7" value="L">Large</option>
</select>
</label>
</div>
<div>
<label for="extratopping">Would you like extra topping? <br>
<input id="YesOption" name="ExtraTopping" type="radio"> Yes
<input id="NoOption" name="ExtraTopping" type="radio"> No
</label>
</div>
<div class="hide" id="toppings">
<label for="toppings">Which toppings would you like?</label>
<input type="checkbox" class="chk_topping" data-value="salami"> Salami
<input type="checkbox" class="chk_topping" data-value="olives"> Olives
<input type="checkbox" class="chk_topping" data-value="ansjovis"> Ansjovis
</div>
<div>
<label for="deliverydate">When do you want the pizza<span class="plural">s</span> to be delivered?
<input id="delivery" name="delivery" type="date" required > </label>
<label for="deliverytime">
<input id="Time" name="Time" type="time" required> </label>
</div>
<label for="discountcode">Do you have a discount code?
<input id="DiscountCode" name="DiscountCode" type="text" pattern="[1-9]{1}-[A-Z]{3}" title="The discount code should be a digit followed by a dash and then 3 uppercase letters" required>
</label>
</div>
</form>
<input type="submit" value="Place your order" name="placeorder"/>
</fieldset>
</form>
<footer><p>Graphics courtesy of © Basecamp </p></footer>
</div>
<script type='text/javascript' src='assets/js/jquery.js'></script>
<script type='text/javascript' src='assets/js/script.js'></script>
</body>
</html>
Why my checkboxes keep telling me it's undefined when selecting them ?
I'm realy not good at javascript so my code will probably be sh*t

Try this
var selected_topping = $(this).data('value');
http://jsfiddle.net/f4Lghy6p/

Found it.
i'm searching for a specefic ID in my select en input fields :
$('input, select').on("change", updateCart);
My checkboxes are located in a DIV with an input fields which don't have an ID.

Related

Trying to add "this" object to an array (Javascript)

I'm trying to make it so when you push a button you add a note to the page. When I push the button, the new note flashes. I'm trying to get it to stay.
When I use a regular bracket object the new note stays. I could just switch to using one, but I wanna know if it's possible to make it work with a "this" object before switching.
The button used to add the note is under the "Note Drop-down" button
var dummyNotes = [];
class NewNote {
constructor(id, title, details, date) {
this.id = id;
this.title = title;
this.details = details;
this.date = date;
this.titleFormat = function() {
return `<span class="titleSpan">
<input type="text" class="noteTitle inputControls" value="${this.title}" maxlength="50">
<label class="editLabel detailScript">0/50</label>
<label class="editLabel errorMessage">Character limit reached!</label>
<span class="noteButtons">
<button class="editTitle">Edit</button>
<button class="deleteNote">Delete</button>
</span>
<span class="noteInfo">
<label class="theDate">${this.date}</label>
<label class="theID">${this.id}</label>
</span>
</span>`;
}
this.detailsFormat = function() {
return `<span class="detailsSpan">
<details><summary>Click for Details</summary>
<textarea class="noteDetails inputControls" maxlength="100">${this.details}</textarea>
<label class="editLabel detailScript">0/100</label>
<label class="editLabel errorMessage">Character limit reached!</label>
<button class="editDetails">Edit</button>
</details>
</span>`;
}
}
}
let newNoteInput = document.getElementById("newNoteInput");
newNoteInput.addEventListener('submit', addANote);
function addANote(){
/*If this fails, just copy paste what's under, insert values */
const pushNote = new NewNote(generateID(), newNoteTitle.value, newNoteDetails.value, dateNote.toLocaleDateString());
dummyNotes.push(pushNote);
addNewNote(pushNote);
newNoteTitle.value = "";
newNoteDetails.value = "";
}
function addNewNote(pushNote) {
const theNewNote = document.createElement("div");
theNewNote.classList.add("newNote");
const theNewNoteForm = document.createElement("form");
theNewNoteForm.classList.add("noteForm");
theNewNote.appendChild(theNewNoteForm);
theNewNoteForm.innerHTML = pushNote.titleFormat() + pushNote.detailsFormat();
noteList.appendChild(theNewNote); /*APPEND CHILD to get every item on the list*/
}
function init() {
dummyNotes.forEach(addNewNote);
noteList.innerHTML = "";
}
init();
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="Notes.css">
<meta name="viewport" content="width=device-width" initial-scale="1.0">
<title>Notes</title>
</head>
<body>
<div id="container">
<div id="noteContainer">
<details id="buttonContainer">
<summary id="toggleContainer">Note Drop-Down</summary>
<span id="newNoteToggle">
<form id="newNoteInput">
<span>
<input type="text" id="newNoteTitle" class="inputControls" placeholder="Title" maxlength="50">
<label class="newLabel detailScript">0/50</label>
<label class="newLabel errorMessage">Character limit reached!</label>
</span>
<span>
<input type="textarea" id="newNoteDetails" class="inputControls" placeholder="Details" maxlength="100">
<label class="newLabel detailScript">0/100</label>
<label class="newLabel errorMessage">Character limit reached!</label>
</span>
<button id="addButton">Add New Note</button>
</form>
</span>
</details>
<div id="noteList">
<div class="newNote">
<form class="noteForm">
<span class="titleSpan">
<input type="text" class="noteTitle" value="Note Title">
<button class="editTitle">Edit</button>
<button class="deleteNote">Delete</button>
<label class="theDate">The Date</label>
<label class="theDate">ID</label>
</span>
<span class="detailsSpan">
<details><summary>Click for Details</summary>
<textarea class="noteDetails"></textarea>
<button class="editDetails">Edit</button>
<span id="wordCount"></span>
</details>
</span>
</form>
</div>
</div>
</div>
<div id="searchContainer">
<details id="searchForm">
<summary><h4>Search Notes</h4></summary>
<form>
<input id="searchDate" type="date" placeholder="Date">
<input id="searchTitle" type="text" placeholder="Title">
<button id ="searchButton">Search</button>
</form>
</details>
</div>
</div>
<script src="Notes.js"></script>
</body>
</html>
Yep, as I suspected, your form was definitely posting without preventing default.
Please review the code, I've commented everywhere I made changes.
//was getting errors for these variables not being defined.
var dummyNotes = [],
dateNote = new Date();
class NewNote {
constructor(id, title, details, date) {
this.id = id;
this.title = title;
this.details = details;
this.date = date;
this.titleFormat = function() {
return `<span class="titleSpan">
<input type="text" class="noteTitle inputControls" value="${this.title}" maxlength="50">
<label class="editLabel detailScript">0/50</label>
<label class="editLabel errorMessage">Character limit reached!</label>
<span class="noteButtons">
<button class="editTitle">Edit</button>
<button class="deleteNote">Delete</button>
</span>
<span class="noteInfo">
<label class="theDate">${this.date}</label>
<label class="theID">${this.id}</label>
</span>
</span>`;
}
this.detailsFormat = function() {
return `<span class="detailsSpan">
<details><summary>Click for Details</summary>
<textarea class="noteDetails inputControls" maxlength="100">${this.details}</textarea>
<label class="editLabel detailScript">0/100</label>
<label class="editLabel errorMessage">Character limit reached!</label>
<button class="editDetails">Edit</button>
</details>
</span>`;
}
}
}
let newNoteInput = document.getElementById("newNoteInput");
//changed this function to run an anonymous function, prevent default and then call addANote():
newNoteInput.addEventListener('submit', function(e) {
e.preventDefault();
addANote();
});
function addANote(){
/*If this fails, just copy paste what's under, insert values */
const pushNote = new NewNote(generateID(), newNoteTitle.value, newNoteDetails.value, dateNote.toLocaleDateString());
dummyNotes.push(pushNote);
addNewNote(pushNote);
newNoteTitle.value = "";
newNoteDetails.value = "";
return false;
}
function addNewNote(pushNote) {
const theNewNote = document.createElement("div");
theNewNote.classList.add("newNote");
const theNewNoteForm = document.createElement("form");
theNewNoteForm.classList.add("noteForm");
theNewNote.appendChild(theNewNoteForm);
theNewNoteForm.innerHTML = pushNote.titleFormat() + pushNote.detailsFormat();
noteList.appendChild(theNewNote); /*APPEND CHILD to get every item on the list*/
}
function init() {
dummyNotes.forEach(addNewNote);
noteList.innerHTML = "";
}
//was getting error due to this function not existing, so I threw this in here:
function generateID() {
return parseInt(Math.random() * 10000);
}
init();
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="Notes.css">
<meta name="viewport" content="width=device-width" initial-scale="1.0">
<title>Notes</title>
</head>
<body>
<div id="container">
<div id="noteContainer">
<details id="buttonContainer">
<summary id="toggleContainer">Note Drop-Down</summary>
<span id="newNoteToggle">
<form id="newNoteInput">
<span>
<input type="text" id="newNoteTitle" class="inputControls" placeholder="Title" maxlength="50">
<label class="newLabel detailScript">0/50</label>
<label class="newLabel errorMessage">Character limit reached!</label>
</span>
<span>
<input type="textarea" id="newNoteDetails" class="inputControls" placeholder="Details" maxlength="100">
<label class="newLabel detailScript">0/100</label>
<label class="newLabel errorMessage">Character limit reached!</label>
</span>
<button id="addButton">Add New Note</button>
</form>
</span>
</details>
<div id="noteList">
<div class="newNote">
<form class="noteForm">
<span class="titleSpan">
<input type="text" class="noteTitle" value="Note Title">
<button class="editTitle">Edit</button>
<button class="deleteNote">Delete</button>
<label class="theDate">The Date</label>
<label class="theDate">ID</label>
</span>
<span class="detailsSpan">
<details><summary>Click for Details</summary>
<textarea class="noteDetails"></textarea>
<button class="editDetails">Edit</button>
<span id="wordCount"></span>
</details>
</span>
</form>
</div>
</div>
</div>
<div id="searchContainer">
<details id="searchForm">
<summary><h4>Search Notes</h4></summary>
<form>
<input id="searchDate" type="date" placeholder="Date">
<input id="searchTitle" type="text" placeholder="Title">
<button id ="searchButton">Search</button>
</form>
</details>
</div>
</div>
<script src="Notes.js"></script>
</body>
</html>
All I had to do to make the remove button work was write init like this:
function init() {
noteList.innerHTML = "";
dummyNotes.forEach(addNewNote);
}
noteList.innerHTML just needed to be on top!

why do i get two different setCustomValidity messages?

i am very new to web dev and javascript. i am working on a project from a book and building a simple web app that takes orders for coffee. i am using the constraint validation api and i am stuck on that. there is a function that tests the input into the email field against a regular expression and it returns true if the email address has 'authorized email address'. as long as it doesn't match i try to submit the form and i get the expected message '**** is not an authorized email address'. but when it it does match the pattern and the isCompanyEmail function returns true i still get a validity message, just a different one saying 'please match the requested format'. does anyone have any idea what could be causing this? i am including the validation code and form code.
validation code:
(function(window){
'use strict';
var App = window.App || {};
var Validation = {
isCompanyEmail: function(email){
return /.+#bignerdranch\.com$/.test(email);
}
};
App.Validation = Validation;
window.App = App;
})(window);
formhandler code:
(function(window){
'use strict';
var App = window.App || {};
var $ = window.jQuery;
function FormHandler(selector){
if (!selector) {
throw new Error('No selector provided!');
}
this.$formElement = $(selector);
if (this.$formElement.length === 0) {
throw new Error('Could not find element with selector ' + selector);
}
};//end constructor
FormHandler.prototype.addSubmitHandler = function(fn){
console.log('Setting submit handler for form');
this.$formElement.on('submit', function(event){
event.preventDefault();
var data = {};
$(this).serializeArray().forEach(function(item){
data[item.name] = item.value;
console.log(item.name + ' is ' + item.value);
});
console.log(data);
fn(data);
this.reset();
this.elements[0].focus();
});
};
FormHandler.prototype.addInputHandler = function(fn){
console.log('Setting input handler for form');
this.$formElement.on('input', '[name="emailAddress"]', function(event){
var emailAddress = event.target.value;
console.log(fn(emailAddress));
var message = '';
if(fn(emailAddress)){
event.target.setCustomValidity(message);
}else{
message = emailAddress + ' is not an authorized email address!';
event.target.setCustomValidity(message);
}
});
};
App.FormHandler = FormHandler;
window.App = App;
})(window);
and the html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>coffeerun</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body class="container">
<header>
<h1>CoffeeRun</h1>
</header>
<section>
<div class="panel panel-default">
<div class="panel-body">
<form data-coffee-order="form">
<div class="form-group">
<label for="coffeeOrder">Coffee Order</label>
<input class="form-control" name="coffee" value="" id="coffeeOrder">
</div>
<div class="form-group">
<label for="emailInput">Email</label>
<input class="form-control" type="email" name="emailAddress" value="" id="emailInput" autofocus required pattern="[a-zA-Z\s]">
</div>
<div class="radio">
<label>
<input type="radio" name="size" value="short">
Short
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="size" value="tall" checked>
Tall
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="size" value="grande">
Grande
</label>
</div>
<div class="form-group">
<label for="flavorShot">Flavor Shot</label>
<select id="flavorShot" class="form-control" name="flavor">
<option value="">None</option>
<option value="caramel">Caramel</option>
<option value="almond">Almond</option>
<option value="mocha">Mocha</option>
</select>
</div>
<div class="form-group">
<label for="strengthLevel">Caffeine Rating</label>
<input id="strengthLevel" type="range" name="strength" value="30">
</div>
<button type="submit" class="btn btn-default">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</form>
</div>
</div>
<div class="panel panel-default">
<div class="panel-body">
<h4>Pending Orders:</h4>
<div data-coffee-order="checklist">
</div>
</div>
</div>
</section>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js" charset="utf-8"></script>
<script src="scripts/datastore.js" charset="utf-8"></script>
<script src="scripts/validation.js" charset="utf-8"></script>
<script src="scripts/formHandler.js" charset="utf-8"></script>
<script src="scripts/checklist.js" charset="utf-8"></script>
<script src="scripts/truck.js" charset="utf-8"></script>
<script src="scripts/main.js" charset="utf-8"></script>
</body>
</html>

Making a sum with 4 values and a button

I'm trying to make a sum of 4 entries in 4 text type and everything seems fine except that when I click the button, it won't set the sum. Like if I enter 1 in each text input, the text input for the sum should show 4. Thanks!
here's my Javascript code :
(function(){
var oForm = document.forms;
oForm[2].querySelector("input[type='button']").
addEventListener("click",
sommeValeur,
false);
}) ()
function sommeValeur() {
var aTxt = document.forms[0].tEx1;
var total = document.forms[0].tEx2;
var txt1 = aTxt[0].value;
var txt2 = aTxt[1].value;
var txt3 = aTxt[2].value;
var txt4 = aTxt[3].value;
total = parseInt(txt1) + parseInt(txt2) + parseInt(txt3) + parseInt(txt4) ;
return true;
}
Here's my html code :
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="css/form.css" />
</head>
<body>
<section>
<form name="frm1">
<label> Valeur 1:
<input type="text" name="tEx1" />
</label>
<label> Valeur 2:
<input type="text" name="tEx1" />
</label>
<label> Valeur 3:
<input type="text" name="tEx1" />
</label>
<label> Valeur 4:
<input type="text" name="tEx1" />
</label>
</form>
</section>
<section>
<form name="frm2">
<label> Somme:
<input type="text" name="tEx2" />
</label>
</form>
</section>
<section>
<form name="frm3">
<label>
<input type="button"
value="bouton"
name="btn1" /></br>
</label>
</form>
</section>
</body>
<script src="js/exercise4.js"></script>
</html>
It looks like your input for total is in the second form, so you need form[1] and also you need to use total.value to set the value:
var total = document.forms[1].tEx2;
...
total.value = parseInt(txt1) + parseInt(txt2) + parseInt(txt3) + parseInt(txt4) ;
Live example:
(function(){
var oForm = document.forms;
oForm[2].querySelector("input[type='button']").
addEventListener("click",
sommeValeur,
false);
}) ()
function sommeValeur() {
var aTxt = document.forms[0].tEx1;
var total = document.forms[1].tEx2;
var txt1 = aTxt[0].value;
var txt2 = aTxt[1].value;
var txt3 = aTxt[2].value;
var txt4 = aTxt[3].value;
total.value = parseInt(txt1) + parseInt(txt2) + parseInt(txt3) + parseInt(txt4) ;
return true;
}
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="css/form.css" />
</head>
<body>
<section>
<form name="frm1">
<label> Valeur 1:
<input type="text" name="tEx1" />
</label>
<label> Valeur 2:
<input type="text" name="tEx1" />
</label>
<label> Valeur 3:
<input type="text" name="tEx1" />
</label>
<label> Valeur 4:
<input type="text" name="tEx1" />
</label>
</form>
</section>
<section>
<form name="frm2">
<label> Somme:
<input type="text" name="tEx2" />
</label>
</form>
</section>
<section>
<form name="frm3">
<label>
<input type="button"
value="bouton"
name="btn1" /></br>
</label>
</form>
</section>
</body>
</html>
You are changing the total instance and not the total.value.
In the line total = ...+...+..+...; you are basically replacing the label with the sum. You should set the label text instead: total.value = ...+..+...+...;

Adding a node to html page with javascript

This is my first time with javascript. I'm making a basic login page where there is a control for the email input. I would like to put an error message of some kind when someone gives an email address with illegal symbol. Here my code:
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta charset="UTF-8">
</head>
<body>
<div>
<form action="Home.html" method="post">
<label for="id">Username</label>
<input type="text" name="id" id="id" value="" />
<br/>
<label for="pass">Password</label>
<input type="password" name="pass" id="pass" value="" />
<br/>
<label for="email">Email</label>
<input type="email" name="email" id="email" value="" />
<br/>
<script type="text/javascript">
function checkEmail ()
{
var emailObject = document.getElementById("email");
var email = emailObject.getAttribute("value").toString();
var error = document.createTextNode("Uncorrect email");
var result = email.search("/[^(a-z | A-Z | 0-9 | #)]/");
if(result !== -1)
{
emailObject.appendChild(error);
}
}
</script>
<button type="button" onclick="checkEmail()"> Confirm </button>
</form>
</div>
</body>
</html>
I have a function I use to validate email addresses, it uses regex. I would suggest jQuery just to show/hide the error message.
function validEmail(val){
if(val.length < 6 || val.length > 255) return false;
return new RegExp(/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/).test(val);
}
$(function(){
$("#email").on("change", function(){
var email = $("#email").val();
if(!validEmail(email)){
$("#emailError").show();
} else {
$("#emailError").hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<!-- Some Inputs here -->
<span id='emailError' style='display: none;'>Please enter a valid email address</span><br>
<input type='email' id='email' name='email' placeholder='Email Address' />
<!-- More Inputs here -->
<button type='submit'>Submit</button>
</form>
you're trying to append something to an input element (email input, in this case). I'd suggest to append it to your main div, which in this case I have identified as "YOUR_ID".
Also, I suggest you a more efficint way to check a valid email.
follow the below example
<body>
<div id="YOUR_ID">
<form action="Home.html" method="post">
<label for="id">Username</label>
<input type="text" name="id" id="id" value="" />
<br/>
<label for="pass">Password</label>
<input type="password" name="pass" id="pass" value="" />
<br/>
<label for="email">Email</label>
<input type="email" name="email" id="email" value="" />
<br/>
<script type="text/javascript">
function checkEmail ()
{
var emailObject = document.getElementById("email");
var divObject = document.getElementById("YOUR_ID");
var email = emailObject.getAttribute("value").toString();
var error = document.createTextNode("Uncorrect email");
var check = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var result = check.test(email);
if(result !== -1)
{
divObject.appendChild(error);
}
}
</script>
<button type="button" onclick="checkEmail()"> Confirm </button>
</form>
</div>
</body>

Firebug returning odd error for one getElementById

I have the following lines of js
var select_container = "container_"+parts[2];
var get_container = document.getElementById(select_container);
The function this is part of is failing and when I look in firebug it returns get_container as undefined. I have checked select_container is the correct value and that there isn't a duplicate id on page.
This is called by an onclick event so I can't see waiting for the page to load being an issue (the result is same no matter how long I wait).
revelent html example:
<div id="container_0">
I'm stumped!
edit
This is all the Javascript from the parent functions
/*detects links in the form editor and uses them to adjust the layout*/
window.onload = function () {
clickDetection();
} /*detect clicks on interesting links*/
function clickDetection() {
var canvas = document.getElementById("content");
var dumbLinks = canvas.getElementsByTagName("a");
for (var i = 0; i < dumbLinks.length; i++) {
dumbLinks[i].onclick = function () {
clickRoute(this);
return false
};
}
} /*reroute click behaviour to correct function*/
function clickRoute(link_object) {
var linkId = link_object.getAttribute("id");
var linkParts = linkId.split("_");
if (linkParts[1] == "delete") {
delete_route(linkParts);
} else if (linkParts[1] == "new") {
new_route(linkParts);
}
}
function delete_route(parts) {
alert(parts);
if (parts[0] == "field") {
var select_container = "container_" + parts[2];
var get_container = document.getElementById(select_container);
document.removeChild(get_container);
} else if (parts[0] == "option") {
alert("delete a option");
}
}
full (typical) html (please note repeating sections have been cut for length and other details changed for secuity):
<!DOCTYPE HTML>
<html>
<head>
<!-- determines header content -->
<meta charset="utf-8" />
<meta name="description" content="Free Web tutorials" />
<meta name="keywords" content="HTML,CSS,XML,JavaScript" />
<script type="text/javascript" src="some.js"></script>
<title>Title of the document</title>
</head>
<body>
<div class="bignavblock"><p>nav link</p></div>
<div class="bignavblock"><p>nav linke</p></div>
<div class="bignavblock"><p>nav link</p></div>
<div class="bignavblock"><p>nav link</p></div>
<div class="bignavblock"><p>nav link</p></div>
<div class="bignavblock"><p>nav link</p></div>
<div id="content">
<h1>screen name</h1>
<form method="post" action="#this">
<label for="summary">Select an item to edit:<br></label>
<select name="summary" id="summary">
<option value="generic">generic</option>
<option value="updated">updated</option>
</select>
<input type="submit" name="summary_select" value="Select">
</form>
<h2>screen name</h2>
<div id="container_7">
<form method="post" action="#this">
<fieldset><legend>existing segment</legend>
<p><a id="field_delete_7" href="#">Delete field</a></p>
<label for="name_7">Field Name</label><input type=text id="name_7" name="name" value="Colour"><br>
<label for="type_7">Data type expected</label>
<select name="type" id="type_7">
<option value="name" >Name</option>
<option value="email" >Email Address</option>
<!-- cut for length -->
</select>
<p>Some text</p>
<label for="option_7_0">Option Value</label><input type=text id="option_7_0" name="option_7_0" value="Red">
<a id="option_delete_7_0" href="#">Delete option</a><br>
<label for="option_7_1">Option Value</label><input type=text id="option_7_1" name="option_7_1" value="Green">
<a id="option_delete_7_1" href="#">Delete option</a><br>
<label for="option_7_2">Option Value</label><input type=text id="option_7_2" name="option_7_2" value="Blue">
<a id="option_delete_7_2" href="#">Delete option</a><br>
<a id="option_new_7" href="#">Add new option</a>
<input type="submit" name="detail" value="Finish"></fieldset></form></div>
<p><a id="field_new" href="#">Add new field</a></p>
</div>
<!-- determines footer content -->
footer content
</body>
</html>
Change this:
document.removeChild(get_container);
to this:
get_container.parentNode.removeChild(get_container);
or if the containers are a direct descendant of body, then you could do this:
document.body.removeChild(get_container);

Categories