JS reset function for 2 clipboards - javascript

Great day, I would like to ask for some advise please, im really new to html and css as well as java and putting all of them together is a bit hard for me so, i'm hoping for some advise.
I recently created a form, though i couldn't figure out how to reset all the function, like resetting the contain to its original form after im done copying it.
please the my codes and let me know what i can do. your help is greatly appreciated.
<html>
<head>
<style type="text/css">
/* Some Generic styles */
body {
text-align: center;
font-family: "Open Sans", Helvetica, Arial, sans-serif;
color: #023378;
line-height: 0.5;
background-color:#1E334F;
}
h1 {
margin: 0.5em auto 0.5em;
color: #71A4EB;
}
textarea,
button {
font-size: 1em;
font-family: "Open Sans", Helvetica, Arial, sans-serif;
}
textarea {
display: block;
margin: 0.5em auto 0.5em;
background: #CAD6E6;
resize: vertical;
}
[id="cleared"] {
margin-top: 4em;
}
textarea:focus {
border-color: #8fa423;
}
button {
position: relative;
padding: 8px 20px;
border: 0;
font-size: 0.835em;
text-transform: uppercase;
letter-spacing: 0.125em;
font-weight: bold;
color: #3F71B6;
background: #7DA9E6;
transition: background .275s;
}
button:hover,
button:focus {
background: #5275A5;
}
p {
margin-top: 3.25em;
font-size: .825em;
color: #777;
font-weight: bold;
letter-spacing: .01em
}
</style>
<h1>SH!N</h1>
<body>
<textarea id="to-copy" cols="80" rows="25" spellcheck="false">
SESA
Caller's Name:
Call back number:
Email Address:
Related case #s (case history):
Location, remote/hotel/office:
Application Name:
Number of Users Affected: Number of Users Affected: (Single User / Less than 5 users / 5 or more users)
What is the issue/problem:
When did the issue/problem begin:
Login id:
Error message (if any):
When was the last time it worked properly:
Have there been any changes to your PC since the last time it worked properly:
Have you changed your password recently:
Troubleshooting steps (detailed):
Additional Detail (links, screen shots etc.. :
</textarea><br>
<button id="copy" type="button">Copy<span class="copiedtext"aria-hidden="true"></span></button>
<textarea id="text" cols="80" rows="8" >
Resolution:
A - problem:
B - cause:
C - actions:
D - resolution:
</textarea><br>
<button onclick="copy()">Copy</button><br>
<SCRIPT TYPE="text/javascript">
var toCopy = document.getElementById( 'to-copy' ),
btnCopy = document.getElementById( 'copy' );
btnCopy.addEventListener( 'click', function(){
toCopy.select();
if ( document.execCommand( 'copy' ) ) {
btnCopy.classList.add( 'copied' );
var temp = setInterval( function(){
btnCopy.classList.remove( 'copied' );
clearInterval(temp);
}, 600 );
} else {
console.info( 'document.execCommand went wrong…' )
}
return false;
} );
function copy () {
var text = document.getElementById('text');
var range = document.createRange();
range.selectNode(text);
window.getSelection().addRange(range);
document.execCommand('copy');
}
</SCRIPT>
</body>
</html>

In order to make a form, you should not use textarea (or using it only as a part of a form, for instance to make a comment in a blog)
If you want to make a form, you must use form tag
<form id="myForm">Caller's name <input type="text" name="callerName"> ... </form>
https://www.w3schools.com/html/html_forms.asp
And then if you want to reset it, inside javascript :
document.getElementById("myForm").reset();
Your form does have id "myForm", you select this element and use reset() function on it which work on form.
PS: You should put your style in a CSS file and your script in a JS file.
EDIT :
If you want to copy it :
var myForm = document.getElementById('myForm');
var targetForm = document.getElementById('targetForm');
targetForm.innerHTML = myForm.innerHTML;
Offcourse you need to have a form tag with id set to targetForm.

Related

How can I anchor an image so text does not move it?

TLDR: How to prevent img from being repositioned when another element above is manipulated by JS.
I am in an introduction to coding course, and this week we were creating a calculator which would allow the user to input a number and receive a total cost based on this quantity (using shirts for an example). I wanted to add a .gif below this calculator, although the .gif is being shifted down when the total amount is displayed on the screen after the user submits their number.
There is already space between the input/button and the .gif below, but the text being added to the screen will move the .gif further down. I tried using a <br clear="top"> thinking that it may wrap the text from the top to stop interference, but that did not seem to work. I also tried position: absolute but that did not work either. Upon inputting an answer with the button, I have it written so var message = "Your total for "+v+" shirts is $"+total; document.querySelector("#paragraph-1").innerHTML = message; and this message is what is impacting the .gif. The image has automatic margins set on CSS img{ width: 50%; display: block; margin-left: auto; margin-right: auto;.
Here is a link for live editing: https://jsfiddle.net/6fom3syt/
Thank you for your time and I appreciate any feedback!
One easy way to solve it:
<p id="paragraph-1"> </p>
don't leave the p element empty.
There are several ways to do what you want, but the easiest is to use the position: absolute on the paragraph. By setting the position: relative to the paragraph container, when you use position: relative on the paragraph, the latter will refer directly to the container, adding bottom: -3rem to position it below the input and left and translate to center it, the result should be what you want.
var cost = 9.99;
var subtotal;
document.querySelector("#button-1").onclick = click
//console.log(document);
function click(){
var i = document.querySelector("#input-1");
var v = i.value;
console.log(typeof(v));
var subtotal = cost*v; //coercion
var total = addTax(subtotal);
total = total.toFixed(2);
var message = "Your total for "+v+" shirts is $"+total;
document.querySelector("#paragraph-1").innerHTML = message;
//console.log("button has been clicked", v, subtotal, total);
if(v==1){
var message2 = "Your total for "+v+" shirt is $"+total;
console.log(message2);
document.querySelector("#paragraph-1").innerHTML = message2
}
else{
console.log(message);
}
}
function addTax(num){
//var taxRate = 0.13;
//var taxAmount = num*taxRate;
//var total = num+taxAmount;
var tax = 1.13;
var total = num*tax;
//console.log(total);
return total
}
h1{
color: antiquewhite;
text-align: center;
font-family: 'Georgia', Times New Roman, Times, serif;
}
#container{
width: 70%;
margin: auto;
text-align: center;
position: relative;
}
#paragraph-1 {
position: absolute;
bottom: -2.5rem;
left: 50%;
transform: translateX(-50%);
}
body{
background-color: rgb(95, 147, 119);
font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
color: antiquewhite;
}
button{
background-color:rgb(95, 147, 119);
color: antiquewhite;
border-color: antiquewhite;
font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
cursor:pointer;
}
input{
background-color: rgb(95, 147, 119);
color:antiquewhite;
border-color:antiquewhite;
font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
}
img{
width: 50%;
display: block;
margin-left: auto;
margin-right: auto;
}
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" type = "text/css" href = "m3.css">
</head>
<body>
<div id = "container">
<h1 id= "mainHeading">module 3: functions</h1>
<h2>How many shirts would you like to buy?</h2>
<button id="button-1">submit</button>
<input id="input-1" type="number">
<p id="paragraph-1"></p>
</div>
<br clear="top">
<p><img src = https://media3.giphy.com/media/3o6Mb7jQurR1B7mM5G/giphy.gif>
</p>
<script src="m3.js"></script>
</body>
</html>
(You should still make it responsive or make the text not wrap, otherwise the space you used between the input and the image is not enough.)
One of the easies way is to handle by css. like has some minimum height so UI looks more good.
https://jsfiddle.net/6fom3syt/
#paragraph-1{
min-height:30px;
}

