Keyevent on an active textarea(ckeditor) in javascript - javascript

I have the code below
<script>
$(document).ready(function(){
//function showChar(){
shortcut.add("Ctrl+F1", function()
document.activeElement.id.value +="text";
});
var counter=0;
setInterval(function() {
for(int i=0;i<4;i++){
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<div><label style="float:left;"></label></div><pre><textarea name="textbox' + counter + '" id="textbox" ><%=rsta2.getString("data")%></textarea></pre>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
}
CKEDITOR.replace( 'textbox'+i+'',
{
toolbar :
[
['Source'],
['Bold','Italic','Underline','Strike'],
],
height: 300,
width: 700
});
},1000);
});
</script>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv0">
</div>
</div>
The above code(minus the ckeditor part of the code) adds 4 textareas,depending on which textarea is active when I press ctrl+f1 text is added to that particular textarea.But when I replace textarea with ckeditor the shortcut keys dont work.What should I do?

Replace your shortcut function with this:
shortcut.add("Ctrl+F1", function() {
var $active_textarea = $('textarea:focus');
var current_value = $active_textarea.val();
$active_textarea.val(current_value + "text");
});

You want to get the textarea that has focus, you can use
$('textarea:focus').val(paste_text);
that should do it.

Related

How to add a function to an appended element

