Select and Copy input text onclick? - javascript

I've actually seen a few questions about this, most of them are from at least 5 or 6 years ago.
I want to have an input box:
<input id="copy-text" type="text" value="Click this text!">
Here's the JavaScript I've been trying to work with:
document.getElementById("copy-text").onclick = function() {
this.select();
execCommand('copy');
alert('This is a test...');
}
I know my code doesn't work. If I remove execCommand('copy'); then the alert() pops up, but it seems to be hitting an error at that line. I've tried making it this.execCommand('copy'); as well, not really sure what to do here.
Fiddle: https://jsfiddle.net/6v24k4sk/
The idea is that I want the user to click the input box, it will select all the text, and then copy it to the clipboard.
Any ideas?

You should put a document. in front of the execCommand.
document.getElementById("copy-text").onclick = function() {
this.select();
document.execCommand('copy');
alert('This is a test...');
}
Here you can find a working example:
https://jsfiddle.net/9q3c1k20/
edit:
The function also returns whether this functionality is supported in the browser. I think you should check the value, because execCommand still has no final specification and is therefore not guaranteed to work in all browsers.

Use this function with your copy_btn (without onclick function).
function function_name() {
var c = document.getElementById("copy");
c.select();
document.execCommand('copy');
}

Related

How were Chrome and other browsers able to initialize this JavaScript variable?

I'm working on a shopping cart that asks the user to check the box indicating they agree to the terms of service before they can "review order" and finally make the purchase.
I have to accomplish this with JavaScript by getting the element containing the "review order" and "continue shopping" buttons and changing the inner HTML to be what I need. I have to do it this way because the cart I am using does not give me full control over these elements in the cart source code.
Here is the code I originally came up with, which worked on Chrome, Edge, and other browsers, but not IE.
var x = document.getElementById('CHECKOUT_LINKS');
x.innerHTML = '<div class="checkoutLinksBottom"><input id="tosBox" type="checkbox" name="tosBox">I agree to the Terms of Service<br>Continue ShoppingReview Order</div>';
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#tosBox').addEventListener('change', changeHandler);
});
var checkbox = document.getElementById("tosBox");
checkbox.checked = true;
checkbox.checked = false;
function changeHandler() {
if (!tosBox.checked)
alert("You must agree to the Terms of Service");
}
function clicker() {
if (!tosBox.checked)
alert("You must agree to the Terms of Service");
else { // Go to review order page
}
}
As you can see the CHECKOUT_LINKS element's inner HTML is changed to what I need on the fly as the page loads. The primary point is to add the id="tosBox" element, then capture the click on id="reviewOrderButton" element and filter it though the simple JS functions changeHandler() and clicker().
In IE developer tools, the console reports 'tosBox' is undefined when I click on id="reviewOrderButton" element. This makes sense when looking at var checkbox = document.getElementById("tosBox"); the variable created is called checkbox, but the variable I try to use later is called tosBox. I simply changed checkbox to tosBox and then everything worked on IE as well.
What's shocking to me is that the original code worked on Chrome and Edge. How did it work? Should I expect it to work and IE is faulting?

Meteor App get value of textarea in form