Change background colors dynamically using "input" event

I'm trying to make a background change dynamically using Javascript using event listeners that are listening to "input" on input type="color" fields.
When I click on the color input fields after I choose a color from the pallet, the background color changes properly. But, I'd like the background to change dynamically as the user scrolls the pallet, and not only when he chooses the final color. Hope I was clear, and thanks in advance!
/* Variables Caching */
var h3 = document.querySelector("h3");
var input_left = document.querySelector("#color_selector_1");
var input_right = document.querySelector("#color_selector_2");
/* Function Declerations */
function colorChange()
{
// edit body style accordingally
var newStyle = changeBodyStyle();
// edit h3
editH3(newStyle);
}
function editH3(new_body_style)
{
h3.textContent = "";
h3.textContent = new_body_style;
}
function changeBodyStyle()
{
var new_background = "linear-gradient(to right, " + input_left.value.toString() + ", " + input_right.value.toString() + ")";
document.body.style.background = new_background;
return new_background;
}
/* Adding Event Listeners */
input_left.addEventListener("input", colorChange);
input_right.addEventListener("input", colorChange);
body{
font: 'Raleway', sans-serif;
color: rgba(0,0,0,.5);
text-align: center;
text-transform: uppercase;
letter-spacing: .5em;
top: 15%;
background: linear-gradient(to right, red, yellow);
}
h1{
font: 600 3.5em 'Raleway' , sans-serif;
color: rgba(0,0,0,.5);
text-align: center;
text-transform: uppercase;
letter-spacing: .5em;
width: 100%;
}
h3 {
font: 900 1em 'Raleway' , sans-serif;
color: rgba(0,0,0,0.5);
text-align: center;
text-transform: none;
letter-spacing: 0.01em;
}
<!DOCTYPE html>
<html>
<head>
<title>Gradient Background</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Background Generator</h1>
<h2>Current CSS Background</h2>
<h3>
<h4>this is a test</h4>
</h3>
<input type="color" id="color_selector_1" value="#00ff00">
<input type="color" id="color_selector_2" value="#ff0000">
<!-- JavaScript -->
<script type="text/javascript" src="script.js">
</script>
</body>
</html>
You'll need to build your own color picker, or use a third-party one, rather than relying on the one built in to the browser. The one built in to the browser doesn't communicate the user's choice back to the page until the user clicks OK, so it's impossible to do what you want with it.

