Append text into div element when click using jquery - javascript

Using the below code I append some input elements into the #cls div. But when I try to type inside the input also new input add. I only need new input when I click "click" text. Can anyone help me. Thank you
$('#cls').click(function() {
var add="<input type="text">"
$(#cls).append(add);
});
<div id="cls">click</div>

You need to see whether the click actually happened in the div
$('#cls').click(function(e) {
if ($(e.target).is(this)) { //or !$(e.target).is('input')
var add = '<input type="text">';
$(this).append(add);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cls">click</div>

If you user .after() method instead of .append() the textbox would appear outside the #cls div and hence clicking the textbox wouldn't cause adding a new one.
Some code
$('#cls').click(function() {
var add="<input type='text'>";
$('#cls').after(add);
});
Try it out

Append your input to parent element:
var clicked= false;
$('#cls').click(function() {
if(!clicked){
var add="<input type='text'>";
$(this).parent().append(add);
clicked = true;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='cls'>click</div>

use jQuery's one method. it will register click handler only once.
$('#cls').one("click", function(e) {
var add = '<input type="text">';
$(this).append(add);
});

Related

How to delete text box along with button in JavaScript

I have a button when user clicks the button it create the text box along with remove button
but all the text boxes created with same id how we can delete the text box when clicks respective remove button
here My Code:
<body>
<button type="button" id="URLbtn" onclick="Createinput()"> + Add URL</button>
<div id="TextAreaBtn"></div>
<script>
function Createinput() {
var newdiv=document.createElement("div");
newdiv.id="test"
var Inputele=document.createElement("input");
Inputele.type="text";
Inputele.id="URLtxt"
newdiv.appendChild(btnele);
var btnele=document.createElement("button");
btnele.id="rmvbtn"
btnele.type="button"
btnele.innerHTML="-"
btnele.onclick=RemoveUrlBox()
newdiv.appendChild(btnele);
var element = document.getElementById("TextAreaBtn");
element.appendChild(newdiv);
}
function RemoveUrlBox() {}
</script>
</body>
i am getting following output
if user click 2 remove button only remove the second textbox and button
You need to select the wrapping div. Easiest way is to use remove() and use closest. No need to use the id..... You also need to remember ids need to be unique.
function createInput() {
var newDiv = document.createElement("div");
newDiv.className = 'group';
var inputElem = document.createElement("input");
inputElem.type = "text";
newDiv.appendChild(inputElem);
var btnElem = document.createElement("button");
btnElem.type = "button";
btnElem.textContent = "-";
btnElem.addEventListener("click", removeUrlBox);
newDiv.appendChild(btnElem);
var element = document.getElementById("TextAreaBtn");
element.appendChild(newDiv);
}
function removeUrlBox() {
this.closest('.group').remove();
}
<button type="button" id="URLbtn" onclick="createInput()"> + Add URL</button>
<div id="TextAreaBtn"></div>
This should do the trick:
const txtarea=document.getElementById('TextAreaBtn');
document.getElementById('URLbtn').onclick=()=>txtarea.innerHTML+=
'<div><input type="text" class="URLtxt"><button class="rmvbtn">-</button></div>';
txtarea.onclick=ev=>ev.target.className==="rmvbtn"&&ev.target.parentNode.remove()
<button type="button" id="URLbtn"> + Add URL</button>
<div id="TextAreaBtn"></div>
I replaced your id attributes with class attributes, as these don't need to be unique.
I reduced your script by using innerHTML instead of laboriously putting elements together with createElement(). This is a matter of opinion as both methods have their advantages.
I also used delegated event listener attachment for the removal buttons. This way you can get away with a single event listener on div.TextAreaBtn. The attached funcion will only trigger any action if the clicked element has class "rmvbtn".
Change
btnele.onclick=RemoveUrlBox()
to
btnele.addEventListener('click', function (e) {
// `this` is the button that was clicked no matter about the id
// `this.parentNode` is the div you want to remove
const nodeToRemove = this.parentNode;
nodeToRemove.parentNode.removeChild(nodeToRemove);
});

Append text to currently selected div

I'm working on this website www.betamaths.eu
When a user had clicked inside one of the divs that have placeholder text and then click a button on the left, I would like the text from that button to append inside the div.
I have this code from another user which appends or prepends text ouside the div (not what I am looking for. You can test it with the lowercase alpha button in the menu on the left of the webpage listed above if you wish to get a better understanding.
<script type="text/javascript">
var No = 0;
var focusedElement;
$(document).ready(function() {
$('#answer_step1').on('click','div',function() {
focusedElement = this;
});
$('#alpha').on('click',function() {
$('#answer_step1').prepend('<div>Test'+No+'</div>');
No++
});
});
If I change the line
$('#answer_step1').append('<div>Test'+No+'</div>');
to
$('#answer_step1').append('Test'+No);
nothing happens. Any help is appreciated. If I can get one of these working, the rest will be easy.
You must have a syntatically error in your code, because I used your same code and was able to accomplish the append();
HTML:
<button id="alpha">
Click
</button>
<div id="answer_step1">
hi
</div>
Javascript:
var No = 0;
var focusedElement;
$(document).ready(function() {
$('#answer_step1').on('click','div',function() {
focusedElement = this;
});
$('#alpha').on('click',function() {
$('#answer_step1').prepend('Test' + No);
No++
});
});
https://jsfiddle.net/typtzr7z/

Get value of appended textarea

i append a textarea with a button
$(".mydiv").append("<textarea id='myTextarea'></textarea><div class='sendReply btn btn-default'>my button</div>");
After that , i'm writing new texts into textarea and trying to get new writed value inside from textarea with this on click function ;
jQuery(document).on('click','.sendReply', function () {
var myNewText = $("#myTextarea").val();
console.log(myNewText);
});
But it says that this an "empty string" , if i add text area with a value like <textarea id="myTextarea">some text</textarea> my fucntion works and gives me "some text" but if i edit textarea and click sendReply button (my on click function), it is still gives me "some text" , it don't change
How can i get edited textarea value after apppend a textarea?
You have an . in .sendReply while appending the HTML
You just need to remove . from .sendReply
Use
<div class='sendReply btn btn-default'>my button</div>"
As you are using Event delegation your jQuery will work.
As you are adding textarea with same ID multiple times? $("#myTextarea").val() will always show value of first textarea with id myTextarea. You can use a common class and then use prev() to select the textarea
See example
$(document).ready(function() {
$(document).on('click', '.sendReply', function() {
var myNewText = $(this).prev(".myTextarea").val();
alert(myNewText);
});
for (var i = 0; i < 5; i++) {
$(".mydiv").append("<textarea class='myTextarea'>some text</textarea><div class='sendReply btn btn-default'>my button</div>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='mydiv'></div>
It should be
$(".mydiv").append("<textarea id='myTextarea'></textarea><div class='sendReply btn btn-default'>my button</div>");
then
jQuery(document).on('click','.sendReply', function () {
var myNewText = $("#myTextarea").val();
console.log(myNewText);
});
dont use dot(.) for the classname..
Instead using div .. use some standard to code up .. you can make it has button .. here is the code
<div class="mydiv"></div>
$(".mydiv").append("<textarea id='myTextarea'></textarea><input type='button' class='sendReply btn btn-default' value='my button'></input>");
jQuery(document).on('click','.sendReply', function () {
var myNewText = $("#myTextarea").val();
console.log(myNewText);
alert(myNewText);
});
JSFIDDLE

Pass element value dynamically using javascript

I have a loop that display buttons with class name that has javascript on it. I need to pass the id of span that is clicked. My problem is because of the loop there, I can get the ID by its index but what I want to get is the id of the clicked button dynamically.
while(...){
<span class="id">'.$table["id"].'</span>
<input type="button" class="edit" value="Edit"/>
}
$('.edit').on('click', function (e) {
var x=document.getElementsByClassName("id")[0];
var xx = x.innerHTML;
$.fancybox({
...
}
});
});
sounds like you want to use
var x= $(this).closest("span");
that should get you the span next to the button clicked.
Could you use just $(this). within your click event?
You don't need to do this:
var x=document.getElementsByClassName("id")[0];
just say
var x = $(this);
because you are already on your element there, when the click event happens.
Hope it helps! :)
I would go with data attributes for passing variables, so you can leave classes for css style purposes only. Also if you are already using jQuery why not going all the way with it?
while(...){
<span class="id" data-id="id">'.$table["id"].'</span>
<input type="button" class="edit" value="Edit" data-target="id"/>
}
$('.edit').on('click', function (e) {
var data = $(this).data('target'); // Get the data-target attribute
var target = $('*[data-id='+data+']'); // Find the matching span
var xx = target.html(); // Get HTML from Span
$.fancybox({
...
}
});
});

changing input text to textarea just like in facebook

i would like to replicate that you see a regular input text and when you click it changes into textarea.
is this a hidden layer or is it actually changing the input to textarea? how to do it?
I do believe it's always a textarea and on focus they just change the height of the textarea.
Edit: yes, it is. They use scripting to do everything with a textarea, there is no input field.
<textarea onfocus='CSS.addClass("c4b900e3aebfdd6a671453", "UIComposer_STATE_INPUT_FOCUSED");CSS.removeClass("c4b900e3aebfdd6a671453_buttons", "hidden_elem");window.UIComposer && UIComposer.focusInstance("c4b900e3aebfdd6a671453");' id="c4b900e3aebfdd6a671453_input" class="UIComposer_TextArea DOMControl_placeholder" name="status" title="What's on your mind?" placeholder="What's on your mind?">
What's on your mind?
</textarea>
One method that I found was to have a text area that begins with a smaller width and height and then to dynamically resize it.
function sz(t) {
a = t.value.split('\n');
b=1;
for (x=0;x < a.length; x++) {
if (a[x].length >= t.cols) b+= Math.floor(a[x].length/t.cols);
}
b+= a.length;
if (b > t.rows) t.rows = b;
}
then you would call your function with an onclick event
onclick="function sz(this)"
I found this here
Fellgall Javascript
One problem that he does mention is that this only functions on browsers that support it.
You can combine the jQuery widget you can find here with some coding
Example:
<div id="myform">
<form>
<textarea></textarea>
<button type="submit" style="display:none;">Post</button>
</form>
</div>
<script>
$(document).ready(function(){
var widget = $('#myform textarea');
var button = $('#myform button');
var tarea = widget[0];
// turn the textarea into an expandable one
widget.expandingTextArea();
var nullArea = true;
tarea.value = "What's on your mind?";
widget.focus(function() {
button.css('display', 'block');
if (nullArea) {
tarea.value = "";
nullArea = false;
}
});
widget.blur(function() {
if ($.trim(tarea.value) == "") {
tarea.value = "What's on your mind?";
button.css('display', 'none');
nullArea = true;
}
});
});
</script>
This code will hide by default the post button and will show it only when the textarea is focused or when you already have written something into it (you may want to hide/show a div instead or anything you want).
If jQuery is an option for you at all, there's a jQuery plugin that does just this called Jeditable.
Check out the demos here.
One way to do this is to code a dynamic textarea. This article explains how to do it: http://www.felgall.com/jstip45.htm
Another way to do it is to change the type of the object. Let's say you place your input text in a div tag (its ID being "commentBox". The code would then be:
//when you click on the textbox
function makeTextArea()
{
document.forms[0].getElementById("commentBox").innerHTML = "<textarea id=\"comments\" onBlur=\"backToTextBox()\"></textarea>";
document.forms[0].getElementById("comments").focus();
}
//when you click outside of the textarea
function backToTextBox()
{
document.forms[0].getElementById("commentBox").innerHTML = "<input type=\"text\" id=\"comments\" onFocus=\"makeTextArea()\"/>";
}

Categories

Resources