I am writing a little Meteor app. There is a textarea in a form, which looks like this:
<form name="comments-form">
<label for="textarea">Comment:</label><br>
<textarea cols="40" rows="10" name="comment_textarea" class="comment_textarea">Write your comment here.</textarea><br>
<button class="btn btn-success js-add-comment">add comment</button>
</form>
In my client.js I have the following code for accessing the value of the textarea:
EVENT_HANDLED = false;
Template.website_item_details.events({
"click .js-add-comment": function(event) {
var comment_text = event.target.comment_textarea.value;
if(Meteor.user()) {
Comments.insert({
created_by: Meteor.user()._id,
text: comment_text,
website_id: this._id
});
}
return EVENT_HANDLED;
}
});
However, when I click the button to add the comment, I get the following console output:
TypeError: event.target.comment_textarea is undefined
["click .js-add-comment"]()
client.js:103
Template.prototype.events/eventMap2[k]</</<()
blaze.js:3697
Template._withTemplateInstanceFunc()
blaze.js:3671
Template.prototype.events/eventMap2[k]</<()
blaze.js:3696
attached_eventMaps/</</</<()
blaze.js:2557
Blaze._withCurrentView()
blaze.js:2211
attached_eventMaps/</</<()
blaze.js:2556
HandlerRec/this.delegatedHandler</<()
blaze.js:833
jQuery.event.dispatch()
jquery.js:4690
jQuery.event.add/elemData.handle()
This seems to be basic form handling, but somehow I can't get that text in the textarea into a variable in my javascript code. I've already tried a multitude of variants of accessing it:
document.getElementsByClass()[0].value
$('.comment_textarea').get(0).val() // there should only be one such text area anyway
event.target.comment_textarea.value;
But none of those work for me, I always get that error. It's almost like the textarea was not part of my html or there is a bug in Meteor, which prevents me from accessing textareas.
I also checked whether there are other things named comment_textarea with a fulltext search on all of my projects clientside files, but there isn't any other.
Am I simply blind and overlooking something? How do I get that text?
What's more is, that although I return false, the browser still reloads the page. Could it be related to the error happening before?
You are using the click event of the button and on that event, the textarea is not available. You need to change the event into submit form. First, put the id into your form, change the button into type submit and change the code into
"submit #your-form-id": function(event) {
event.preventDefault();
var comment_text = event.target.comment_textarea.value;
.....
}
After trying even more desperate ways to access that textarea, I think I know now what's wrong:
// var comment_text = event.target.comment_textarea.value;
// var comment_text = document.getElementByName('comment_textarea').value;
// var comment_text = document.getElementByTagName('textarea')[0].value;
// var comment_text = $('textarea').get(0).val();
// var comment_text = $('textarea').get(0).text();
var comment_text = $('textarea').get(0).value; // finally working!
So it seems that when I use jQuery, I can't use the .val() function as stated in my other answers to many other questions, but for some reason I have to treat it like a normal DOM object and use the attribute value instead of the function .val().
Maybe it's specific to the jQuery version in my Meteor app?
So I will test the following:
var comment_text = $('textarea.comment_textarea').get(0).value;
...
Yes, that also works.
Also it fixes the reload issue. I guess since there was an error, it didn't even get to return false and this is why the website reloaded.

replacing focused span by input with focus