Save contentEditable into html file with javascript

How can I save contenteditable element with javascript(no PHP) into actual HTML code? So I can edit content whenever even in offline mode.
Like when you click "save button" it replace old file with new one(text with changes).
If there is a way to make this work in offline mode with any other programming lang please suggest.
I found a few examples but they were all made with PHP.
Also, I will post code. In this code, you are able to edit the file with javascript and save it. But problem is that it does not save into actual HTML code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<style type="text/css">
body{
font-family: "Dosis";
font-size: 1.3em;
line-height: 1.6em;
}
.headline{
font-size: 2em;
text-align: center;
}
#wrapper {
width: 600px;
background: #FFF;
padding: 1em;
margin: 1em auto;
box-shadow: 0 2px 5px rgba(0,0,0,0.3);
border-radius: 3px;
}
button {
border: none;
padding: 0.8em;
background: #F96;
border-radius: 3px;
color: white;
font-weight: bold;
margin: 0 0 1em;
}
button:hover, button:focus {
cursor: pointer;
outline: none;
}
#editor {
padding: 1em;
background: #E6E6E6;
border-radius: 3px;
}
</style>
<body>
<div id="wrapper">
<section>
<h1 class="headline">contentEditable Demonstration</h1>
<button id="editBtn" type="button">Edit Document</button>
<div id="editDocument">
<h1 id="title">A Nice Heading.</h1>
<p>Last Edited by <span id="author">Monty Shokeen</span>
</p>
<p id="content">You can change the heading, author name and this content itself. Click on Edit Document to start editing. At this point, you can edit this document and the changes will be saved in localStorage. However, once you reload the page your changes will be gone. To fix it we will have to retrieve the contents from localSotrage when the page reloads.</p>
</div>
</section>
</div>
<script>
var editBtn = document.getElementById('editBtn');
var editables = document.querySelectorAll('#title, #author, #content');
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem('title') !== null) {
editables[0].innerHTML = localStorage.getItem('title');
}
if (localStorage.getItem('author') !== null) {
editables[1].innerHTML = localStorage.getItem('author');
}
if (localStorage.getItem('content') !== null) {
editables[2].innerHTML = localStorage.getItem('content');
}
}
editBtn.addEventListener('click', function(e) {
if (!editables[0].isContentEditable) {
editables[0].contentEditable = 'true';
editables[1].contentEditable = 'true';
editables[2].contentEditable = 'true';
editBtn.innerHTML = 'Save Changes';
editBtn.style.backgroundColor = '#6F9';
} else {
// Disable Editing
editables[0].contentEditable = 'false';
editables[1].contentEditable = 'false';
editables[2].contentEditable = 'false';
// Change Button Text and Color
editBtn.innerHTML = 'Enable Editing';
editBtn.style.backgroundColor = '#F96';
// Save the data in localStorage
for (var i = 0; i < editables.length; i++) {
localStorage.setItem(editables[i].getAttribute('id'), editables[i].innerHTML);
}
}
});
</script>
</body>
</html>
You'll want to use something like the downloadInnerHtml function as described here. Ideally you'll probably also want to strip out the script tag and content editable attribute before exporting because you won't want the final html page to be editable

