I'm trying to create a copy to clipboard IE javascript function but my code isn't working. How should I format my parameters and pass the argument?
/*invisible storage*/
<textarea id="storageBox" STYLE="display:none;">
</textarea>
<p id="abc">I WANT TO COPY THIS TEXT</p>
<button onClick="Copy(abc);">Copy</button><br />
<script type="text/javascript">
function Copy(txt) {
storageBox.innerText = txt.innerText;
Copied = storageBox.createTextRange();
Copied.execCommand("RemoveFormat");
Copied.execCommand("Copy");
}
</script>
Major karma for anyone who can write this using zclip or show me a similar example as well!!
The following changes should help:
... onclick="Copy('abc');"...
storageBox.value = document.getElementById(txt).innerText
I think. You weren't very specific in saying what doesn't work or even for what reason you're trying to hijack the clipboard (what if the user has important stuff in there?)
First, you need to pass the parameter as a string:
<button onClick="Copy('abc');">Copy</button><br />
In your function, you need to get the element from the DOM based on this ID (as a string):
function Copy(txt) {
storageBox.innerText = document.getElementById(txt).innerText;
...
Though I commented your script working fine, there is something to fix in the HTML. If you set display: none, execCommand() can't copy the content. So you'll need to do this:
<textarea id="storageBox" style="width: 0px; height: 0px; border: 0px;"></textarea>
Related
I have seen many questions like this one, but my question is slightly different.
I wrote an HTML code that can execute another HTML code inside a <div>. The page looks like this:
The code of this page is this:
<html>
<meta name="viewport" content="width=device-width"/>
<style>
html, body{margin: 0; padding: 0;}
textarea {width:100%; height: 28%;}
div {display: block; width: 100%;}
</style>
<body onload="loadData()" onbeforeunload="storeData()" onunload="this.onbeforeunload()">
<div style="overflow: auto;">
<textarea id="code"></textarea>
</div>
<div>
<button onclick="run()" style="float: left;">Run</button>
<button onclick="setSize()" style="float: right;">Set size</button>
<input type="number" id="size" style="float: right; text-align: right;"/>
</div>
<div id="result" style="overflow: auto; height: 70%; border-top: 2px solid black;"></div>
</body>
<script>
const editor=document.getElementById('code');
function run()
{
var res=document.getElementById('result');
var input=editor.value;
res.innerHTML=input;
}
function setSize()
{
editor.style.fontSize=document.getElementById("size").value;
document.getElementsByTagName("button")[0].style.fontSize=document.getElementById("size").value;
document.getElementsByTagName("button")[1].style.fontSize=document.getElementById("size").value;
document.getElementsByTagName("input")[0].style.fontSize=document.getElementById("size").value;
}
function storeData()
{
var data=document.getElementById("code").value;
var txtSize=document.getElementById("size").value;
localStorage.setItem("stored", data);
localStorage.setItem("size", txtSize);
}
function loadData()
{
var data=localStorage.getItem("stored");
var txtSize=localStorage.getItem("size");
document.getElementById("code").value=data;
document.getElementById("size").value=txtSize;
editor.style.fontSize=txtSize;
document.getElementsByTagName("button")[0].style.fontSize=document.getElementById("size").value;
document.getElementsByTagName("button")[1].style.fontSize=document.getElementById("size").value;
document.getElementsByTagName("input")[0].style.fontSize=document.getElementById("size").value;
}
</script>
</html>
It is working absolutely correct, except one thing. The problem is that, if a <button> is created and the onclick attribute has this code: document.write('Some text');, then the whole page gets cleared. See these screenshots:
So, can you tell any way by which I can ensure that no changes can be done to the original page?
Please help a class 10 student.
Instead of having 'result' as a regular div element, which is meant to represent a section of the actual page, what you want here is to embed a whole separate page/context, which is something that iframe is used for.
I managed to accomplish what you wanted by replacing the div with an iframe, and the first line in the 'run' method with this:
var res=document.getElementById('result').contentDocument.body;
See this fiddle for an example.
The problem is that, if a is created and the onclick attribute has this code: document.write('Some text');, then the whole page gets cleared.
That is exactly what is supposed to happen when document.write() is called. That function always replaces the entire page with whatever is in the quotes.
The solution is to simply never call that method. If there is some reason why you want to call document.write, you need to explain what that is in your question so we can suggest an appropriate alternative.
I have a page, showlist.php, which loads a set of results from a recordset. There is a search field which returns results using jquery load. This works fine for one word, but not if there is more than one word in the search query. Can anybody show how to get this to work for any search query? Must be some basic error but googling around has not helped.
Key elements of showlist.php:-
<div id="contentarea">
<script type="text/javascript">
function contentloader(url){
$("#contentarea").load(url);
}
</script>
<input name="search" type="text" id="inputsearch"/>
<a onclick="contentloader('showlist.php?search='+document.getElementById('inputsearch').value+'')">Search</a>
</div>
You need to HTML encode the result of document.getElementById('inputsearch').value so that all the works are passes to the server.
See:
HTML-encoding lost when attribute read from input field
Encode URL in JavaScript?
and links therein.
You need to call encodeURIComponent with the value to correctly format the query/search term:
<a onclick="contentloader('showlist.php?search='+encodeURIComponent(document.getElementById('inputsearch').value)+'')">Search</a>
See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.
type abc%20xyz in the box. if that works, maybe you need to urlencode the value.
You can use onClick listener, since you are already using jQuery. I think it is a better than using onClick attribute.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<div id="contentarea">
<input name="search" type="text" id="inputsearch"/>
<a id="search">Search</a>
<script type="text/javascript">
$( document ).ready(function (){ // when document ready
$("#search").click(function(){ // add a click listner
$("#contentarea").load(
encodeURI($('#inputsearch').val()) // encode input string
);
}
);
})
</script>
</div>
I am trying to check if fields are blank or not, but it always throws this error:
TypeError: document.getElementById(...) is null
Here is the code: http://pastebin.com/v8mDwG2i
I am using jQuery UI and jQuery. Mine problem is that it always throws null and breaks on that line.
You get that error because in the JS you check for an ID, but in the HTML you have no id tag supplied, only a name tag.
I changed the name="..." for every input-element to id="...".
But there were some other errors in your code as well. Below is a working code snippet with all those error fixed, and an explanation as to what I have changed:
JS, CSS, HTML:
$(window).on('load',function(){
$("#submitBtn").hide();
$("#logStat").hide();
$('#preCheckBtn').click(function(){
$("#logStat").fadeIn(200);
$("#progBar").progressbar();
$("#progBar").progressbar("value", 0);
$("#writeThis").html("Verifying name...");
if ($("#nameIn").val() == (null||"")) {
$("#writeThis").html("ERROR: Name is empty.");
setTimeout(function(){$("#logStat").fadeOut(200);},2000);
return;
}
$("#progBar").progressbar("value", 25);
$("#writeThis").html("Verifying ID...");
if ($("#idIn").val()==(null||"") || isNaN($("#idIn").val())) {
$("#writeThis").html("ERROR: ID is empty or has wrong format.");
setTimeout(function(){$("#logStat").fadeOut(200);},2000);
return;
}
$("#progBar").progressbar("value", 50);
$("#writeThis").html("Verifying phone number...");
if ($("#phoneIn").val()==(null||"") || isNaN($("#phoneIn").val())) {
$("#writeThis").html("ERROR: Phone Number is empty or has wrong format.");
setTimeout(function(){$("#logStat").fadeOut(200);},2000);
return;
}
$("#progBar").progressbar("value", 75);
$("#writeThis").html("Locking data...");
$("#nameIn").attr("disabled", true);
$("#idIn").attr("disabled", true);
$("#phoneIn").attr("disabled", true);
$("#submitBtn").show();
$("#progBar").progressbar("value", 100);
$("#writeThis").html("Done!");
setTimeout(function(){$("#logStat").fadeOut(200);},1000);
});
});
body{
font-family: sans-serif;
width: 1020px;
margin: 25px auto;
}
#logStat{
margin: auto;
text-align: center;
padding: 10px;
width: 60%;
border-radius: 5px;
background-color: #B3B3B3;
}
<link href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.0/jquery-ui.min.js"></script>
<body>
<form action="data/scripts/submit_form.php" method="post">
<input type="text" placeholder="Name" id="nameIn" required /><br />
<input type="text" placeholder="ID" id="idIn" required /><br />
<input type="text" placeholder="Phone number" id="phoneIn" maxlength="10" required /><br />
<input type="submit" value="Run PHP" id="submitBtn" />
</form>
<button id="preCheckBtn">Pre-check data</button>
<div id="logStat">
<div id="progBar"></div>
<p id="writeThis"></p>
</div>
</body>
(fiddle: http://jsfiddle.net/sdbhu7yL/8/)
In the second and third if-clause you only check the input-element itself, not it's value. I think you probably just forgot the .value, so I changed it to check the value.
In those same if-clauses, isNaN(checkData) gives an error because checkData is never declared, it's undefined. I changed it to isNaN($("#someID").val()) to check the value directly.
In all your if-clauses, I changed ==null into ==(null||""). Otherwise, if you click the pre-check-button while one or more of the input fields are still empty, they all get disabled anyway, and you can't fill in the empty fields anymore. (I'm not so sure if disabling them is such a good idea in the first place, because a user might make a mistake filling them in, and then he/she can't correct it anymore.)
I put the CSS and JS in separate files. This is good practice: keep different kinds of code separated. (In the code snippet and jsfiddle they are just in separate sub-windows, but on your actual site you need to link to the CSS and JS files - just like you link to the jQuery '.js' and '.css' files.)
I removed the loaded() function. The whole idea of jQuery's document.ready and window.load is to replace the normal JavaScript's window.onload.
What you are doing is this: on page load you call a function loaded() (from inside your HTML body), and inside that function you check for document.ready. That is very redundant.
Plus, document.ready is called before window.load, so putting document.ready inside the function that is called on load, has no use whatsoever. Actually, the first two .hide() lines weren't even executed; the submitBtn and logStat remained visible, because you checked for document.ready after window.load, but document.ready won't fire anymore because it already happened before window.load.
(I recommend always using window.load btw, unless there is a specific need for document.ready.)
I put window.load around the whole code, not just the first two .hide() lines. This is how window.load should preferably be used.
I removed the type="button" from your pre-check-button in HTML. type="button" is only used on input elements to classify it as a button (because there are more input types). If you already use a dedicated <button> element, you don't need the type="button" anymore.
I gave the pre-check-button an ID and moved the onclick-binding to jQuery: $('#preCheckBtn').click(function(){ ...});. It is cleaner to have all your JS related code inside the JS file. Read about it here.
I translated all your regular JavaScript to jQuery (e.g. document.getElementById("someID").innerHTML = ...; to $('#someID').html(...);.
I added $("#submitBtn").show(); at the end, I think you probably just forgot to add it (I'm assuming you want that button to show when all if-clauses are passed).
I changed your "ERROR: ID is NULL." messages to a more user friendly text, because that NULL-error message also displays when you type in text (instead of numbers), which makes the message incorrect. (This is more of a design issue of course, feel free to hate me for it.)
I have a situation with sample code as follows:
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<p>
<h1>The header</h1>
<div>
matter ia always matter matter ia <strong>bold matter</strong> matter matter <em>italics matter</em>matter ia <em><strong>bold italics matter</strong></em>lways matter
</div>
</p>
</body>
</html>
I am just trying to retrieve the specific tags like body->p->div->em->strong when I click on "bold italics matter" using jQuery. Is there any standard method to retrieve as per the click event?
If you wan to get the tag name of the element which is clicked, then you can use:
$('*').click(function(e) {
e.stopPropagation();
console.log($(this).prop('tagName'));
});
Fiddle Demo
I'm not completely sure about what you are trying to accomplish. If you are trying to retrieve the tag itself that the text is contained in, i would recommend that you put a <span> tag in around the the text in question and do an onclick="function()" or simply put the onclick right on the <strong> tag.
As far the the JQuery/Javascript goes, if you want to retrieve the content, it looks like
var foo = document.getElementById.innerHTMl("id");
However, this requires you to have an id in your tags which is probably the best, if not
'standard' method of retrieving the content that is within the tag.
After reading your comments, i am editing this post:
The best way to get the parent elements is to use the JQUery .parent() function. I'd imagine that you would just recursively state something like this:
var foo = $("nameofelement").parent();
I hope this is more of what your looking for.
Thanks for contributing everybody. At last I made it myself with the following code.
$(document.body).click(function(e){
var Tags=[], Target=e.target, stat_msg="";
Tags.push(Target.tagName);
while($(Target).parent().get(0).tagName!=="BODY")
{
Tags.push($(Target).parent().get(0).tagName);
Target=$(Target).parent();
}
Tags.push("BODY");
for(i=Tags.length;i>0;i--)
stat_msg=stat_msg+Tags[i-1]+" ";
alert(stat_msg);
});
I'm at my first hackathon and trying to finish my project. I am very very new the javascript... everything I know I literally learned in the last 2 hours. That being said...
So I know that eval is not the greatest thing to use, but I'm trying to write a simple program in which you can input a javascript snippet into a textarea, click an execute button, and have the javascript execute inside another textarea. I'm trying to stay away from jquery for now, because I want to get the really basic idea down before I add another level of complexity, which is why I'm not using id's.... but if jquery is the only way to do this, then I guess I'll have to pony up and learn it in the next 8 hours.
Code as follows (ish):
function executeJS ()
{
var result = eval(game.input.value);
game.execute.value=result;
}
<head>
<body>
<H1>PRogram</H1>
<form name="game">
<textarea name="execute" rows="5" cols="30" value=""></textarea><br>
<textarea type="text" name="input" rows="10" cols="30" value=""></textarea>
<input type = "button" value = "guess" onclick = "executeJS()</input>
</form>
</body>
</head>
I'm not getting an output in my execute box.
Any insight would be much appreciated.
"game" isn't a variable. it's a DOM element name.
if you want to get it's object, give it an id let's say "game", and use document.getElementById('game')
Note that your <head> surround the <body>
Your javascript code isn't inside <script></script tag.
Here is a working version. However, I would reconsider your idea of not using IDs or libraries:
function executeJS() {
var game = document.forms['game'];
var result = eval(game.input.value);
game.execute.value = result;
}
And be wary of eval.