I want to be able when I press button "Submit" to add dynamically image. Something like the image below.
I have researched by my self, but couldn't find any solution. Any kind of help will be helpful :)
Live Demo
HTML:
<textarea id ="comments" cols="30" rows="3"></textarea>
<input type="submit" value="Submit" id="submit"/>
<div id="divComments"></div>
JQuery:
function addComment(name1) {
var container = $('#divComments');
var inputs = container.find('label');
var id = inputs.length + 1;
var div = $('<div />', { class: 'CommentStyle' });
$('<label />', {
id: 'comment' + id,
text: name1
}).appendTo(div);
div.appendTo(container);
}
$('#submit').click(function () {
addComment($('#comments').val());
$('#comments').val("");
});
Check That DEMO
That Should do your job
var img = $('<img>').attr("src", 'http://ssl.gstatic.com/accounts/ui/logo_2x.png').appendTo($('#divComments'));
Related
Basically, I have a simple webpage with two text fields, and a button to choose an image from the computer. What I need to happen, is for the user to pick a photo, fill in the "artist" and "text" field, press the "Add image" button. This should then add all three items to an array, and display both the image in a div, and the text in an "li" list item.
At the moment, the image works, and will display on the screen when the button is pressed, the text seems to get pushed into the array, but no matter what I do, I can't get the text to display on the web page. I also couldn't get the image to display if I turned the array into objects, which is why I've split the pushing of the text to a separate function.
Either way, whatever I try, either breaks the image display, or breaks the text display. I can't get both to display on the page. I am trying to make it so whenever a new image and text is added, it will all display one after another sort of like this:
[album cover]
[text]
[album cover]
[text]
And this would carry on down the screen as you keep adding more. Can someone please tell me where I'm going wrong with this. Thanks.
var info = {
myImages: [],
addImage: function(imageBlob) {
this.myImages.push(imageBlob);
},
addInfo: function(artist, title) {
this.myImages.push({
artist: artist,
title: title
});
},
redrawImages: function() {
var divForImages = document.getElementById('myImages');
divForImages.innerHTML = '';
this.myImages.forEach((imageBlob) => {
var img = document.createElement('img');
img.style.width = "200px";
img.style.height = "200px";
img.src = URL.createObjectURL(imageBlob);
divForImages.appendChild(img);
});
},
redrawInfo: function() {
var ul = document.querySelector('ul');
this.myImages.forEach(function (item) {
let li = document.createElement('li');
ul.appendChild(li);
li.innerHTML += item;
});
}
}
var handlers = {
addImageAndRedraw: function() {
var fileInput = document.getElementById('fileInput');
var artistField = document.getElementById('artistField');
var titleField = document.getElementById('titleField');
if (fileInput.files.length === 1) {
info.addImage(fileInput.files[0]);
info.addInfo(artistField.value, titleField.value);
info.redrawImages();
info.redrawInfo();
}
}
}
var button = document.getElementById('button');
button.addEventListener('click', handlers.addImageAndRedraw);
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>My images</h1>
<input id="fileInput" type="file" accept="image/*" multiple="false" value="Select image">
<input id="button" type="button" value="Add image and redraw">
<div>
<input id="artistField" type="text" placeholder="artist">
<input id="titleField" type="text" placeholder="title">
</div>
<hr>
<div id="myImages">
</div>
<ul></ul>
<script src="album.js"></script>
</body>
</html>
You're adding the info to the same array as the images, so it will end up like [image, info, image, info] etc.. You're better off adding an object that contains both the image and the info, and then treating it as a single object when you add the contents to the page, rather than adding the images and text in separate functions. Also, you're not clearing the info list, so it would grow exponentially.
Here's a modified example, just after tweaking the bits I mentioned above...
var info = {
myInfo: [],
add: function(imageBlob, artist, title) {
this.myInfo.push({
image: imageBlob,
artist: artist,
title: title
});
},
redraw: function() {
var divForImages = document.getElementById('myImages');
divForImages.innerHTML = '';
var ul = document.querySelector('ul');
ul.innerHTML = "";
this.myInfo.forEach((info) => {
var img = document.createElement('img');
img.style.width = "200px";
img.style.height = "200px";
img.src = URL.createObjectURL(info.image);
divForImages.appendChild(img);
let li = document.createElement('li');
ul.appendChild(li);
li.innerHTML = info.artist + " - " + info.title;
});
},
}
var handlers = {
addImageAndRedraw: function() {
var fileInput = document.getElementById('fileInput');
var artistField = document.getElementById('artistField');
var titleField = document.getElementById('titleField');
if (fileInput.files.length === 1) {
info.add(fileInput.files[0], artistField.value, titleField.value);
info.redraw();
}
}
}
var button = document.getElementById('button');
button.addEventListener('click', handlers.addImageAndRedraw);
<h1>My images</h1>
<input id="fileInput" type="file" accept="image/*" multiple="false" value="Select image">
<input id="button" type="button" value="Add image and redraw">
<div>
<input id="artistField" type="text" placeholder="artist">
<input id="titleField" type="text" placeholder="title">
</div>
<hr>
<div id="myImages"></div>
<ul></ul>
I am using ckeditor on textarea but i could not get data from it.
Code :
<textarea name="DSC" class="materialize-textarea"></textarea>
<script>
CKEDITOR.replace('DSC');
</script>
Jquery :
var title = $('input[name=TITLE]').val();
var desc = $('textarea[name=DSC]').text();
var formdata = 'TITLE='+title+'&DSC='+desc;
No need for jQuery CKEditor has its own method to get data from converted textarea:
var desc = CKEDITOR.instances['DSC'].getData();
OR:
var desc = CKEDITOR.instances.DSC.getData();
Use id attibute in textarea and use that id in CKeditor instead of textarea's name check bellow
<textarea name="textareaname" id="textarea-id"></textarea>
CKEDITOR.replace( 'textarea-id');//use id not name//
var ckValue = CKEDITOR.instances["textarea-id"].getData(); or
var ckValue = CKEDITOR.instances.textarea-id.getData();
alert(CKEDITOR.instances.DSC.getData());
Past Text area id below.
CKEDITOR.instances['Text_Area_Id_Here'].getData();
For example, i have text area
<textarea class="form-control" id="Description" name="description" width="100%" height="150" ckeditor="true" maxlength="20000" ismandatory="false">
</textarea>
I got value of text area like this
var description = CKEDITOR.instances['Description'].getData();
Using the jQuery_Adapter you may write:
$(function () {
$('textarea[name="DSC"]').ckeditor();
$('#btn').on('click', function(e) {
console.log('ckeditor content: ' + $('textarea[name="DSC"]').val());
})
});
Include files:
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="//cdn.ckeditor.com/4.5.9/standard/ckeditor.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/ckeditor/4.5.9/adapters/jquery.js"></script>
HTML:
<textarea name="DSC" class="materialize-textarea"></textarea>
<button id="btn">Get text</button>
<form>
<textarea name="editor1" id="editor1" rows="10" cols="80">
This is my textarea to be replaced with CKEditor.
</textarea>
<button type="button" id="getDataBtn">Get Data</button>
</form>
<script>
// Replace the <textarea id="editor1"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace( 'editor1' );
$(document).ready(function(){
$("#getDataBtn").click(function(){
var editorData= CKEDITOR.instances['editor1'].getData();
alert(" your data is :"+editorData);
})
});
</script>
//getting data form ckeditor in textarea.
var NodeDataSessionTextarea = {};
jQuery('.class-textarea').each(function(index, el) {
var editor_id = jQuery(this).attr('id');
var elevalue = jQuery(this).val();
// Getting ckeditor instance.
var editor = CKEDITOR.instances[editor_id];
if (editor) {
editor.on('key', function(e) {
var self = this;
setTimeout(function() {
//store data in object with id
NodeDataSessionTextarea[editor_id] = self.getData();
}, 10);
});
editor.on('afterCommandExec', function(e) {
var self = this;
setTimeout(function() {
//store data in object with id
NodeDataSessionTextarea[editor_id] = self.getData();
}, 10);
});
editor.on( 'blur', function() {
//store data in session
var nodedataencodetextarea = JSON.stringify(NodeDataSessionTextarea);
sessionStorage.setItem("NodeDataSessionTextarea", nodedataencodetextarea);
});
}
});
//put data in ckeditor.
var editor = CKEDITOR.instances[id];
if (editor) {
editor.setData(getTemplateData);
}
For an update of Bogdan Kuštan's answer using CKEditor 5 (tested in may 2022):
editor.getData() is the new way of getting the Data from the editor.
Here is one common example of using it: filling an hidden field on submitting the form.
import ClassicEditor from '.../src/ckeditor.js';
ClassicEditor
.create('#editor-container')
.then(editor => {
persistForm(editor);
};
function persistForm(editor)
{
document.querySelector('form').addEventListener('submit', (e) => {
document.querySelector('.hidden-input').value = editor.getData();
});
}
This post is also a reminder for myself later.
You should use getData() method to get data from CKEDITOR.
<textarea name="DSC" class="materialize-textarea" id="DSC"></textarea>
<script>
CKEDITOR.replace('DSC');
</script>
//reference the id DSC
var desc = CKEDITOR.instances['DSC'].getData();
When I write some text in the input field. And want it displayed below the input field, when pressing the submit button it disappears. I don't know why.
Live Demo
HTML:
<textarea id ="comments" cols="30" rows="3"></textarea>
<input type="submit" value="Submit" id="submit"/>
<div id="divComments"></div>
Jquery:
function addComment(name1) {
var container = $('divComments');
var inputs = container.find('label');
var id = inputs.length + 1;
var div = $('<div />');
$('<label />', {
id: 'comment' + id,
text: name1
}).appendTo(div);
div.appendTo(container);
}
$('#submit').click(function () {
addComment($('#comments').val());
$('#comments').val("");
});
You missed the # for id selector, change
var container = $('divComments');
to
var container = $('#divComments');
See the fixed demo.
The selector for the divComments div is missing the # for the id selector.
function addComment(name1) {
var container = $('#divComments');
var inputs = container.find('label');
var id = inputs.length + 1;
var div = $('<div />');
$('<label />', {
id: 'comment' + id,
text: name1
}).appendTo(div);
div.appendTo(container);
}
$('#submit').click(function () {
addComment($('#comments').val());
$('#comments').val("");
});
Working fiddle.
As well as fixing the following line to add a hash
var container = $('#divComments');
you will also want to change the submit function:
$('#submit').click(function (e) {
e.preventDefault();
addComment($('#comments').val());
$('#comments').val("");
});
This will stop the form actually been submitted (and reloading the page) - which is probably the reason for your text disappearing. If you don't have a form surrounding your inputs then you don't need to bother with the second part of this answer.
im very new at javascipt (im php developer) so im really confused trying to get this working.
In my web form i have 3 textfields (name, description and year) that i need to let the user add as many he needs, clicking on a web link, also, any new group of text fields need to have a new link on the side for removing it (remove me).
I tried some tutorial and some similar questions on stackoverflow but i dont get it well. If you can show me a code example just with this function i may understand the principle. Thanks for any help!
this is the simplest thing that has come to my mind, you can use it as a starting point:
HTML
<div class='container'>
Name<input type='text' name='name[]'>
Year<input type='text' name='year[]'>
Description<input type='text' name='description[]'>
</div>
<button id='add'>Add</button>
<button id='remove'>Remove</button>
jQuery
function checkRemove() {
if ($('div.container').length == 1) {
$('#remove').hide();
} else {
$('#remove').show();
}
};
$(document).ready(function() {
checkRemove()
$('#add').click(function() {
$('div.container:last').after($('div.container:first').clone());
checkRemove();
});
$('#remove').click(function() {
$('div.container:last').remove();
checkRemove();
});
});
fiddle here: http://jsfiddle.net/Fc3ET/
In this way you take advantage of the fact that in PHP you can post arrays: server side you just have to iterate on $_POST['name'] to access the various submissions
EDIT - the following code is a different twist: you have a remove button for each group:
$(document).ready(function() {
var removeButton = "<button id='remove'>Remove</button>";
$('#add').click(function() {
$('div.container:last').after($('div.container:first').clone());
$('div.container:last').append(removeButton);
});
$('#remove').live('click', function() {
$(this).closest('div.container').remove();
});
});
Fiddle http://jsfiddle.net/Fc3ET/2/
jsFidde using append and live
String.format = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}
var html = "<div>" + '<input name="name{0}" type="text" />' + '<input name="description{1}" type="text" />' + '<input name="year{2}" type="text" />' + '<input type="button" value="remove" class="remove" />' + '</div>',
index = 0;
$(document).ready(function() {
$('.adder').click(function() {
addElements();
})
addElements();
$('.remove').live('click', function() {
$(this).parent().remove();
})
});
function addElements() {
$('#content').append(String.format(html, index, index, index));
index = index + 1;
}
Look at this: http://jsfiddle.net/MkCtV/8/ (updated)
The only thing to remember, though, is that all your cloned form fields will have the same names. However, you can split those up and iterate through them server-side.
JavaScript:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#addnew").click(function(e) {
$("#firstrow").clone() // copy the #firstrow
.removeAttr("id") // remove the duplicate ID
.append('<a class="remover" href="#">Remove</a>') // add a "remove" link
.insertAfter("#firstrow"); // add to the form
e.preventDefault();
});
$(".remover").live("click",function(e) {
// .live() acts on .removers that aren't created yet
$(this).parent().remove(); // remove the parent div
e.preventDefault();
});
});
</script>
HTML:
Add New Row
<form id="myform">
<div id="firstrow">
Name: <input type="text" name="name[]" size="5">
Year: <input type="text" name="year[]" size="4">
Description: <input type="text" name="desc[]" size="6">
</div>
<div>
<input type="submit">
</div>
</form>
Try enclosing them in a div element and then you can just remove the entire div.
Try this
Markup
<div class="inputFields">
..All the input fields here
</div>
Add
<div class="additionalFields">
</div>
JS
$("#add").click(function(){
var $clone = $(".inputFields").clone(true);
$clone.append($("<span>Remove</span").click(functio(){
$(this).closest(".inputFields").remove();
}));
$(".additionalFields").append($clone);
});
There are 2 plugins you may consider:
jQuery Repeater
jquery.repeatable
This question has been posted almost 4 years ago. I just provide the info in case someone needs it.
Right now I have this in Javascript without jQuery:
Here is it: http://jsbin.com/ewihu3
It's working just fine, but I wish to use jQuery for making the code simpler and shorter.
I want exactly same things to do as on the example above, that when you click on the text, it should turn into an input field. And on blur it should display what you've edited in the box, and then make a variable (like e.value on the example above) so I can send that in a ajax call later.
How can i do this in jQuery?
You can use the jEditable plugin
Or you can start something similar pretty simply by yourself too, with something like this:
$('span.editable').click(function() {
var input = $('<input type="text" />', {
value: $(this).text()
}).click(function() {
$.get('editsave.php?tekstny=' + $(this).value(), function(response) {
var span = $('span', {
text: response
});
$(this).replaceWith(span);
});
});
$(this).replaceWith(input);
});
Editable header or Button by clicking on edit button, type your own text and click on Ok to replace your text.
function editable() {
var h1 = document.getElementsByTagName("H1")[0];
var att = document.createAttribute("contenteditable");
att.value = "true";
h1.setAttributeNode(att);
}
function noteditable() {
var h1 = document.getElementsByTagName("H1")[0];
var att = document.createAttribute("contenteditable");
att.value = "flase";
h1.setAttributeNode(att);
}
function editable2() {
var input = document.getElementsByTagName("input")[0];
var att = document.createAttribute("type");
att.value = "text";
input.setAttributeNode(att);
}
function noteditable2() {
var input = document.getElementsByTagName("input")[0];
var att = document.createAttribute("type");
att.value = "button";
input.setAttributeNode(att);
}
$('.my-button').click(function() {
$(".my-textbox").focus()
});
$('.my-button2').click(function() {
$(".button").focus()
});
body {
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class='my-textbox' contenteditable="false">Hello World</h1>
<button class='my-button' onclick="editable()">Edit</button>
<button onclick="noteditable()">OK</button>
<br>
<br>
<br>
<input type="button" class="button" value="Hello World" />
<br>
<br>
<button class='my-button2' onclick="editable2()">Edit</button>
<button onclick="noteditable2()">OK</button>