I want to add text to textarea when user clicks a button. I have used the code bellow :
<script>
document.addEventListener('DOMContentLoaded', start, false);
function start(){
document.getElementById("button0").addEventListener("click", function(){
addText(this);
});
function addText(elem) {
document.getElementById("transcript").innerHTML += elem.value;
}
};
</script>
When the users click the button the text added to the textarea but the moment they type using their keyboard they won't be able to add the text using the button anymore.
use .value not .innerHTML.
.innerHTML overwrites the markup of the element, not just the text. Since it's a form element you should be manipulating its value only.
document.getElementById("button0").addEventListener("click", function() {
document.getElementById("transcript").value += "huh";
});
#transcript {
height: 100px;
}
<button id="button0">Click Me</button>
<textarea id="transcript"></textarea>
Related
I am looking for the simplest possible solution to copy text within a html p tag on an image click to the clipboard.
I tried some small (code wise) solutions from this thread Click button copy to clipboard using jQuery, but it just won't copy the text. In my case I need it to work with an image click rather than a button click.
$("#clipboardImage").click(function() {
$("#didText").select();
document.execCommand("copy");
alert("Text copied")
});
#didText {
color: #1816A9;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<div id="didContainer">
<p id="didText" type="text">I hopefully end up in the form field anytime soon!</p>
<img id="clipboardImage" src="" alt="Click me, to bring him down!">
</div>
<br>
<form>
Worked?
<input type="text" name="copied Text">
</form>
</html>
If I understand well your goal is to put the text from the p tag into the input field.
Just select the text with JQuery .text() and put it into the input filed as a value
EDIT
So, if the main goal is to put some text from an element to the clipboard I suggest to use a dedicated function, there's a workaround that create an invisible and readonly textarea and use it as a "proxy" to store and copy the text to your clipboard.
NB: to avoid passing the text to the input field just get rid of $("input").val(text); row.
function copyToClipboard (str) {
var el = document.createElement('textarea'); // Create a <textarea> element
el.value = str; // Set its value to the string that you want copied
el.setAttribute('readonly', ''); // Make it readonly to be tamper-proof
el.style.position = 'absolute';
el.style.left = '-9999px'; // Move outside the screen to make it invisible
document.body.appendChild(el); // Append the <textarea> element to the HTML document
var selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; // Mark as false to know no selection existed before
el.select(); // Select the <textarea> content
document.execCommand('copy'); // Copy - only works as a result of a user action (e.g. click events)
document.body.removeChild(el); // Remove the <textarea> element
if (selected) { // If a selection existed before copying
document.getSelection().removeAllRanges(); // Unselect everything on the HTML document
document.getSelection().addRange(selected); // Restore the original selection
}
};
$("#clipboardImage").click(function() {
var didText = $("#didText");
var text = didText.text();
copyToClipboard(text);
$("input").val(text);
alert("Text copied")
});
#didText {
color: #1816A9;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<div id="didContainer">
<p id="didText" type="text">I hopefully end up in the form field anytime soon!</p>
<img id="clipboardImage" src="" alt="Click me, to bring him down!">
</div>
<br>
<form>
Worked?
<input type="text" name="copied Text">
</form>
</html>
So I am dynamically generating HTML code with JavaScript that loads in all my images from my Firebase Realtime Database. I'm currently working on implementing a button attached to each image that will delete this image when clicked. However, after multiple attempts to grab this div's ID attribute using both standard JavaScript and Jquery, the id in the alert box is always 'undefined'. Inspecting the webpage allows me to see that the image's id is always loaded in just fine, so I know it is there.
This is the HTML Generated that I'm trying to interact with.
JavaScript function to respond to my html 'onclick event'
function deleteFile(){
var postId = $(this).closest('div').attr('id');
alert("You have selected id: " + postId);
var sure = confirm("Are you sure you want to delete this post?");
if(sure){
firebase.database().ref().child('Posts/' + postId).remove().then(function(){
alert("Post deleted sucessfully");
});
}
};
Attached image is what html is generated on the actual chrome inspector. The ID's of course will all be unique.
add this parameter on your html onclick attribute so it become deleteFile(this)
then on your js
function deleteFile(element){
var postId = $(element).closest('div').attr('id');
alert("You have selected id: " + postId);
var sure = confirm("Are you sure you want to delete this post?");
if(sure){
firebase.database().ref().child('Posts/' + postId).remove().then(function(){
alert("Post deleted sucessfully");
});
}
};
Pairing onclick with $(this) won't work as you expect because $(this) has a different context, you could view its value using console.log($(this));
What should be done is add a class to that button and bind an onclick event via jquery. Run snippet below.
Red div contains onclick event attached via jquery.
Yellow div contains onclick event attached to the button attribute onclick.
$(document).ready(function(){
$(".getIdButton").click(function() {
alert($(this).closest("div").attr("id"));
});
});
function getId() {
alert($(this).closest("div").attr("id"));
console.log($(this));
}
div {
width: 100px;
height: 100px;
padding: 20px;
display: inline-block;
}
#red {
background-color: red;
}
#yellow {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="red">
Just a link
<button class="getIdButton">Click Me</button>
</div>
<div id="yellow">
Just a link
<button onclick="getId()">Click Me</button>
</div>
I would like to add text to the active textbox when a button is clicked.
I have read many threads explaining how it is done when one is wishing to add to a specific textbox but nothing on simply adding text to whichever text field is active...
Any help would be appreciated. Thanks.
The below is a solution for a virtual keyboard.
Pure JS + HTML:
function bind() {
var keyArr = document.getElementsByClassName('key');
for(var i = 0; i < keyArr.length; i++) {
keyArr[i].addEventListener('click', function() {
document.getElementById('textinput').value += this.innerHTML;
});
}
var capsLock = document.getElementById('capslock');
capsLock.addEventListener('click', function() {
for(var i = 0; i < keyArr.length; i++) {
if(capsLock.capsactive) {
keyArr[i].innerHTML = keyArr[i].innerHTML.toLowerCase();
} else {
keyArr[i].innerHTML = keyArr[i].innerHTML.toUpperCase();
}
}
capsLock.capsactive = !capsLock.capsactive;
});
}
<body onload='bind()'>
<input id='textinput'><br>
<button class='key'>q</button>
<button class='key'>w</button>
<button class='key'>e</button>
<button class='key'>r</button>
<button class='key'>t</button>
<button class='key'>y</button><br>
<button id='capslock' capsactive=false>CapsLock</button>
</body>
You can access a textbox's value by element.value or by $(selector).val().
For changing, use: element.value = newvalue; (JS) or $(selector).val(newvalue); (jQuery).
In the example, ...addEventListener... attaches a function to each button. The function, here, changes the value of the textinput textbox, to be the previous value + the text of the button which was pressed.
For instance, if the even the capsLock button is given the class key, on clicking capsLock, the text "Caps Lock" will be appended to the textbox.
Note: This solution covers adding text to a definite field. If there are multiple textbox-es present on the page, and the text has to be added to the currently focused one, a different approach has to be taken:
var lfl = -1, capsactive = false;
$(document).ready(function() {
$('*').blur(function() {
lfl = this;
});
$('.key').click(function() {
if($(lfl).hasClass('vkballowed')) {
$(lfl).val($(lfl).val() + $(this).html());
$(lfl).focus();
}
});
$('#capslock').click(function() {
capsactive = !capsactive;
if(capsactive == true) {
$('.key').each(function() {
$(this).html($(this).html().toUpperCase());
});
} else {
$('.key').each(function() {
$(this).html($(this).html().toLowerCase());
});
}
$(lfl).focus();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<input id='input0' class='vkballowed'><p>Editable</p><br>
<input id='input1' class='vkballowed'><p>Editable</p><br>
<input id='input2'><p>Not Editable</p><br>
<button class='key'>q</button>
<button class='key'>w</button>
<button class='key'>e</button>
<button class='key'>r</button>
<button class='key'>t</button>
<button class='key'>y</button><br>
<button id='capslock'>CapsLock</button>
Example instructions: Focus on the Editable text-fields, then press a key on the virtual-keyboard, so that corresponding text is appended to the fields. The virtual-keyboard doesn't work on the Not Editable text-field.
Here, the last element on the page that lost focus (was blurred) is stored in a variable. Next, whenever a key on the virtual-keyboard is pressed, first, it is checked whether the keyboard is allowed on that control, then the button's text is appended to the control, and finally, the control is given its focus back. Note that if the class vkballowed is added to controls such as buttons, no action would be effective on those controls. On other controls such as textareas, which have a value property, the virtual-keyboard will be functional.
The above approach isn't wholly correct. If, for instance, a key on the virtual-keyboard is pressed right after some other interactive button on the page, that button would receive focus again (this may not re-cause the action attached to that button, though). It, hopefully, gives you a starting point though.
jquery
$('#buttonId').click(function(event) {
$('.tstboxClass').val('heelo i am text box value.');
})
I want to create a live HTML/CSS preview on a page.
But the code will not be given using textareas. The code is going to be fixed in the page (div).
I want the user to be able to alter the code and that will reflect on the live preview box.I have created the page where you can change parts of the script text (for amateurs). You can preview that here :
http://apolosiskos.co.uk/HTML-CSS-EDITOR/index3.html
01) The live preview does not work if I replace the textarea with a div.
02) Even if I use the textareas, the live preview does not work because in my HTML script I am using the codeand the xmp tags.
--> Snippet that works with a textarea but not with a div :
var wpcomment = document.getElementById('WPComment');
wpcomment.blur = wpcomment.onkeypress = function(){
document.getElementById('prevCom').innerHTML = this.value;
}
#prevCom
{
background:#124;
color:#fff;
min-width:20px;
min-height:50px;
font-size:25pt;
}
<textarea name="WPcomment" id="WPComment" placeholder="Add comments:">aaaaa</textarea>
<div id="prevCom"></div>
with no success. Is there any other addEventListener() method I can replace keyup with?
Yes, blur
If you would like to add keydown events on a <div> element, you can do the following:
First, you need to set the tabindex attribute:
<div id="a-div" tabindex="1" />
Then,
(2) Bind to keydown:
$('#mydiv').bind('keydown', function(event) {
//console.log(event.keyCode);
});
If you would like your div to be "focused" from the start:
$(function() {
$('#mydiv').focus();
});
You should place your preview code it within a function, then you can simply call it once the document has loaded.
https://jsfiddle.net/michaelvinall/4053oL1x/1/
The separate issue of your preview only rendering when you press the enter key, is because of the following if statement:
if(e.which == 13 && $(this).val().length > 0)
The e.which == 13 within your if is specifying that the code within the block should only be ran if the key pressed by the user was the enter key (code 13). By removing this portion of each if statement, any key pressed will execute the code within the block:
if($(this).val().length > 0)
Your function is call when keyup is trigger, but no after page load.
You must do it : Define function to call them when 2 different event are fired.
$(function() {
function GetHtml(){
var html = $('.html').val();
return html;
}
function GetCss(){
var Css = $('.css').val();
return Css;
}
var previewRendering = function(){
console.log('kikou');
var targetp = $('#previewTarget')[0].contentWindow.document;
targetp.open();
targetp.close();
var html = GetHtml();
var css = GetCss();
$('body',targetp).append(html);
$('head', targetp).append('<style>' + css + '</style>');
};
$('.innerbox').on("keyup",function(){
previewRendering();
});
$(document).ready(function() {
previewRendering();
});
});
This code can not work because load event is only compatible with this list of HTML tags: body, frame, iframe, img, input type="image", link, script, style
$('.innerbox').load(function()
I create a textarea and a button on a loop based on a certain condition:
while($row_c= mysqli_fetch_array($result_comments))
{
//some code goes here
<textarea type="text" id="pm_text" name="text"></textarea><br>
<button name="send_comment" id="post_comment" class="button" onClick="post_pm_comment()">Post</button>
}
Now in my function "post_pm_comment" I would like to access the text written in the textarea when the post button is clicked.
I tried this, but it only gives me the text of the first textarea and button created:
function post_pm_comment(thidid, pm_id, path, pm,getter)
{
var pm_text = document.getElementById("pm_text").value;
}
What should I do?
Thank you
Your code is outputting an invalid DOM structure, because id values must be unique on the page. You cannot have the same id on more than one element. Remove the id values entirely, you don't need them.
Having done that, the minimal-changes answer is to pass this into your handler:
onClick="post_pm_comment(this)"
...and then in your handler, do the navigation:
function post_pm_comment(postButton)
{
var pm_text;
var textarea = postButton.previousSibling;
while (textarea && textarea.nodeName.toUpperCase() !== "TEXTAREA") {
textarea = textarea.previousSibling;
}
if (textarea) {
pm_text = textarea.value; // Or you may want .innerHTML instead
// Do something with it
}
}
Live Example | Source