This question gives more details about context and motivation. Notice that I am on Linux and cares only about recent Firefox (at least 38) & Chrome.
Basically, I want to edit some AST interactively with a web interface.
In the MELT monitor on github commit 7b869102332bd29309 I would like to have a focusable <span> (which has tabindex='0' so can get focus) which, when I press the spacebar, is replaced by some <input type='text'/> which has already the focus...
I am not using contenteditable anymore, see this, because it looks that contenteditable is really messy (and don't work as well as I want)!
I've made a jsfiddle containing a simple example with:
<div id='mydiv_id'>
*before* <span id='myspan_id' tabindex='0'>in span</span> !after!
</div>
and the JQuery 2 code:
var $mydiv = null;
var $myspan = null;
$(document).ready(function() {
$myspan = $('#myspan_id');
$mydiv = $('#mydiv_id');
console.log (" mydiv=", $mydiv, " myspan=", $myspan);
$myspan.on("keypress", function (ev) {
console.log ("myspan keypress ev=", ev);
if (ev.keyCode === 32 || ev.key === ' ') {
console.log ("myspan got space ev=", ev);
var myinput =
$("<input type='text' id='myinput_id' width='16' class='myinp_cl'/>");
$myspan.replaceWith(myinput);
myinput.focus();
console.log ("myspan replaced with myinput=", myinput);
}
});
console.log (" mydiv=", $mydiv, " myspan=", $myspan);
});
but it does not work as expected.
Or perhaps a focused <span> element cannot be replaced (on space keypress) with a focused <input> element?
(in the MELT monitor, I'm using jquery 2.1.4 embedded inside)
addenda
the updated jsfiddle works (sorry for my mistake, it needs jquery 2.1.4, with which it is working -and I regret having asked the question here), and since the Javascript of the MELT monitor is AJAX generated, I am not seeing every error in the console (see this question).
NB: In commit df3bdf3984bc202f I now have a case when, after programmatically moving the focus to a newly created <input>, $(':focus') is an empty object, and document.activeElement is the <body> itself....
I am now tempted to delete this question, it is probably useless...
As i saw your fiddle, what i noticed:
You are using .on() method.
.on() is not introduced in jQuery version 1.6.x but 1.7+.
So you can change to this:
$myspan.keypress(function (ev) {
Updated fiddle.
cares only about recent Firefox (at least 38) & Chrome.
So, best to upgrade the jQuery version to latest one as possible and take the version 2.x tree.
You can bind focus event on the span like this:
var $mydiv = null;
var $myspan = null;
$(document).ready(function() {
$myspan = $('#myspan_id');
$mydiv = $('#mydiv_id');
$myspan.on('focus', function() { var myinput =
$("<input type='text' id='myinput_id' width='16' class='myinp_cl'/>");
$myspan.replaceWith(myinput);
myinput.focus();
});
});
Demo:
http://jsfiddle.net/wLf0e3cs/

Javascript form.submit() not working in Firefox

There are several questions/answers on this here, here and here and elsewhere, but they all seem JQuery specific and do not appear to apply to this (for example, I am NOT creating a new Form object, this is an existing form in the document. Also I am NOT using Jquery at all).
I have a form which has to be modified before submission for reasons of IE7 compatibility. I have to strip out all the BUTTON tags from my form and then add a hidden field, but this is all in an existing form on the existing HTML page. This code works properly in IE and Chrome but doesn't work in Firefox (versions 23 & 24 both tested).
buttonClickFunction(formName, buttonObject) {
var formObject = document.forms[formName];
var i = 0;
// Strip out BUTTON objects
for (i=0;i<formObject.length;i++) {
if (formObject[i].tagName === 'BUTTON') {
formObject[i].parentNode.removeChild(formObject[i]);
i--;
}
}
// Create new field
var newField = document.createElement('input');
newField.type = 'hidden';
newField.id=buttonObject.id;
newField.name = buttonObject.name;
if (buttonObject.attributes['value'] != null) {
newField.value = buttonObject.attributes['value'].value;
} else {
newField.value = buttonObject.value;
}
// Submit form
formObject.appendChild(newField);
document.forms[formName].appendChild(newField);
document.forms[formName].submit();
}
In addition to the document.forms[formName].submit() I have also tried formObject.submit() - both work in Chrome but both fail in Firefox. I'm at a loss as to why this doesn't work - I've traced through the JS and watched that document.forms[formName].submit() execute - no exception appears but nothing goes to the server.
Can anyone identify why Firefox won't submit this form, and how I can fix it?
Firefox expects that, when you submit a form, you have at least a submit button available, meaning there should be something like:
<button type="submit">Click me</button>
or:
<input type="submit" value="Click me" />
When you use the first one in your code, it will not work (because you strip out all buttons before submitting the form). When you use the second option, it will work, also in Firefox. As you can see in this fiddle: http://jsfiddle.net/q9Dzc/1/
I had similar behaviour, when form.submit() didn't work on Firefox, but worked on other browsers. Just make sure that all the buttons within form contain type="button".
For anyone having an issue with making the Firefox submit with the page location changing / reloading afterwards, you need to put your redirect code in the $.post callback:
$(".form").submit(function(e){
e.preventDefault();
$.post("submit.php", {data: textData}, function(){
history.go(-1);
});
return false;
});
If your form has a mixture set of "input [type=button]" and "button", the JavaScript of submit() will not work for "input [type=button]" sometimes.

jQuery focus() sometimes not working in IE8

I am developing webapp using jQuery.
I have functionality that adds new row of 3 input fields. After creating these DOM elements I want to focus one of input fields. I am doing it with calling jQuery focus() function on necessary input field.
Problem is that calling focus() works fine in IE6 and FF3.5, but not working in IE8.
I was trying to make simple working example of this problem for showing it here, but with stripped version of code focus() is working fine. So my guess was that DOM is not ready yet when I call focus() in IE8. For this I tried calling setTimeout('myFocus()',400). I had success and in some of cases focus was really working but still not always. Randomly it does not focus my input field.
Question is: Has anybody faced similar problems and does anybody have any idea how to workaround it? Using setTimeout feels like very ugly workaround.
Tnx in advance
Edited : 26.08.2009
Succeeded to reproduce on simple example. Here is HTML+JS code that reproduces this bug on IE8.
<html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
function performChanged() {
formChanged = true;
}
function handleChange() {
var parentDiv = $('#container');
newValue = $(html).html();
parentDiv.html(newValue);
$(".sel1",parentDiv).bind('change',handleChange);
//alert('Uncomment this and after alert focus will be on input');
$("input.cv_values",parentDiv).focus();
}
$(document).ready(function() {
$('.trackChange').bind('change', handleChange);
});
var html = '<div class=\"div1\">\n<select class=\"sel1\" id=\"sel1\" name=\"sel1\"><option value=\"\"><\/option>\n<option value=\"11\">Select me to see problem<\/option>\n<\/select>\n\n\n<input class=\"cv_values\" id=\"sel3\" name=\"sel3\" size=\"30\" type=\"text\" value=\"\" /><br/>Focus should in input field. With alert it is but without alert focus is not there</div>';
</script>
</head>
<body>
<select class="trackChange" onchange='performChanged();'>
<option value=""></option>
<option value="1" >Select me to generate new inputs</option>
</select>
<div id="container"></div>
</body>
To reproduce:
1) select value from first dropdown. You will see that first time input is working
2) select value from second dropdown. You will see that bug is reproduced.
Then in code you can comment out line where it shows JS alert(). Strange thing is that if there is this alert() then after it focus is working fine.
Hope this helps to understand where my problem is.
P.S. I need my app to work this way - it is regenerating those inputs after selecting value from dropdown. This is simplified example of my app ;).
I had a similar problem with my app, but I can't reproduce the focus problem with your code. My problem was slightly different in that my page had a link hash that made IE not give my element focus.
Anyway, to get around the problem I added a timeout:
setTimeout(function () {
$('.my-thing').focus();
}, 100);
Not noticeable by a user but it gives IE a moment to breathe.
In conjunction with Kazys's solution, I found this to fix all my problems (using IE8 & .HTA files):
$("elem").blur();
$("elem").focus().focus();
I have no idea why, but somehow calling focus twice helps IE along.
EDIT:
I have found that calling .show() and .select() can also help.
Strangely i had the same problem and resolved it using plain old javascript like so:
document.getElementById('friend_name').focus();
Using jQuery equivalent $('#friend_name').focus(); didn't work in IE8 :-/
Had similar problem with IE8. I wanted to focus input in dialog when it is opened. Used autoOpen = false. Noticed that focus doesn't work only for first focusable element in dialog. Tried setTimeout but it worked only sometimes. Blurring element before focusing helped me.
$('#dialog').find('#name').blur();
$('#dialog').find('#name').focus();
Since you have not posted any code are you using:
$(document).ready(function(){
//code here
});
This will make javascript run after the html is loaded.
And you should use live events also. When your adding inputs to the dom the will automatically have focus binded to them.
$("p").live("focus", function(){
alert( $(this).text() );
});
This means that every p that is created will have a focus binded to it.
This is the best solution for the moment to set focus:
$('.elt').fadeIn(200, function() {$('.elt').focus();});
This is an old question, but it is top in search, so wanted to update.
I don't know if there was ever a time that it was fixed, but I ran into this issue again today in IE11, using jquery-2.1.3. I found that wrapping the focus call in a setTimeout, as set out by Ponny above, worked best for me.
I did need to increase the timeout in some cases, to get it to work.

Categories

Resources