Show a preview picture using JavaScript before uploading files - javascript

I have a little script for uploading images with PHP and showing a preview picture before click "upload". It uses an input "multiple" for upload multiple files... So done, it works fine, but I have a little problem ...
When I duplicate the input type="file" (and erase Multiple) with two, three or more inputs, PHP processes the uploaded files but JavaScript shows the first picture only ...
How can I show a picture for all the inputs?
This is my script :
index.php
<?php include("file-upload.php"); ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<title>PHP 7 Upload Multiple Files Example</title>
<style>
.container {
max-width: 450px;
}
.imgGallery img {
padding: 8px;
max-width: 100px;
}
</style>
</head>
<body>
<div class="container mt-5">
<form action="" method="post" enctype="multipart/form-data" class="mb-3">
<h3 class="text-center mb-5">Upload Multiple Images in PHP 7</h3>
<div class="user-image mb-3 text-center">
<div class="imgGallery">
<!-- Image preview -->
</div>
</div>
<div class="custom-file">
<input type="file" name="fileUpload[]" class="custom-file-input" id="chooseFile" multiple>
<label class="custom-file-label" for="chooseFile">Select file</label>
</div>
<button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
Upload Files
</button>
</form>
<!-- Display response messages -->
<?php if(!empty($response)) {?>
<div class="alert <?php echo $response["status"]; ?>">
<?php echo $response["message"]; ?>
</div>
<?php }?>
</div>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script>
$(function() {
// Multiple images preview with JavaScript
var multiImgPreview = function(input, imgPreviewPlaceholder) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(imgPreviewPlaceholder);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#chooseFile').on('change', function() {
multiImgPreview(this, 'div.imgGallery');
});
});
</script>
</body>
</html>