Find title/any tag of Ajax error.ResponseText from it's Html string or Converted jQuery Object

I want to hit a controller action by jQuery ajax and didn't make that action intentionally to show the error.
"
Server Error in '/' Application. The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its
dependencies) could have been removed, had its name changed, or is
temporarily unavailable. Please review the following URL and make
sure that it is spelled correctly. Requested URL:
/SoftwareCompany/HamdunSoft
"
As the above error is coming through the ajax error.responseText
error: function(error)
{
}
The full error.responseText is in the below code snippet.
"
<!DOCTYPE html>
<html>
<head>
<title>The resource cannot be found.</title>
<meta name="viewport" content="width=device-width" />
<style>
body {
font-family: "Verdana";
font-weight: normal;
font-size: .7em;
color: black;
}
p {
font-family: "Verdana";
font-weight: normal;
color: black;
margin-top: -5px
}
b {
font-family: "Verdana";
font-weight: bold;
color: black;
margin-top: -5px
}
H1 {
font-family: "Verdana";
font-weight: normal;
font-size: 18pt;
color: red
}
H2 {
font-family: "Verdana";
font-weight: normal;
font-size: 14pt;
color: maroon
}
pre {
font-family: "Consolas", "Lucida Console", Monospace;
font-size: 11pt;
margin: 0;
padding: 0.5em;
line-height: 14pt
}
.marker {
font-weight: bold;
color: black;
text-decoration: none;
}
.version {
color: gray;
}
.error {
margin-bottom: 10px;
}
.expandable {
text-decoration: underline;
font-weight: bold;
color: navy;
cursor: hand;
}
#media screen and (max-width: 639px) {
pre {
width: 440px;
overflow: auto;
white-space: pre-wrap;
word-wrap: break-word;
}
}
#media screen and (max-width: 479px) {
pre {
width: 280px;
}
}
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>The resource cannot be found.</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
<br><br>
<b> Requested URL: </b>/Chemical/DyeingPartList<br><br>
<hr width=100% size=1 color=silver>
<b>Version Information:</b> Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1038.0
</font>
</body>
</html>
<!--
[HttpException]: A public action method 'DyeingPartList' was not found on controller 'Menu.Controllers.ChemicalStore.ChemicalController'.
at System.Web.Mvc.Controller.HandleUnknownAction(String actionName)
at System.Web.Mvc.Controller.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->"
I have turned the string error.responseText into object element from this answer .
var element = $(error.responseText);
and the element is like this
As we can see there is an element named title in the object in red box at position 2 indexed 1. I can find it's(title tag) innerHtml by any one of the following
elem.get(1).innerHTML
elem.get(1).text
element[1].innerHTML
element[1].text
But I want to find this value by Jquery in the below way. Because in future for some cases I may required searching elements in object by property name rather than the index value. please help me if it is possible.
$("title", element).html()
$(element).find("title").html()
You can use $.parseHTML to convert html string to array of DOM nodes. Which can be used along with jquery selectors and function:
var dom_nodes = $($.parseHTML(e.responseText));
alert( dom_nodes.filter('title').text());
First, create a document from the string.
How to create Document objects with JavaScript
var doc = (new DOMParser).parseFromString(error.responseText, "text/html");
// first argument: html to be converted to doc
// second argument: mime_type (text/html or text/xml, it depends)
Second, you know the drill.
doc.querySelector("title").textContent;
// $(doc).find("title").html();
// The resource cannot be found.
Alternatively, use $.parseHTML and filter nodes.
var doc = $.parseHTML(error.responseText);
var titleNode = doc.filter(function (node) {
return node.localName === "title";
});
console.log(titleNode[0].textContent);

Credit cards types for jessepollak's JQuery.Card.js