I have an input-text. If you type something, the text appears below (see code snippet).
Now, I need to do the same with a previous step: clicking a button (preferably a checkbox) to append/remove all. Here is my failed idea: DEMO (it appends the input text, but when you type, text won't apear below like it does on my code snippet).
I feel like the function to add text below does not work because there is a problem with selecting the appended element. How do I do this?
Any more simple idea to do this would be great
var name1 = document.getElementById('name');
name1.addEventListener('input', function() {
var result = document.querySelector('.X');
console.log(this.value );
result.innerHTML = this.value;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>What is your name? </label><input type="text" id="name">
<p>Your name is: <span class="X"></span></p>
Put your first part of the snippet into appending logic while clicking the add button. As in your codes, the input box is appended to the document after its listener being attached.
if (!added) {
$content = $(NewContent).appendTo('.firstappend');
// attach listener after input box actually exists!
var name1 = document.getElementById('A');
name1.addEventListener('input', function() {
var result = document.querySelector('span.Y');
console.log(this.value );
result.innerHTML = this.value;
});
}
$(function() {
let NewContent = '<div class="added">' +
'<p>' +
'<label>What is your name? </label>' +
'<input type="text" id="A">' +
'</p>' +
'<p>Your name is: <span class="Y"></span></p>' +
'</div>';
$(".addremove").on('click', function() {
if ($(".added").length) {
$(".added").remove();
} else {
$(".firstappend").append(NewContent);
}
});
$(document).on('change keyup', '#A', function(event) {
$("span.Y").html($(event.currentTarget).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="toadd">
<button type="button" class="addremove">Do you have a name?</button>
</div>
<div class="firstappend"></div>
as from the DEMO you included,
appended elements to document cannot be invoked explicitly, since you're using jQuery, you can do this
$(document).on('change keyup', '#A', function(event) {
$("span.Y").html($(event.currentTarget).val());
});

How to show hide specific div in table?

HTML:-
'<td>' + item.Message + ' <input type="button" class="btn btn-info" id="' + item.LogID + '" onclick="Clicked(this);" value="View More" /> <p> ' + item.FormattedMessage + ' </p></td></tr>'
this is button in table
Jquery:-
function Clicked(e)
{
var SelectedID = e.id;
$("p").toggle();
};
In this When i click on button i want to show selected id column only and hide rest columns.
But when i click on button it shows all column or hides all column
In addition to balachandar answer. if you want to hide p tag initially then use display:none for p tag
function Clicked(e)
{
var SelectedID = e.id;
$("#"+SelectedID).next("p").toggle(function(){
var btn_text = $("#"+SelectedID).val();
if(btn_text == "View More"){
$("#"+SelectedID).val("Hide");
}else{
$("#"+SelectedID).val("View More")
}
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="btn btn-info" id="myID" onclick="Clicked(this)" value="View More" /> <p style="display:none"> Some Text you want to in future </p>
Try this below code
function Clicked(e)
{
var SelectedID = e.id;
$("#"+SelectedID).next("p").toggle();
};
Hope this will help you.
You can select the element by its id and find the p element inside:
function Clicked(e)
{
var SelectedID = e.id;
$("#" + SelectedID).find("p").toggle();
};
Or just use this:
function Clicked(e)
{
$(this).find("p").toggle();
};
function Clicked(e)
{
var SelectedID = e.id;
$("#" + SelectedID).toggle();
};
You can use:
function Clicked(d)
{
var SelectedID = d.id;
$("#" + SelectedID).toggle();
};
This function picks all p inside td of your table and hides all of them, then it shows only the one with the same ID as the button.
function Clicked(e) {
var SelectedID = e.id;
$("td p").hide();
$("#" + SelectedID).show();
};

jQuery variable is not updating on dynamic created textbox

I am trying to detect the current button click to assign values to its respective textboxes. Each time I select any of the button, it will detect the first button click and assign the value to the first textbox. Meaning to say that, the second and third button values are assigned to the first textbox. The upload_textbox variable is not changing its value.
I did some error testing, when upload_textbox variable enters custom_uploader.on('select', function(), the value stays and will not change. I am not sure on why it doesn't.
What have I done wrong here? Below are my codes:
function dynamic_image( button )
{
var custom_uploader;
$(button).on('click','input.button',function(e)
{
e.preventDefault();
var $clickedInput = $(this);// JQuery Object of section2_2
var clickedInputId = $clickedInput.attr('id'); // section2_2
var upload_textbox = '#' + 'upload_image_' + clickedInputId;
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media(
{
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function()
{
attachment = custom_uploader.state().get('selection').first().toJSON();
$(upload_textbox).val(attachment.url);
//console.log(upload_textbox);
});
//Open the uploader dialog
custom_uploader.open();
})
}
dynamic_image('#TextBoxesGroup');
HTML
<tr class="form-field">
<th scope="row">
<label for="component1"> Component 1</label>
<br></br>
<input type='button' class="button button-large" value='+' id='addButton'>
<input type='button' class="button button-large" value='-' id='removeButton'>
<input type='button' class="button button-large" value='Get TextBox Value' id='getButtonValue'>
</th>
<td>
<div id='TextBoxesGroup'>
<div id="ImageDiv1">
<input id="section2_1" class="button" type="button" value="Upload Image" name="upload_s2_1"/>
</div>
<div id="TextBoxDiv1">
<label>Title #1 : </label>
<input type='text' id='title1' />
</div>
<div id="DescDiv1">
<label>Description #1 : </label>
<input type='text' id='description1' /><br></br>
</div>
</div>
</td>
</tr>
script
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>5){
alert("Only 5 components are allowed");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
var newDescDiv = $(document.createElement('div'))
.attr("id", 'DescDiv' + counter);
var newImageDiv = $(document.createElement('div'))
.attr("id", 'ImageDiv' + counter);
var newUploadDiv = $(document.createElement('div'))
.attr("id", 'UploadDiv' + counter);
newTextBoxDiv.after().html('<label>Title #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="title_section2_' + counter + '" value="" >');
newDescDiv.after().html('<label>Description #'+ counter + ' : </label>' +
'<input type="text" name="descbox' + counter +
'" id="desc_section2_' + counter + '" value="" ><br></br>');
newImageDiv.after().html('<input class="button" type="button" name="upload_s2_' + counter +
'" value="Upload Image" id="section2_' + counter + '" >');
newUploadDiv.after().html('<input type="text" name="image_url_' + counter +
'" id="upload_image_section2_' + counter + '" >');
newUploadDiv.appendTo("#TextBoxesGroup");
newImageDiv.appendTo("#TextBoxesGroup");
newTextBoxDiv.appendTo("#TextBoxesGroup");
newDescDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more component to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
$("#DescDiv" + counter).remove();
$("#ImageDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
Then I suspect this could be the culprit.
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
This would always give you instance of first custom_uploader object.
Try to destroy the previous instance and generate new one.
There might be issue with the event binding within dynamic_image method.
Try
$(button).live('click',function(e) (deprecated as of jQuery 1.7 though)
or
$( document ).on( 'click', button, data, function(e)
instead of
$(button).on('click','input.button',function(e)
I hope it helps.
Can you try following.
$(button).change(function(){
//Write code here
});
I have solved my question. The culprit behind this was the custom_uploader mentioned by #Aman. There was a return statement there where it made the function not to take the new value that has been replaced. After doing so, the custom_uploader opens twice because there is two statement of it which it was called. Did it into an if else statement and had it the way I wanted. Below is my updated code.
function dynamic_image( button )
{
var custom_uploader;
var upload_textbox;
$(button).on('click','input.button',function(e)
{
e.preventDefault();
var $clickedInput = $(this);
var clickedInputId = $clickedInput.attr('id');
upload_textbox = '#' + 'upload_image_' + clickedInputId;
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media(
{
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function()
{
attachment = custom_uploader.state().get('selection').first().toJSON();
$(upload_textbox).val(attachment.url);
});
if (custom_uploader) {
custom_uploader.open();
}else
//Open the uploader dialog
custom_uploader.open();
})
}
#Aman, you have mentioned about optimizing it. It seems quite fast at the moment. Maybe if there is a way to optimize it for the better, it would be a great help.
Thank you all, #Regent, #Aman, #Bhushan Kawadkar, #Arindam Nayak, #Raj

Loop Through Looped Button Element to Manipulate Looped Input

I'm using JavaScript/jQuery. I'm having an issue with looping through an array to display the data as well as removing contents via button clicks.
Original Code in Question
HTML
<textarea id="sds">Apple
Banana
Grape
Orange</textarea>
<input type="hidden" id="sdh" />
Problem: Every button returns 5!
<div id="popup" title="Poof">
</div>
Script
var sds = $("#sds").val();
var sda = sds.split("\n");
var sdi = "";
$.each(sda, function(k, s) {
sdi += "<input type='text' id='sd" + k + "' value='" + s + "' /><button id='button" + k + "'>Click Me</button><br />";
$("#sdh").val(k);
});
$("#popup").html(sdi);
var h = $("#sdh").val();
var i = 0;
while (i <= h) {
$("#button" + i).click(function() {
// Here is where I have a problem trying to manipulate the input associated to the button.
alert(i); // Test to see what returns for the value of i.
$("#sd" + i).val("Clicked button " + i);
});
i++;
}
CSS (Thanks for providing the CSS to make the demo look better, Jose!)
#sds {
display: none;
}
jsFiddle
Revised Code
HTML
<textarea rows="4" cols="40" id="sds">Apple
Banana
Grape
Orange</textarea>
<input type="text" id="sd" value="Click here to verify" />
<input type="hidden" id="key" />
<div id="popup" title="Verify Multiple Fruits">
</div>
Script
$(document).ready(function() {
var sds = $("#sds").val();
var sda = sds.split("\n");
var sdi = "";
$.each(sda, function(key, sd) {
sdi += "<input type='text' id='sd" + key + "' value='" + sd + "' /><button id='button'" + key + "'>Remove</button><br />";
alert(key); // Test to see what returns for the value of i.
$("#button" + key).click(function() {
// Here is where I have a problem trying to manipulate the input associated to the button.
$("#sd" + key).val("Clicked button " + i);
});
$("#key").val(key);
});
$("#popup").html(sdi);
});
$(function() {
$("#popup").dialog({
autoOpen: false,
buttons: {
"Update": function() {
var key = $("#key").val();
var i = 0;
var sds = "";
while (i <= key) {
sds += $("#sd" + i).val() + "\n";
i++;
}
sds = sds.slice(0, -1);
$("#sds").val(sds);
$(this).dialog("close");
},
"Cancel": function() {
$(this).dialog("close");
}
},
close: function() {
},
height: 320,
hide: {
duration: 1000,
effect: "explode"
},
modal: true,
resizable: false,
show: {
duration: 1000,
effect: "blind"
},
width: 480
});
$("#sd").focus(function() {
$("#popup").dialog("open");
});
});
CSS (Thanks again for the CSS here, Jose!)
#sds {
display: none;
}
#popup input,
#popup button {
float: left;
width: auto;
}
#popup input {
clear: left;
}
jsFiddle
Revised Code after Applying One of the Answers
HTML
<textarea rows="4" cols="40" id="sds">Apple
Banana
Grape
Orange
Pear
Strawberry</textarea>
<input type="text" id="sd" value="Click here to verify." />
<input type="hidden" id="key" />
<div id="popup" title="Verify Multiple Fruits"></div>
Script
$(document).ready(function() {
$.each($("#sds").val().split("\n"), function(key, sd) {
$("#popup").append(
$("<input type='text' id='sd" + key + "' value='" + sd + "' />").add(
$("<button id='button" + key + "'>Remove</button><br />").click(function() {
$("#sd" + key).val("");
$("key").val(key);
})));
});
});
$(function() {
$("#popup").dialog({
autoOpen: false,
buttons: {
"Update": function() {
var key = $("#key").val();
var i = 0;
var sds = "";
while (i <= key) {
sds += $("#sd" + i).val() + "\n";
i++;
}
sds = sds.slice(0, -1);
$("#sds").val(sds);
$(this).dialog("close");
},
"Cancel": function() {
$(this).dialog("close");
}
},
close: function() {
},
height: 320,
hide: {
duration: 1000,
effect: "explode"
},
modal: true,
resizable: false,
show: {
duration: 1000,
effect: "blind"
},
width: 480
});
$("#sd").focus(function() {
$("#popup").dialog("open");
});
});
CSS (This is really awesome, Jose!)
#sds {
display: none;
}
#popup input,
#popup button {
float: left;
width: auto;
}
#popup input {
clear: left;
}
jsFiddle
Suppose the value of sds is Apple, Banana, Grape and Orange on different lines. Each button created by the .each() loop will have the correct number assigned, but when trying to change the value, the variable i returns 5 on the alert message box while the next line doesn't seem to work at all - due to the index being off.
How can I revise this code to make it work like it's supposed to?
Corrected the error mentioned by the loving and caring commentators. Still not working. Obviously that wasn't the issue as my original code that I copied off of had the parenthesis closed correctly. I was hand-jamming the code here since I have no ability to copy and paste the code here, so a small typo was made. My question is about the logic, not typo. Thanks!
In order to minimize the confusion, I've revised the code section of this question to reflect the original code I had, so it'll show the consistency with the answers Jose provided below.
Obviously, the revised code also had more issues, so I made a new revision yet again. Here is what I've gotten so far. It's still quirky, but works on most part. I'm going to need help with the cancel action on the modal dialog since it won't bring back the previous values from the textarea tag. Also, please, note the version changes on jQuery and addition of jQuery UI to the JSFiddle demo to reflect my development environment.
The Ultimate Solution
HTML
<textarea rows="4" cols="40" id="sds">Apple
Banana
Grape
Orange
Pear
Strawberry</textarea>
<input type="text" id="sd" value="Click here to verify." />
<div id="popup" title="Verify Multiple Fruits"></div>
Script
$(document).ready(function() {
if ($("#sds").val()) {
var i = 0;
$.each($("#sds").val().split("\n"), function(key, sd) {
$("#popup").append(
$("<input type='text' class='blah' id='sd" + key + "' value='" + sd + "' />").add(
$("<button id='button" + key + "'>Remove</button><br />").click(function() {
$("#sd" + key).val("");
})));
i++;
window["i"] = i;
});
}
});
$(function() {
$("#popup").dialog({
autoOpen: false,
buttons: {
"Update": function() {
var i = window["i"];
var sds = "";
$(".blah").each(function(i) {
if ($(this).val()) {
sds += $("#sd" + i).val() + "\n";
}
});
sds = sds.slice(0, -1);
$("#sds").val(sds);
$(this).dialog("close");
},
"Cancel": function() {
$(this).dialog("close");
}
},
close: function() {
$("#popup").html("");
if ($("#sds").val()) {
var i = 0;
$.each($("#sds").val().split("\n"), function(key, sd) {
$("#popup").append(
$("<input type='text' class='blah' id='sd" + key + "' value='" + sd + "' />").add(
$("<button id='button" + key + "'>Remove</button><br />").click(function() {
$("#sd" + key).val("");
})));
i++;
window["i"] = i;
});
}
},
height: 320,
hide: {
duration: 1000,
effect: "explode"
},
modal: true,
resizable: false,
show: {
duration: 1000,
effect: "blind"
},
width: 480
});
$("#sd").focus(function() {
if ($("#sds").val()) {
$("#popup").dialog("open");
}
});
});
CSS
#sds {
display: none;
}
#popup input,
#popup button {
float: left;
width: auto;
}
#popup input {
clear: left;
}
jsFiddle
Thoughts after Solving the Issue
I was initially irritated by the people who pointed out the typos rather than trying to see the entire picture to discover the "big" flaw with the program itself because that's what I thought I would have done for people who would ask me for guidance. Then, it hit me when I thought about how I would really react when I see petty mistakes like typos and bad grammars. I admit I hate seeing those petty mistakes, mostly because I have an obsessive-compulsive disorder when it comes to writing anything, including codes. Now that I've learned about JSFiddle, I'll test my code there before trying to post a question here from now on. It has been a terrific learning experience and thanks to all for the assistance.
There are several ways to solve this problem.
Use a closure
Inside the loop, declare an anonymous function and call it immediately, passing in i as the parameter local_i. In other words, i has a global scope, but the local_i has a scope limited to the anonymous function. This way, the click event "sees" the local_i value, not the i (5) as you had before.
while (i <= h) {
(function (local_i) {
$("#button" + local_i).click(function() {
alert(local_i); // Test to see what returns for the value of i.
$("#sd" + local_i).val("Clicked button " + local_i);
});
})(i); // <-- HERE I am calling the function
i++;
}
Click here for a live demo
Get the index from the button id
There is one pattern here: You want i=0 for #button0, i=1 for #button1.
So, just get the index from the id. This solution requires no loops.
// select all buttons inside #popup, that have an id starting by "button"
$("#popup button[id^=button]").click(function() {
var i = parseInt($(this).attr('id').replace('button', ''));
alert(i); // Test to see what returns for the value of i.
$("#sd" + i).val("Clicked button " + i);
});
Live demo
Optimized version, no loops, no global variables
$.each($("#sds").val().split("\n"), function(k, s) {
$("#popup").append(
// append the text box
$("<input type='text' id='sd" + k + "' value='" + s + "' />").add(
// and the button with the click already defined
$("<button id='button" + k + "'>Click Me</button>").click(function() {
alert(k);
$("#sd" + k).val("Clicked button " + k);
}))
);
});
Live demo
Final Solution
Brand new code was pasted into the question. To fix the problem in that code, just change
$("#button" + key).click(function() {
// Here is where I have a problem trying to manipulate the input associated to the button.
$("#sd" + key).val("Clicked button " + i);
});
to
$("#button" + key).click(function() {
var i = $(this).attr('id').replace('button', '');
$("#sd" + i).val("Clicked button " + i);
});
You can use the other alternatives I wrote above.
Hope this helps.
you have an error here
$("#button" + i.click(function() {
it should be
$("#button" + i).click(function() {
corrent that and it will work.

jQuery text to input?

I have a simple layout with a textblock and one <a>, like:
text1 edit
When I click on the <a>, I want this textblock to become text input. How is that possible with jQuery?
Use jQuery replaceWith():
$(document).ready(function(){
$("a").click(function(e){
e.preventDefault();
$(this).parent().replaceWith("<input />");
});
});
http://jsfiddle.net/Dqkyg/1/
Furthermore, you can fill the textbox with the text outside the link like so:
$(document).ready(function(){
$("a").click(function(e){
e.preventDefault();
var txt = $(".text").html();
$(".text").replaceWith("<input value='" + txt + "' />");
});
});
http://jsfiddle.net/Dqkyg/5/
The following will replace the edit with Save & Cancel options:
<div>
<span class="text">testing</span> <a href='#'>test</a>
</div>
$(document).ready(function(){
$("a").click(function(e){
e.preventDefault();
var txt = $(".text").html();
$(".text").replaceWith("<input value='" + txt + "' />");
$(this).replaceWith("<a href='#'>Save</a> | <a href='#'>Cancel</a>");
});
});
http://jsfiddle.net/Dqkyg/6/
There are plenty of plugins that you can use... No need to reinvent the wheel
http://www.appelsiini.net/projects/jeditable
Hmm ... ur a bit unclear... but
http://jsfiddle.net/mMYrf/4/
<div class="dataGrid">
<span>test</span>
edit
</div>
And
$('.dataGrid a').click( function(e) {
e.preventDefault();
var EditGrid = $(this).parent().children('span');
var DataTxt = EditGrid.text();
var InputHtml = '<input type=text" value="'+DataTxt +'" />';
$(this).text('Save?');
EditGrid.html(InputHtml);
});
<div class="editable">This is the content.</div>
<script type="text/javascript">
$(function() {
$('.editable').each(function() {
var a = $('edit');
(function(link, parent) {
link.click(function() {
link.remove();
var textField = $('<textarea/>').val(parent.html());
parent.replaceWith(textField);
delete parent, link;
});
})(a, $(this));
$(this).append(" ").append(a);
});
});
</script>
Working example: http://jsfiddle.net/BnH29/

Categories

Resources