The #chooseFile CSS selector selects by ID - that's what the # does. IDs must be unique in HTML (obviously, because the whole point of an ID is to uniquely identify something). So to make that select several input elements, you'd be best to use a class instead as the selector.
For example:
$(function() {
// Multiple images preview with JavaScript
var multiImgPreview = function(input, imgPreviewPlaceholder) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(imgPreviewPlaceholder);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('.chooseFile').on('change', function() {
console.log("detected change");
multiImgPreview(this, 'div.imgGallery');
});
});
.imgGallery img {
padding: 8px;
max-width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="custom-file">
<input type="file" name="fileUpload[]" class="custom-file-input chooseFile">
<label class="custom-file-label" for="chooseFile">Select file</label>
</div>
<div class="custom-file">
<input type="file" name="fileUpload[]" class="custom-file-input chooseFile">
<label class="custom-file-label" for="chooseFile">Select file</label>
</div>
<div class="custom-file">
<input type="file" name="fileUpload[]" class="custom-file-input chooseFile">
<label class="custom-file-label" for="chooseFile">Select file</label>
</div>
<div class="imgGallery">
<!-- Image preview -->
</div>
You might find jQuery's documentation about selectors is useful background reading: https://api.jquery.com/category/selectors/

Related

Google Apps Script HTML form won't submit for overseas user

I have a small sidebar form that submits user data. It is all functional for anyone in the USA but if someone from overseas tries to submit the form, it fails. I even logged into the same user account as the one overseas and the form submits for me. I have never encountered an issue like this with GAS. The account the user is logged into owns the spreadsheet that the script is housed in and he has tried both local and US IP addresses to submit the data (not sure if this even matters.) What do I need to change/include in my scripts to allow all users to be able to submit the form? Would creating a Webapp and trigger be a fix?
Code.gs
//OPEN THE FORM IN SIDEBAR
function showFormInSidebar() {
var form = HtmlService.createTemplateFromFile('Index').evaluate().setTitle('New Client');
SpreadsheetApp.getUi().showSidebar(form);
}
//PROCESS FORM DATA
function processForm(formObject){
var notes = [formObject.client,
formObject.website,
formObject.email,
formObject.plan];
var mTabs = [formObject.client,
formObject.plan,
formObject.timeAllowed,
'',
'',
'00:00:00.000'];
pushToSheets(notes,mTabs);
}
//INCLUDE HTML PARTS, EG. JAVASCRIPT, CSS, OTHER HTML FILES
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
//THIS FUNCTION IS USED TO PUSH DATA TO EACH RESPECTIVE SHEET FROM THE SIDEBAR FORM SUBMISSION
function pushToSheets(notes,mTabs) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var noteTab = ss.getSheetByName('NOTES');
var sheetArr = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEPT','OCT','NOV','DEC'];
// var sheetArr = ['JAN','FEB'];
var nLast = noteTab.getLastRow();
noteTab.insertRowBefore(nLast+1);
noteTab.getRange(nLast+1, 1,1,4).setValues([notes]);
noteTab.getRange(2,1,nLast+1,17).sort([{column: 4, ascending: true}, {column: 1, ascending: true}])
for(var x = 0; x < sheetArr.length; x++) {
var sheet = ss.getSheetByName(sheetArr[x]);
var sLength = sheet.getLastRow();
sheet.insertRowBefore(sLength-1);
sheet.getRange(sLength-1, 1,1,6).setValues([mTabs]);
sheet.getRange(2, 1,sLength,11).sort([{column: 2, ascending: true}, {column: 1, ascending: true}])
}
}
Index.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<?!= include('JavaScript'); ?> <!-- See JavaScript.html file -->
<title>Contact Details</title>
</head>
<body class="bg-secondary text-light">
<div class="container">
<?!= include('Form'); ?> <!-- See Form.html file -->
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
<script>
$('#timeAllowed').keypress(function() {
var regex = new RegExp("^[0-9]");
var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
if(this.value.length == 2){
this.value = this.value+':';
}
if(this.value.length == 5){
this.value = this.value+':00';
}
if(this.value.length > 7) {
return false;
}
});
</script>
</body>
</html>
Form.html
<form id="myForm" onsubmit="handleFormSubmit(this)" autocomplete="off">
<div class="form-group">
<label for="client">Client</label>
<input class="form-control form-control-sm" type="text" class="form-control" id="clint" name="client" placeholder="Client Name">
</div>
<div class="form-group">
<label for="gender">Plan</label>
<select class="form-control form-control-sm" id="plan" name="plan" required>
<option value="" selected disabled>Choose...</option>
<option value="00 hosting">00 hosting</option>
<option value="01 slim">01 slim</option>
<option value="02 basic">02 basic</option>
<option value="10 special">10 special</option>
<option value="99 coming up">99 coming up</option>
</select>
</div>
<div class="form-group">
<label for="last_name">Time Allowed</label>
<input class="form-control form-control-sm" type="text" class="form-control" pattern="[0-9][0-9]:[0-9][0-9]:[0-9][0-9]" title ="00:00:00" id="timeAllowed" name="timeAllowed" placeholder="00:00:00">
</div>
<div class="form-group">
<label for="email">Email</label>
<input class="form-control form-control-sm" type="email" class="form-control" id="email" name="email">
</div>
<div class="form-group">
<label for="website">Website</label>
<input class="form-control form-control-sm" type="text" class="form-control" id="website" name="website">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
JavaScript.html
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function handleFormSubmit(formObject) {
google.script.run.processForm(formObject);
document.getElementById("myForm").reset();
}
</script>
Looks like I just needed to add this as a Webapp and that fixed the issue. Thank you for the suggestions!
//OPEN THE FORM IN SIDEBAR
function showFormInSidebar() {
var form = HtmlService.createTemplateFromFile('test').evaluate().setTitle('New Client');
SpreadsheetApp.getUi().showSidebar(form);
}
function doGet() {
var form = HtmlService.createTemplateFromFile('Index').evaluate().setTitle('New Client');
form.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
return form;
}
test.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<center>
<embed type="text/html" src="redacted" width="290" height="800">
</center>
</body>
</html>