I am using jquery.card.js from jessepollak. It is awesome.
If anyone has experience with it, could you please tell me if there is an option to choose what types of credit card you want to support?
e.g.
//This is how I would like it to be...
var card = new Card({
supportedCardTypes: 'Visa, Master'; //I don't want DC or AMEX etc...
});
Is there any options like that? How do I achieve it?
Thank you.
Answer ------------------------------------------------------------
Turns out, only changing cardTypes as TMan suggested didn't work. But it is not about the fish, it is about giving me the idea of fishing. Following TMan's idea hacking into the script, I found adding this line would work:
Card.prototype.handlers = {
setCardType: function($el, e) {
//my modification here to support only Visa and Master!!
var cardType = e.data === 'mastercard' || e.data === 'visa' ? e.data : 'unknown';
//end of my modification!!
if (!QJ.hasClass(this.$card, cardType)) {
QJ.removeClass(this.$card, 'jp-card-unknown');
QJ.removeClass(this.$card, this.cardTypes.join(' '));
QJ.addClass(this.$card, "jp-card-" + cardType);
QJ.toggleClass(this.$card, 'jp-card-identified', cardType !== 'unknown');
return this.cardType = cardType;
}
},
You can just hack the library source code, quick and dirty NOT the best idea, or do something to initialise the handlers your way in your own code.
Thanks again.
Great ideas all around. Here's a way to take your addition to the handler and override it without having to hack at the library. This will persist future changes much better.
var setCardTypeOrig = Card.prototype.handlers.setCardType;
Card.prototype.handlers.setCardType = function($el, e) {
var allowedCards = ['mastercard','visa'];
if (allowedCards.indexOf(e.data) < 0) e.data = 'unknown';
setCardTypeOrig.call(this, $el, e);
}
Demo in Stack Snippets
var setCardTypeOrig = Card.prototype.handlers.setCardType;
Card.prototype.handlers.setCardType = function($el, e) {
var allowedCards = ['mastercard','visa'];
if (allowedCards.indexOf(e.data) < 0) e.data = 'unknown';
setCardTypeOrig.call(this, $el, e);
}
var card = new Card({ form: '.form-container form', container: '.card-wrapper' })
.form-container {
margin-top: 20px;
}
.form-container input {
font-family: 'Helvetica Neue', Helvetica, Helvetica, Arial, sans-serif;
float: left;
}
.form-container input.col-6 {
width: 50%
}
.form-container input.col-3 {
width: 25%
}
.form-container input[type="text"] {
background-color: #fff;
border: 1px solid #cccccc;
font-size: 0.875rem;
margin: 0 0 1rem 0;
padding: 0.5rem;
height: 2.3125rem;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.form-container .button {
cursor: pointer;
position: relative;
text-decoration: none;
text-align: center;
font-size: 0.875rem;
margin: 0 0 1rem 0;
padding: 0.5rem;
height: 2.3125rem;
color: #fff;
background-color: #008CBA;
border-width: 0;
}
.form-container .button:hover,
.form-container .button:focus {
background-color: #007295;
}
<script src="https://rawgit.com/jessepollak/card/master/lib/js/card.js"></script>
<div class="demo-container">
<div class="card-wrapper"></div>
<div class="form-container">
<form action="">
<input placeholder="Card number" type="text" name="number" class="col-6"/>
<input placeholder="Full name" type="text" name="name" class="col-6"/>
<input placeholder="MM/YY" type="text" name="expiry" class="col-3"/>
<input placeholder="CVC" type="text" name="cvc" class="col-3"/>
<input type="submit" value="Submit" class="button col-6"/>
</form>
</div>
</div>
To test it, you can look at the card payment definitions:
mastercard (55*) - works ✓
visa (4*) - works ✓
amex (37*) - doesn't ✓
Based on the Coffeescript file, I think your best bet would be to fork the library and then remove the cards you don't want to support from the cardTypes array so that all other numbers would show up as undefined.
https://github.com/jessepollak/card/blob/master/src/coffee/card.coffee
Or the following line in card.js:
https://github.com/jessepollak/card/blob/master/lib/js/card.js#L1134
Card.prototype.cardTypes = ['jp-card-amex', 'jp-card-dankort', 'jp-card-dinersclub',
'jp-card-discover', 'jp-card-jcb', 'jp-card-laser', 'jp-card-maestro',
'jp-card-mastercard', 'jp-card-unionpay', 'jp-card-visa', 'jp-card-visaelectron'];
You'll also probably want to modify the cardTemplate variable to remove the DOM nodes that no longer apply:
https://github.com/jessepollak/card/blob/master/src/coffee/card.coffee#L36

Categories

Resources