Currently i am able to replicate a form, however i want to set a limit to the number of times it is able to do so(replicate). Is there a way to make it so that when, for example i want the limit to be 5, once the total number of forms hit 5 the "add" button will be disabled(when i click it, its does nothing). However when i remove a form the "add" button becomes functional(can add form) again. I am only allowed to use HTML CSS and Javascript.
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p').size() + 1;
$('#addNew').live('click', function() {
$('<label>Choose a picture<br><input type="file" ' + i + '" value="" /><img class="target" src="#" alt="Choose and Upload" />Remove</label><br>').appendTo(addDiv);
i++;
$('fieldset input').change(function() {
if (this.files && this.files[0]) {
var $target = $(this).next('.target');
var reader = new FileReader();
reader.onload = function(e) {
$target.attr('src', e.target.result).width(150).height(112);
};
reader.readAsDataURL(this.files[0]);
}
});
return false;
});
$('#remNew').live('click', function() {
if (i > 2) {
$(this).parents('label').remove();
i--;
}
return false;
});
});
.locationsector {
border-radius: 5px;
border: 5px solid black;
width: 30%;
margin-left: 0.79%;
float: left;
padding: 10px;
}
img {
text-align: center;
margin: 2%;
display: inline-block;
border: 10px solid #140E26;
border-radius: 10px;
padding: 5px;
width: 150px;
height: 112px;
}
#addNew {
background: black;
margin-left: 2%;
padding: 5px;
font-size: 15px;
color: white;
display: inline-block;
width: 100px;
border: 1px solid #140E26;
border-radius: 10px;
cursor: pointer;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<fieldset class="locationsector" id="addinput">
<legend>Test</legend>
<p>
<label for="north">Choose a Picture
<br>
<input type="file" required="required" />
<img class="target" src="#" alt="Choose and Upload" />
</label>
<br>
<a id="addNew">Add</a>
</p>
</fieldset>
You already have a counter i and that's good.
This will make it simpler for you to limit the replication:
// ...
$('#addNew').live('click', function() {
if(i > 5) {
alert("Reached maximum number of fields.");
return false;
}
$('<label>Choose a picture<br><input type="file" ' + i + '" value="" /><img class="target" src="#" alt="Choose and Upload" />Remove</label><br>').appendTo(addDiv);
// ...
The alert call is optional (You mentioned doing nothing?)
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I want to make a script, to automate my game.
First look my snippet demo to finding out how my games works.
I know this request is a bit confusing but please help
var randomNumber = randomNumberFromRange();
function randomNumberFromRange(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
$(".btn").click(function() {
var inp1 = $("#inp1");
var Gem = $("#Gem");
var $getRnd = $("#getRand");
if (Number(inp1.val()) > Number(Gem.val())) {
alert(" you don't have enough Gem");
e.preventDefault()
}
$getRnd.val(randomNumberFromRange(0, 1000));
if (Number($getRnd.val()) >= "500") {
$("#win").css("display", "block");
var sum = Number(inp1.val()) + Number(Gem.val());
Gem.val(Number(sum));
$("#lose").css("display", "none");
} else if (Number($getRnd.val()) <= "499") {
$("#lose").css("display", "block");
var sub = Number(Gem.val()) - Number(inp1.val());
Gem.val(Number(sub));
$("#win").css("display", "none");
}
});
#nav {
background-color: #1b354b;
border: 2pt solid gold;
text-align: center;
padding: 5px;
width: 800px;
height: auto;
margin: 0 auto;
}
#Left_button,
#Right_button {
background-color: gold;
text-align: center;
cursor: pointer;
border-radius: 5pt;
border: none;
width: 100px;
height: 30px;
margin: 5px;
font-size: larger;
}
#left_Box {
width: 300px;
height: 170px;
background-image: linear-gradient(#fff942, yellow);
;
text-align: center;
float: left;
margin-top: 5px;
}
#right_Box {
width: 500px;
height: 170px;
background-image: linear-gradient(#FFB75E, yellow);
text-align: center;
float: right;
margin-top: 5px;
}
#inp1,
#Gem,
#getRand {
text-align: center;
width: 50px;
color: #ff0d2f;
cursor: pointer;
font-size: large;
margin-top: 10px;
}
#lose {
display: none;
background-color: red;
padding: 10px;
margin-top: 15px;
}
#win {
display: none;
background-color: #64f26f;
padding: 10px;
margin-top: 15px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Model</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="nav">
<input id="Left_button" class="btn" type="button" value="Left">
<input id="Right_button" class="btn" type="button" value="Right">
<div id="Body">
<div id="left_Box">
<label><span style="font-size: large">Gem Chance : </span><input id="inp1" type="text" value="1"></label>
</div>
<div id="right_Box">
<label><span style="font-size: large">Gems : </span><input id="Gem" type="text" value="1000"
disabled></label><br>
<label><span style="font-size: large">Number : </span><input id="getRand" type="text" value=""></label>
<br>
<i style="color: #1b354b"> win : higher than 499</i>
<br>
<i style="color: #1b354b"> lose : lower than 500</i>
<div id="Place">
<div id="lose">lose</div>
<div id="win">win</div>
</div>
</div>
</div>
</div>
</body>
</html>
we have important parameters here.
Gem Chance :
Gems :
I want to create a script to do
1 - click buttons by random(left & right) every 2 sec . (click)
2 - after losing 3 times (continuous) , change the Gem chance to X (X=2)
3 - click
4 - if win => reset => change Gem chance to 1
and start from part 1;
5 - if lose => change Gem chance to 1
and click ;
if lose = > change Gem chance to 2X
click ;
if win :
reset => change Gem chance to 1
and start from part 1
if lose :
change Gem chance to 1
click ;
if win : reset
but ( after 3 losing changes the Gem chance to last lose value )
last example:
After we reached 3 consecutive losses
After each loss
The chance of a gem becomes 1. And click.
And again the chance of gem
It doubles and clicks.
This will happen until we win.
But if between losses
When the gem chance.
He gave us the victory over the number 1
All steps are performed from the beginning with the difference that
Since the chance of gem. It's doubling its last loss.
I give you the code to begin to build what you want, its the routine which launch every 2 sec the function automate and click randomly on left or right button.
var randomNumber = randomNumberFromRange();
//begin to automate
var timer = setInterval(automate, 2000);
var buts=[$("#Left_button"), $("#Right_button")];
var win = 0;
var loose = 0;
var loop = 0;
function automate(){
var idx=randomNumberFromRange(0, 1);
buts[idx].trigger("click");
console.log("i click on " + buts[idx].attr("id"));
console.log("i " + $("#Place div[style='display: block;']").attr('id'));
$("#inp1").val("111");//sample to modify the value of Gem chance
if(loop++ == 4) clearInterval(timer);//stop call the function after some loop
}
function randomNumberFromRange(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
$(".btn").click(function () {
var inp1 = $("#inp1");
var Gem = $("#Gem");
var $getRnd = $("#getRand");
if (Number(inp1.val()) > Number(Gem.val())) {
alert(" you don't have enough Gem");
e.preventDefault()
}
$getRnd.val(randomNumberFromRange(0, 1000));
if (Number($getRnd.val()) >= "500") {
$("#win").css("display", "block");
var sum = Number(inp1.val()) + Number(Gem.val());
Gem.val(Number(sum));
$("#lose").css("display", "none");
} else if (Number($getRnd.val()) <= "499") {
$("#lose").css("display", "block");
var sub = Number(Gem.val()) - Number(inp1.val());
Gem.val(Number(sub));
$("#win").css("display", "none");
}
});
#nav {
background-color: #1b354b;
border: 2pt solid gold;
text-align: center;
padding: 5px;
width: 800px;
height: auto;
margin: 0 auto;
}
#Left_button, #Right_button {
background-color: gold;
text-align: center;
cursor: pointer;
border-radius: 5pt;
border: none;
width: 100px;
height: 30px;
margin: 5px;
font-size: larger;
}
#left_Box {
width: 300px;
height: 170px;
background-image: linear-gradient(#fff942, yellow);;
text-align: center;
float: left;
margin-top: 5px;
}
#right_Box {
width: 500px;
height: 170px;
background-image: linear-gradient(#FFB75E, yellow);
text-align: center;
float: right;
margin-top: 5px;
}
#inp1, #Gem, #getRand {
text-align: center;
width: 50px;
color: #ff0d2f;
cursor: pointer;
font-size: large;
margin-top: 10px;
}
#lose {
display: none;
background-color: red;
padding: 10px;
margin-top: 15px;
}
#win {
display: none;
background-color: #64f26f;
padding: 10px;
margin-top: 15px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Model</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="nav">
<input id="Left_button" class="btn" type="button" value="Left">
<input id="Right_button" class="btn" type="button" value="Right">
<div id="Body">
<div id="left_Box">
<label><span style="font-size: large">Gem Chance : </span><input id="inp1" type="text" value="1"></label>
</div>
<div id="right_Box">
<label><span style="font-size: large">Gems : </span><input id="Gem" type="text" value="1000"
disabled></label><br>
<label><span style="font-size: large">Number : </span><input id="getRand" type="text" value=""></label>
<br>
<i style="color: #1b354b"> win : higher than 499</i>
<br>
<i style="color: #1b354b"> lose : lower than 500</i>
<div id="Place">
<div id="lose">lose</div>
<div id="win">win</div>
</div>
</div>
</div>
</div>
</body>
</html>
This question already has answers here:
Styling an input type="file" button
(46 answers)
Closed 5 years ago.
I have a file upload button which i need to file. I currently defaults to some pre-set styles.
<form class="uploadButton" method="POST" action="upload.php" enctype="multipart/form-data">
<input type="file" name="file[]" multiple>
</form>
You can try the below code
$('input[type="file"]').on('change', function() {
$('input[type="text"]').val($(this).val());
});
$('span').on('click', function() {
$('input[type="text"]').val($('input[type="file"]').val());
});
form.uploadButton {
position: relative;
display: flex;
}
input[type="text"] {
width: 200px;
height: 40px;
box-sizing: border-box;
border-radius: 2px;
border: 1px solid #ccc;
margin-right: 5px;
}
span {
background: red;
border: 0;
color: #fff;
padding: 0 20px;
width: 80px;
text-align: center;
line-height: 40px;
cursor: pointer;
}
input[type="file"] {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
opacity: 0;
cursor: pointer;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="uploadButton" method="" action="" enctype="multipart/form-data">
<input type="text">
<span>Browse</span>
<input type="file" name="file[]" multiple>
</form>
input[type="file"] {
display: none;
}
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
<form class="uploadButton" method="POST" action="upload.php" enctype="multipart/form-data">
<label for="file-upload" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i> Custom Upload
</label>
<input id="file-upload" type="file" name="file[]" multiple/>
</form>
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += "<br><strong>" + (i+1) + ". file</strong><br>";
var file = x.files[i];
if ('name' in file) {
txt += "Name: " + file.name + "<br>";
}
if ('size' in file) {
txt += "Size: " + file.size + " bytes <br>";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
::-webkit-file-upload-button {
background: black;
color: red;
padding: 0.5em;
}
<body onload="myFunction()">
<input type="file" id="myFile" class="custom-file-upload" multiple size="50" onchange="myFunction()">
<p id="demo"></p>
</body>
Try this.
'use strict';
;( function ( document, window, index )
{
var inputs = document.querySelectorAll( '.inputfile' );
Array.prototype.forEach.call( inputs, function( input )
{
var label = input.nextElementSibling,
labelVal = label.innerHTML;
input.addEventListener( 'change', function( e )
{
var fileName = '';
if( this.files && this.files.length > 1 )
fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
else
fileName = e.target.value.split( '\\' ).pop();
if( fileName )
label.querySelector( 'span' ).innerHTML = fileName;
else
label.innerHTML = labelVal;
});
// Firefox bug fix
input.addEventListener( 'focus', function(){ input.classList.add( 'has-focus' ); });
input.addEventListener( 'blur', function(){ input.classList.remove( 'has-focus' ); });
});
}( document, window, 0 ));
input[type="file"] {
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
width: 100%;
margin: 0;
padding: 0;
font-size: 1px;
cursor: pointer;
opacity: 0;
filter: alpha(opacity=0);
}
.inputfile + label span {
width: 200px;
min-height: 18px;
display: inline-block;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
vertical-align: top;
border: 1px solid #ccc;
}
.inputfile + label strong {
height: 100%;
color: #fff;
background-color: #d3394c;
display: inline-block;
}
.inputfile + label span,
.inputfile + label strong {
padding: 10px;
}
.inputfile + label svg {
width: 1em;
height: 1em;
vertical-align: middle;
fill: currentColor;
margin-top: -0.25em;
margin-right: 0.25em;
}
.box {
position: relative;
}
<div class="box">
<input type="file" name="file" id="file" class="inputfile" data-multiple-caption="{count} files selected" multiple />
<label for="file"><span></span> <strong><svg xmlns="http://www.w3.org/2000/svg" width="20" height="17" viewBox="0 0 20 17"><path d="M10 0l-5.2 4.9h3.3v5.1h3.8v-5.1h3.3l-5.2-4.9zm9.3 11.5l-3.2-2.1h-2l3.4 2.6h-3.5c-.1 0-.2.1-.2.1l-.8 2.3h-6l-.8-2.2c-.1-.1-.1-.2-.2-.2h-3.6l3.4-2.6h-2l-3.2 2.1c-.4.3-.7 1-.6 1.5l.6 3.1c.1.5.7.9 1.2.9h16.3c.6 0 1.1-.4 1.3-.9l.6-3.1c.1-.5-.2-1.2-.7-1.5z"/></svg> Choose a file…</strong></label>
</div>
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += "<br><strong>" + (i+1) + ". file</strong><br>";
var file = x.files[i];
if ('name' in file) {
txt += "Name: " + file.name + "<br>";
}
if ('size' in file) {
txt += "Size: " + file.size + " bytes <br>";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
<body onload="myFunction()">
<input type="file" id="myFile" class="custom-file-upload" multiple size="50" onchange="myFunction()">
<p id="demo"></p>
</body>
Try something like this.
document.getElementById("file-upload").addEventListener("change", function() {
var fullPath = document.getElementById("file-upload").value
var filename = fullPath.replace(/^.*[\\\/]/, '')
document.getElementById("status").innerHTML = filename;
});
.file-upload {
opacity: 0;
position: absolute;
top:0;
left:0;
height:75px;
width:100%;
border: 1px solid red;
}
.file-container {
position:relative;
}
.custom-file-upload {
position: absolute;
top:0;
left:0;
}
#status {
font-size: 25px;
color:red;
font-weight: bold;
}
<div class="file-container">
<div class="custom-file-upload">
Put fancy <img src="https://cdn3.iconfinder.com/data/icons/badger-s-christmas/300/stocking-32.png" /> stuff here <img src="https://cdn3.iconfinder.com/data/icons/badger-s-christmas/300/bells-48.png" /> (click me)
<input type="file" class="file-upload" id="file-upload" />
</div>
</div><br /><br /><br /><p id="status"></p>
Step 1. Create a simple html markup
<div class="fileUpload btn btn-primary">
<span>Upload</span>
<input type="file" class="upload" />
</div>
Step 2. CSS: Tricky Part
.fileUpload {
position: relative;
overflow: hidden;
margin: 10px;
}
.fileUpload input.upload {
position: absolute;
top: 0;
right: 0;
margin: 0;
padding: 0;
font-size: 20px;
cursor: pointer;
opacity: 0;
filter: alpha(opacity=0);
}
Is there any reason as to why I cannot get the Upload button to display the name of the file(s) uploaded despite copying exactly the tutorial on YouTube - see link below?
In the tutorial e is used for the eventListener function in JS, but Adobe Dreamweaver is having none of it, so I used addEventListener
Thanks in advance for any insight. :)
https://www.youtube.com/watch?v=JML3BZo_ToA&list=PLQ0Y5YcHFmjVCFO7t1_72VU2FiXo5XaEI&index=1
$(document).ready(function(){
"use strict";
$("#uploadBtn").on("change", function(){
var files = $(this)[0].files;
if(files.length >= 2){
$("#label_span").text(files.length + " files ready to upload");
} else {
var filename = addEventListener.target.value.split('\\').pop();
$("#label_span").text(filename);
}
});
});
.uploadFile{
height: auto;
padding: 30px;
background-color: #E0DDDD;
color: #797979;
}
#uploadBtn{
display: none;
width: auto;
}
.uploadButtonLabel{
font-size:18px;
padding: 10px 40px;
border-style: none;
margin-top: 10px;
text-align: center;
}
.uploadButtonLabel:before{
font-family: fontAwesome;
content: "\f093";
margin-right: 10px;
}
.uploadButtonLabel:hover{
cursor: pointer;
}
<head>
<script type="text/javascript" src="../JS Documents/bookCastingJS.js"></script>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<div class="uploadFile">
<h2>Upload your documents...</h2>
<p>Please ensure that you upload your require documents. Failure to do will may delay your applications.</p>
<label for="uploadBtn" class="uploadButtonLabel calltoActionButton" id="label_span">Select file(s) to upload</label>
<input style="width: 25%;" type="file" id="uploadBtn" name="upload" multiple = "true" />
</div>
<script src="bookCastingJS.js"></script>
You can just use your files variable instead.
$(document).ready(function() {
"use strict";
$("#uploadBtn").on("change", function() {
var files = $(this)[0].files;
if (!files) return;
if (files.length > 1) {
$("#label_span").text(files.length + " files ready to upload");
} else {
var filename = files[0].name;
$("#label_span").text(filename);
}
});
});
.uploadFile {
height: auto;
padding: 30px;
background-color: #E0DDDD;
color: #797979;
}
#uploadBtn {
display: none;
width: auto;
}
.uploadButtonLabel {
font-size: 18px;
padding: 10px 40px;
border-style: none;
margin-top: 10px;
text-align: center;
}
.uploadButtonLabel:before {
font-family: fontAwesome;
content: "\f093";
margin-right: 10px;
}
.uploadButtonLabel:hover {
cursor: pointer;
}
<head>
<script type="text/javascript" src="../JS Documents/bookCastingJS.js"></script>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<div class="uploadFile">
<h2>Upload your documents...</h2>
<p>Please ensure that you upload your require documents. Failure to do will may delay your applications.</p>
<label for="uploadBtn" class="uploadButtonLabel calltoActionButton" id="label_span">Select file(s) to upload</label>
<input style="width: 25%;" type="file" id="uploadBtn" name="upload" multiple="true" />
</div>
<script src="bookCastingJS.js"></script>
I'm attempting to make a remove button for my dynamically created input boxes, however I can't seem to get it to work. I get the feeling its because the "child" didn't exist upon initially loading the script, but I'm not sure.
Any help would be appreciated. Thanks.
var addButton = document.getElementById("add-button");
var removeButton = document.getElementById("remove-button");
var incomeSection = document.getElementById("income");
var incomeRow = document.getElementById("income-row");
var itemCounter = 2
incomeSection.addEventListener("click", activateItem);
function activateItem(e) {
if (e.target.id == "add-button") {
incomeSection.innerHTML += '<div id="income-row"><input class="input" type="text" name="income-type-1" placeholder="Income source ' + itemCounter + '"><span class="currency">£</span><input class="input income-amount" type="text" name="income-amount-1" placeholder="Amount"><input id="remove-button" class="button" type="button" value="-"></div>';
itemCounter++;
}
if (e.target.id == "remove-button") {
incomeSection.removeChild(incomeRow);
}
}
html body {
background-color: #c9c9c9;
font-family: 'Montserrat', sans-serif;
color: #686868;
}
#income {
padding: 10px;
}
.input {
padding: 8px;
font-size: 14px;
margin-right: 10px;
margin-bottom: 5px;
width: 30%;
}
.button {
width: 25px;
height: 25px;
}
.currency {
padding: 10px;
font-size: 14px;
margin-right: -4px;
margin-bottom: 5px;
background-color: darkgray;
color: white;
}
<div id="income">
<div id="income-displayed">
<h2>Income: <span></span></h2>
</div>
<div id="income-row">
<input class="input" type="text" name="income-type-1" placeholder="Income source">
<span class="currency">£</span>
<input class="input income-amount" type="text" name="income-amount-1" placeholder="Amount">
<input id="add-button" class="button" type="button" value="+">
</div>
</div>
Just replace the following line it will resolved your issue :-
incomeSection.removeChild(incomeRow);
with the following
e.target.parentNode.remove();
var addButton = document.getElementById("add-button");
var removeButton = document.getElementById("remove-button");
var incomeSection = document.getElementById("income");
var incomeRow = document.getElementById("income-row");
var itemCounter = 2
incomeSection.addEventListener("click", activateItem);
function activateItem(e) {
if (e.target.id == "add-button") {
incomeSection.innerHTML += '<div id="income-row"><input class="input" type="text" name="income-type-1" placeholder="Income source '+itemCounter+'"><span class="currency">£</span><input class="input income-amount" type="text" name="income-amount-1" placeholder="Amount"><input id="remove-button" class="button" type="button" value="-"></div>'; itemCounter ++;
}
if (e.target.id == "remove-button") {
e.target.parentNode.remove();
}
}
html body {
background-color: #c9c9c9;
font-family: 'Montserrat', sans-serif;
color: #686868;
}
#income {
padding: 10px;
}
.input {
padding: 8px;
font-size: 14px;
margin-right: 10px;
margin-bottom: 5px;
width: 30%;
}
.button {
width: 25px;
height: 25px;
}
.currency {
padding: 10px;
font-size: 14px;
margin-right: -4px;
margin-bottom: 5px;
background-color: darkgray;
color: white;
}
<div id="income">
<div id="income-displayed"><h2>Income: <span></span></h2></div>
<div id="income-row">
<input class="input" type="text" name="income-type-1" placeholder="Income source"><span class="currency">£</span><input class="input income-amount" type="text" name="income-amount-1" placeholder="Amount"><input id="add-button" class="button" type="button" value="+"></div>
</div>
This Snippet demonstrates how to add and remove elements to and from the DOM utilizing:
cloneNode
.children
parentNode
Further details are commented in the source
SNIPPET
// #incFormA element will bind with eventListener
var form = document.getElementById("incFormA");
// #setA will contain the #dupes
var set = document.getElementById("setA");
// Reference to clone template #dupe
var dupe = document.getElementById('dupe');
// Increment counter that will ensure unique ids
var cntr = 0;
// If any part of the form is clicked call actDeact
form.addEventListener("click", actDeact);
/*
| actDeact()
| -If the clicked button's id === addA
| then clone #dupe and add an id (#dupe+cntr)
| -Iterate through it's children
| and assign unique ids and names to
| the 1st and 3rd children of (#dupe+cntr)
| -Append #dupe+cntr to #setA
*/
/*
| -If the clicked button was a .remA
| find it's parentNode and remove it.
*/
function actDeact(e) {
cntr++;
if (e.target.id === 'addA') {
var clone = dupe.cloneNode(true);
clone.id = 'dupe' + cntr;
var i;
var grp = clone.children;
var qty = grp.length;
for (i = 0; i < qty; i++) {
switch (i) {
case 0:
grp[0].id = 'inc' + cntr;
grp[0].name = 'inc' + cntr;
break;
case 2:
grp[2].id = 'amt' + cntr;
grp[2].name = 'amt' + cntr;
break;
default:
break;
}
}
setA.appendChild(clone);
} else if (e.target.className === "remA") {
var clone = e.target.parentNode;
setA.removeChild(clone);
} else return false;
}
html body {
background-color: #c9c9c9;
font-family: 'Montserrat', sans-serif;
color: #686868;
}
#setA {
padding: 10px;
}
/* The clone template is out of the way
| yet still accessible for cloning.
*/
#dupe {
display: none;
}
.input {
padding: 8px;
font-size: 14px;
margin-right: 10px;
margin-bottom: 5px;
width: 30%;
}
button {
width: 25px;
height: 25px;
float: right;
}
.currency {
padding: 10px;
font-size: 14px;
margin-right: -4px;
margin-bottom: 5px;
background-color: darkgray;
color: white;
}
/*
| This ruleset is for positioning #addA
*/
.block {
position: relative;
display: block;
min-height: 100%;
width: 20%;
left: 80%;
bottom: 15px;
}
<!--Use <form> to post collect and send data*-->
<form id='incFormA' name='incFormA'>
<fieldset id="setA">
<legend class="display">
<!--Use <output> to calculate and display data*-->
<h2>Income: <output id='outA'></output></h2>
</legend>
<div class='block'>
<!--One add <button>-->
<button id="addA" type='button'>+</button>
</div>
<!--#dupe is the group of elements kept as a clone template-->
<span id='dupe'>
<input id='inc' class="input" name="inc" type="text" placeholder="Income source">
<span class="currency">£</span>
<input id="amt" class="input" name="amt" type="text" placeholder="Amount">
<button class="remA">-</button>
</span>
</fieldset>
</form>
<!--*Choice of elements optional-->
I am working on a site, in which I had to add screen adjustments using scrollbars and I made it using this example. You can see the code below...
HTML CODE:
<h1>Image Editor with CSS Filters and jQuery</h1>
<!--Form for collecting image URL -->
<form id="urlBox" class="center">
<input class="url-box" type="url" id="imgUrl" placeholder="Paste any image link and start playing!">
<input id="go" type="button" value="Go">
</form>
<hr color="grey">
<!--Controls for CSS filters via range input-->
<div class="sliders">
<form id="imageEditor">
<p>
<label for="gs">Grayscale</label>
<input id="gs" name="gs" type="range" min="0" max="100" value="0">
</p>
<p>
<label for="blur">Blur</label>
<input id="blur" name="blur" type="range" min="0" max="10" value="0">
</p>
<p>
<label for="br">Exposure</label>
<input id="br" name="br" type="range" min="0" max="200" value="100">
</p>
<p>
<label for="ct">Contrast</label>
<input id="ct" name="ct" type="range" min="0" max="200" value="100">
</p>
<p>
<label for="huer">Hue Rotate</label>
<input id="huer" name="huer" type="range" min="0" max="360" value="0">
</p>
<p>
<label for="opacity">Opacity</label>
<input id="opacity" name="opacity" type="range" min="0" max="100" value="100">
</p>
<p>
<label for="invert">Invert</label>
<input id="invert" name="invert" type="range" min="0" max="100" value="0">
</p>
<p>
<label for="saturate">Saturate</label>
<input id="saturate" name="saturate" type="range" min="0" max="500" value="100">
</p>
<p>
<label for="sepia">Sepia</label>
<input id="sepia" name="sepia" type="range" min="0" max="100" value="0">
</p>
<input type="reset" form="imageEditor" id="reset" value="Reset" />
</form>
</div>
<!--container where image will be loaded-->
<div id="imageContainer" class="center">
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/123941/stadium.jpg">
</div>
<p class="p">Demo by Vikas Lalwani. See article.</p>
CSS CODE:
/* General styles for the page */
* {
margin: 0;
padding: 0;
}
body {
background-color: #D2D7D3;
font-family: monospace;
margin: 0 auto;
width: 960px;
}
h1 {
margin: 25px 0 25px 0;
font-size: 40px;
text-align: center;
}
hr {
margin: 20px 0;
}
form {
text-align: center;
}
/* Styles for URL box */
.url-box {
background-color: transparent;
display: inline-block;
height: 30px;
border: none;
border-bottom: 4px solid #b3b3b1;
padding: 0px 0px 0px 20px;
margin: 0px 0px;
width: 50%;
outline: none;
text-align: center;
font-size: 15px;
font-family: monospace;
font-weight: 100;
color: #000;
}
#go {
display: inline-block;
height: 50px;
width: 50px;
background-color: transparent;
padding: 0px;
border: 4px solid #b3b3b1;
border-radius: 50%;
box-shadow: none;
cursor: pointer;
outline: none;
text-align: center;
font-size: 20px;
font-family: monospace;
font-weight: 100;
color: #000;
}
/* Styles for image container*/
#imageContainer {
border: 2px solid grey;
border-radius: 10px;
padding: 5px;
width: 65%;
max-width: 600px;
float: left;
margin: 20px;
}
#imageContainer img {
border-radius: 10px;
width: 100%;
}
/* Styles for sliders*/
.sliders {
float: left;
border: 2px solid grey;
border-radius: 10px;
margin-top: 20px;
margin-bottom: 20px;
padding-left: 10px;
}
.sliders p {
margin: 18px 0;
vertical-align: middle;
}
.sliders label {
display: inline-block;
margin: 10px 0 0 0;
width: 100px;
font-size: 16px;
color: #22313F;
text-align: left;
vertical-align: middle;
}
.sliders input {
position: relative;
margin: 10px 20px 0 10px;
vertical-align: middle;
}
input[type=range] {
/*removes default webkit styles*/
-webkit-appearance: none;
/*fix for FF unable to apply focus style bug */
border-radius: 5px;
/*required for proper track sizing in FF*/
width: 150px;
}
input[type=range]::-webkit-slider-runnable-track {
width: 300px;
height: 7px;
background: #ABB7B7;
border: none;
border-radius: 3px;
}
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
border: none;
height: 20px;
width: 20px;
border-radius: 50%;
background: #4B77BE;
margin-top: -6px;
vertical-align: middle;
}
input[type=range]:focus {
outline: none;
}
input[type=range]:hover {
cursor: pointer;
}
#reset {
display: inline-block;
height: 40px;
width: 100px;
background-color: transparent;
padding: 0px;
border: 4px solid #b3b3b1;
border-radius: 10px;
box-shadow: none;
cursor: pointer;
outline: none;
text-align: center;
font-size: 20px;
font-family: monospace;
font-weight: 100;
color: #000;
margin: 0 0 10px 0;
}
.p {
clear: both;
text-align: center;
padding: 40px 0 40px;
}
JQUERY DODE:
//on click of go(submit) button, addImage() will be called
$("#go").click(addImage);
//on pressing return, addImage() will be called
$("#urlBox").submit(addImage);
// editing image via css properties
function editImage() {
var gs = $("#gs").val(); // grayscale
var blur = $("#blur").val(); // blur
var br = $("#br").val(); // brightness
var ct = $("#ct").val(); // contrast
var huer = $("#huer").val(); //hue-rotate
var opacity = $("#opacity").val(); //opacity
var invert = $("#invert").val(); //invert
var saturate = $("#saturate").val(); //saturate
var sepia = $("#sepia").val(); //sepia
$("#imageContainer img").css(
"filter", 'grayscale(' + gs+
'%) blur(' + blur +
'px) brightness(' + br +
'%) contrast(' + ct +
'%) hue-rotate(' + huer +
'deg) opacity(' + opacity +
'%) invert(' + invert +
'%) saturate(' + saturate +
'%) sepia(' + sepia + '%)'
);
$("#imageContainer img").css(
"-webkit-filter", 'grayscale(' + gs+
'%) blur(' + blur +
'px) brightness(' + br +
'%) contrast(' + ct +
'%) hue-rotate(' + huer +
'deg) opacity(' + opacity +
'%) invert(' + invert +
'%) saturate(' + saturate +
'%) sepia(' + sepia + '%)'
);
}
//When sliders change image will be updated via editImage() function
$("input[type=range]").change(editImage).mousemove(editImage);
// Reset sliders back to their original values on press of 'reset'
$('#imageEditor').on('reset', function () {
setTimeout(function() {
editImage();
}, 0);
});
// adding an image via url box
function addImage(e) {
var imgUrl = $("#imgUrl").val();
if (imgUrl.length) {
$("#imageContainer img").attr("src", imgUrl);
}
e.preventDefault();
}
What I can't aim, is to load, save or reset values of adjustments using a cookie and jquery!!! Any idea how can I do this?
EDIT
I need an example based on this part of code:
$(document).ready(function(){
function adjustments() {
var br = $("#br").val(); // brightness
var ct = $("#ct").val(); // contrast
var opacity = $("#opacity").val(); //opacity
var saturate = $("#saturate").val(); //saturate
$("#page-wrap, #preloader").css("filter", 'brightness(' + br +
'%) contrast(' + ct +
'%) opacity(' + opacity +
'%) saturate(' + saturate +
'%) ');
$("#page-wrap, #preloader").css("-webkit-filter", 'brightness(' + br +
'%) contrast(' + ct +
'%) opacity(' + opacity +
'%) saturate(' + saturate +
'%) ');
}
$("input[type=range]").change(adjustments).mousemove(adjustments);
$('#adjustments-form').on('reset', function () {setTimeout(function() {adjustments();},0);});
});
You can manage cookies (get, add,update, etc..) in your script using one of these two examples:
https://github.com/js-cookie/js-cookie
https://github.com/carhartl/jquery-cookie
Then simply:
Check for the cookie existence on page load:
If cookie is available then load properties,
If cookie don't exist - create a new cookie with the current properties.
An example (using jQuery cookie plugin)
Setting a cookie and storing some data:
// prepare and store data
var props = {
name:'John',
age:'31'
};
$.cookie('_storeProperties', JSON.stringify(props) );
Retrieve cookie and parse saved data:
var props = $.parseJSON( $.cookie('_storeProperties') );
// do something with the data..
Another approach (which I would prefer) would be using localStorage.
You can read a bit about localStorage in the following link:
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
EDIT ON OP REQUEST
This is not a complete code, just showing you how to utilize what I have explained on your own scenario, customize to fit your needs:
function adjustments() {
// creating an initial properties object
var props = {
br : $("#br").val(), // brightness
ct : $("#ct").val(), // contrast
opacity : $("#opacity").val(), //opacity
saturate : $("#saturate").val(), //saturate
};
// try to fetch stored properties from a cookie
var propsCookie = $.cookie('_storeProperties');
// we have previous settings stored
if(propsCookie){
// load them
props = $.parseJSON( propsCookie );
}else{
// no previous settings stored, lets store ours
$.cookie('_storeProperties', JSON.stringify(props) );
}
// use the props object as: props.br , props.ct, etc..
// your code
}
Hope it helps a bit!