Redirect page after checking password

I use the userClicked() in code.gs of my google apps script to save some data if the user password in login.html is correct.
How can I redirect the user to page.html after saving data in line #18?
I want to redirect only if the password is correct. So I can't use simple on the login page.
Code.gs file
login.html
code.gs
function doGet(e) {
if (!e.parameters.v){
return HtmlService.createTemplateFromFile("login").evaluate();
}
else {
return HtmlService.createTemplateFromFile(e.parameters['v']).evaluate();
}
}
function userClicked(userInfo){
if (userInfo.userPassword && userInfo.userPassword == userInfo.dbPassword){
/* save page data in a google spreadsheet */
var ss = SpreadsheetApp.openById("1OU6y0Iid5r2xGcfxZpUqGzZjZo8Gz7rALkYcajCslN8"); // calls "DB_" spreadsheet
var ws = ss.getSheetByName("Sheet1");
var lastRow = ws.getRange("A1").getDataRegion().getLastRow(); // get last row of column A
var lastRow1 = lastRow + 1;
ws.getRange("A"+ lastRow1 +":D"+ lastRow1).setValues([[new Date(), userInfo.userName, userInfo.userPassword, userInfo.dbPassword ]]);
}
}
function include(filename){
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
function lookup(pass){
var ss = SpreadsheetApp.openById("1gBo8UrCpqtQ5Rf67HCriEDRhJeQuhvPZ1vebeTHndt0"); // calls "Therapists" spreadsheet
var ws = ss.getSheetByName("Therapists");
var data = ws.getRange(1, 4, ws.getLastRow(), 2).getValues();
var therapistsList = data.map(function(r){ return r[0];});
var passwordsList = data.map(function(r){ return r[1];});
var position = therapistsList.indexOf(pass);
if (position > -1){
return passwordsList[position];
}
else {
return 'Not Found!';
}
}
Login.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<?!= include("css"); ?>
</head>
<body>
<div class="container">
<p>Login</p>
<div class="row">
<div class="input-field col s3">
<input id="username" type="text" class="validate">
<label for="username">Username</label>
</div>
<div class="input-field col s3">
<input disabled id="dbPass" type="text" class="validate">
<label for="dbPass">Database Pass</label>
</div>
</div><!-- row -->
<div class="row">
<div class="input-field col s3">
<input id="userPass" type="text" class="validate">
<label for="userPass">Password</label>
</div>
</div><!-- row -->
<div class="row">
<button id="btn" class="waves-effect waves-light btn-small blue accent-4"><i class="material-icons left">play_arrow</i>submit</button>
</div>
</div> <!-- Container -->
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<?!= include("js_"); ?>
</body>
</html>
add tag and surround inside all your input field and other elements that take values from user.use return attribute with your function name. Return attribute does is; if your function returns true you can direct return false, you can't redirect
Ex:
<form onsubmit="return productsvalidationform();" method="POST" action="AddProductServlet">
<div class="form-group">
<label>Product Name</label><br> <input type="text" required class="form-control" name="ProductName" placeholder="productname" id="productname">
</div>
</form>
productsvalidationform(); is the function,This function return true or false.If true we can be redirected to AddProductServlet.In the form tag, include action attribute that describes where you want to go.

dynamically add fields to HTML form, send data AND remember added fields and values

I have the following problem:
I want to add textfields to my html form, send them to my script and than redirect back AND have the number of fields and their values shown.
Adding the fields via jQuery is working fine, but I can't store the values later on, because it's done via adding DIVs and they're having the same name.
Can someone point me to the right direction?
Here's the code in my index.php and in my action.php
index.php
<?php
session_start([
'cookie_lifetime' => 3600,
]);
?>
<html>
<head>
<!-- HTML5 -->
<meta charset='utf-8'>
<!-- HTML 4.x -->
<meta http-equiv='content-type' content='text/html; charset=utf-8'>
<link rel='stylesheet' href='https://unpkg.com/purecss#1.0.0/build/pure-min.css' integrity='sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w' crossorigin='anonymous'>
<link rel='stylesheet' href='style/style.css'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>
myDrop2
</title>
<script src="scripts/jquery.js"></script>
</head>
<body>
<script>
function showLoadingMessage() {
document.getElementById('content').style.display = 'none';
var message = document.createElement('div');
message.innerHTML = '<center><h1>Wird gearbeitet, bitte warten!</h1></center>';
document.body.appendChild(message);
}
function checkRemove() {
if ($('div.d1_drops').length == 1) {
$('#remove').hide();
} else {
$('#remove').show();
}
};
$(document).ready(function() {
checkRemove()
$('#add').click(function() {
$('div.d1_drops:last').after($('div.d1_drops:first').clone());
$('div.d2_drops:last').after($('div.d2_drops:first').clone());
checkRemove();
});
$('#remove').click(function() {
$('div.d1_drops:last').remove();
$('div.d2_drops:last').remove();
checkRemove();
});
});
</script>
<center>
<div id='header'>
<b>myDrop2</b>
</div>
<br><br>
<div id='content'>
<br>
<button id='add'>[ + ]</button>
<button id='remove'>[ - ]</button>
<form action=scripts/action.php class='pure-form pure-form-aligned' onsubmit='showLoadingMessage();' method='post'>
<!-- <form action=scripts/action.php class='pure-form pure-form-aligned' onsubmit='showLoadingMessage();' method='post'> -->
<div id='settings1'>
<br>
Belichtung starten
<br><br>
<label>Warten (ms) <input name='firstwait' type='number'></label>
</div>
<div id='ventile'>
<div id='ventil1'>
<input type='radio' id='v1' name='ventile' value='1' checked='checked'>
<label for='v1'><h2>1 Ventil</h2></label>
<br><br>
<div class='d1_drops'>
<label>Tropfen 1 Dauer (ms) <input name='d1_drop[]' type='number'></label>
<br><br>
<label>Warten (ms) <input name='d1_wait[]' type='number'></label>
<br><br>
</div>
</div>
<div id='ventil2'>
<input type='radio' id='v2' name='ventile' value='2'>
<label for='v2'><h2>2 Ventile</h2></label>
<br><br>
<div class='d2_drops'>
<label>Tropfen 1 Dauer (ms) <input name='d2_drop[]' type='number'></label>
<br><br>
<label>Warten (ms) <input name='d2_wait[]' type='number'></label>
<br><br>
</div>
</div>
</div>
<div id='settings2'>
Blitzen
<br><br>
<label>Warten (ms) <input name='lastwait' type='number'></label>
<br><br>
Belichtung stoppen
<br><br>
</div>
<div id='run'>
<button type='submit'>ausführen</button>
<br>
<br>
</div>
</form>
</div>
</center>
</body>
</html>
action.php
<?php
session_start();
include ('../conf.php');
$d1_array_drop = $_POST['d1_drop'];
$d1_array_wait = $_POST['d1_wait'];
$d2_array_drop = $_POST['d2_drop'];
$d2_array_wait = $_POST['d2_wait'];
(...) do stuff with the data (..)
header('Location: ' . $_SERVER['HTTP_REFERER']);
?>
You can use sessionstorage or localstorage to remember values,if you want to output values from php ,first store them in session|files|db after redirecting , you can just output the values to js
<?php
$data=$_SESSION["data"];
?><script>
var data=<?php echo json_encode($data);?>;
</script>

I'm Duplicating Javascript

We will have a set of records where the user will select what color they want that section to be. As you can see I'm duplicating script code so that I can change the colors of a div. This value will be stored in mysql and retrieved when the user access the page again. Is there a way to format this code so that it's not duplicated 500 times? Thank you for your help. --newbie
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<script type="text/javascript" src="//code.jquery.com/jquery-1.4.3.min.js"></script>
<style type="text/css">
#full {
background-color: #ffffff;
}
</style>
<title></title>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function(){
$(".theme").change(function()
{var background = $("#color1").val();
$("#full").css("background-color", background);
});
$(".theme2").change(function()
{var background = $("#color2").val();
$("#full2").css("background-color", background);
});
$(".theme3").change(function()
{var background = $("#color3").val();
$("#full3").css("background-color", background);
});
});
});//]]>
</script>
<link rel="stylesheet" href="css/color_picker.css" type="text/css" />
<script language="javascript" type="text/javascript" src="js/jquery.colorpicker.js"/></script>
<script type="text/javascript">
//Run the code when document ready
$(function() {
$('#color1').colorPicker({showHexField: false});
$('#color2').colorPicker({showHexField: false});
});
</script>
</head>
<body>
<body >
<label for="color">Color :</label> </td><td>
<div id="full">
<form method="post" action="">
<input id="color1" type="hidden" name="color1" value="" class="theme"/>
</div>
<div id="full2" border="1" width="100%">
<input id="color2" type="hidden" name="color2" value="" class="theme2"/>
</div>
<div id="full3" border="1" width="100%">
<input id="color3" type="hidden" name="color3" value="" class="theme3"/>
</div>
</form>
</body>
instead of using Id's, you can use classes like full and theme, so your html for any given set would look like
<form method="post" action="">
<div class="full">
<input id="color1" type="hidden" name="color1" value="" class="theme"/>
</div>
<div class="full" border="1" width="100%">
<input id="color2" type="hidden" name="color2" value="" class="theme"/>
</div>
<div class="full" border="1" width="100%">
<input id="color3" type="hidden" name="color3" value="" class="theme"/>
</div>
</form>
Then your javascript would look like
$('.theme').change(function() {
var $this = $(this);
var background= $this.val();
$this.closest('.full').css("background-color", background);
})
edit: fixed bug, changed from parent to closest so that .full doesn't have to be a direct parent of the input.
You can achieve this with a simple for loop.
If the number of colors is not static you can use the jquery "starts with" selector to get all of the elements and then take the length.
$(window).load(function(){
$(document).ready(function(){
//if the count is static you can just hardcode it
var colorCount = $("[id^='color']").length;
for(var i = 1; i <= colorCount; i++) {
var color = "#color" + i;
var full = "#full" + i;
var theme = ".theme" + i;
//only necessary because your first div does not have the number
if(i === 1) {
full = "#full";
theme = ".theme";
}
$(".theme").change(function()
{
var background = $(color).val();
$(full).css("background-color", background);
});
}
});
});
Below is a working snippet. There were some issues with your HTML, and I'm not sure if you were setting the .change() event intentionally, but for the demo I just changed it directly.
$(window).load(function(){
$(document).ready(function(){
var colorCount = $("[id^='color']").length;
for(var i = 1; i <= colorCount; i++) {
var color = "#color" + i;
var full = "#full" + i;
var theme = ".theme" + i;
//only necessary because your first div does not have the number
if(i === 1) {
full = "#full";
theme = ".theme";
}
var background = $(color).val();
$(full).css("background-color", background);
}
});
});
.color-box {
background-color: #ffffff;
border: solid 2px black;
min-height: 30px;
margin: 5px;
}
<script type="text/javascript" src="//code.jquery.com/jquery-1.4.3.min.js"></script>
<label for="color">Color :</label>
<form method="post" action="">
<div id="full" class="color-box">
<input id="color1" type="hidden" name="color1" value="lightblue" class="theme"/>
</div>
<div id="full2" class="color-box">
<input id="color2" type="hidden" name="color2" value="#226666" class="theme2"/>
</div>
<div id="full3" class="color-box">
<input id="color3" type="hidden" name="color3" value="rgba(140,15,110,.6)" class="theme3"/>
</div>
</form>

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