jQuery clone() input value function - javascript

I have created a clone function to clone a selection of elements. I have managed to get the basics of the clone function working. CLICK HERE
I have a bug in this function. When the user types text into the input field, it clones the last inputted text and changes the text value for all cloned items.
$('.add-item').on('click', function() {
var value = $('input').val();
if ($('#items-field').val()) {
$('.list-items p').text(value)
$('.list-items:first').clone().appendTo("#items").addClass('isVisible');
$('input').val('');
event.preventDefault();
}
})
Does anyone know how this problem can be resolved?

Clear the value of inputs after you clone(). You can use the find() method to get all the inputs inside the cloned item.
var c = $('.list-items:first').clone();
c.find("input").val(""); // find all inputs and clear
c.appendTo("#items").addClass('isVisible');
Here is a working jsbin sample
Also, In your code, you are reading the input value and setting it to all the p tags's text. You should be setting it only to the p tag of the cloned div.
$(function(){
$('.add-item').on('click', function(e) {
event.preventDefault();
var value = $('#items-field').val();
if (value!="") {
var c = $('.list-items:first').clone();
c.find("input").val(""); // find all inputs and clear
c.appendTo("#items").addClass('isVisible');
c.find("p").text(value);
}
});
})
Here is a working sample of the complete solution

Related

Form values are overwritten after change

I have a form that shows up when each row in a table is double clicked. The values of this form can be updated and the form should be submitted with all row changes. But each time I double click on a row and edit the values of that form for that row, the previous values I had changed get overwritten. In order to work around this, I tried adding all the changes to a map with the row id as the key and the values of the form as the value. But the form still won't update with the new values. Here is a fiddle to demonstrate what I mean:
https://jsfiddle.net/4fr3edk7/2/
If I double click on the row that says "Adam Smith" and change that name to John Doe, when I double click on the second row and then double Click on "Adam Smith" again, it should say "John" on the first textbox and "Doe" on the second one. But the new value never seems to save.
This code snippet loops through each key, then loops through each value of that key:
for(var i = 0; i<key.length; i++){
var getval = globalchanges[key[i]];
for(var k=0; k<getval.length; k++){
$("#input1").val(getval[0]);
$("#input2").val(getval[1]);
}
}
How can I get the new changes to save? (The table rows don't have to show the changes, just the textbox values). Any help would be appreciated.
First, as mentioned by #Taplar you are binding the click event multiple times. Your approach is close enough, the idea of storing the changes is valid. You should have 2 functions, store the changes on button click and the second one to retrieve the changes by id.
Updated Fiddle
This function will get the values of the form and will store in on a global object
function setMap(id){
var firstrow = $("#input1").val();
var secondrow = $("#input2").val();
globalchanges[id] = [firstrow,secondrow];
}
This other function will check if the global object has values for the passed id, if not, it will use the values on the row
function getMap(id, tr){
if(globalchanges[id] != undefined && globalchanges[id].length == 2){
$("#input1").val(globalchanges[id][0]);
$("#input2").val(globalchanges[id][1]);
}
else{
$("#input1").val($(tr).find('td').eq(1).text());
$("#input2").val($(tr).find('td').eq(2).text());
}
}
Please note there are also changes on the dbclick and click events, they should be separated
$("#table tr").dblclick(function(){
$("#txtbox-wrapper").css({"display" : "block"});
var id = $(this).find('td').eq(0).text();
$('#id').val(id);
getMap(id,this);
});
$("#savebtn").click(function(){
var id = $('#id').val();
setMap(id);
});
And that we added and additional input to store the id on the form.
You are going to need to rethink your logic because of this part
$("#table tr").dblclick(function(){
$("#txtbox-wrapper").css({"display" : "block"});
var id = $(this).find('td').eq(0).text();
$("#input1").val($(this).find('td').eq(1).text());
$("#input2").val($(this).find('td').eq(2).text());
$("#savebtn").click(function(){
addToMap(id);
});
});
-Every time- you double click a table row you are adding a new click binding to the savebtn element. This means if you double click both rows, when you click that button it will execute addToMap for both ids. You may have other issues with your logic relying on only two other inputs for multiple rows, but this double/triple/+ binding is going to bite you.
There are few changes required in your logic as well as implementation.
1: Do not bind save event inside row click.
2: You are selecting the value in row double click event from td element. You need to update this element to keep your logic working
3: Keep track of which row is getting updated.
Updated Code
var globalchanges = {};
var rowSelected = null;
$("#table tr").dblclick(function() {
$("#txtbox-wrapper").css({
"display": "block"
});
rowSelected = $(this).find('td').eq(0).text();
$("#input1").val($(this).find('td').eq(1).text());
$("#input2").val($(this).find('td').eq(2).text());
});
$("#savebtn").click(function() {
addToMap(rowSelected);
});
function addToMap(row) {
var array = [];
var changes = {};
var firstrow = $("#input1").val();
var secondrow = $("#input2").val();
array.push(firstrow, secondrow);
globalchanges[row] = array;
makeChanges(row);
}
function makeChanges(row) {
var key = Object.keys(globalchanges);
console.log(key);
$("#table tr td").each(function(k, v) {
if ($(v).text() == key) {
$(v).next().html(globalchanges[row][0]);
$(v).next().next().html(globalchanges[row][1]);
globalchanges = {};
}
});
}
Working fiddle : https://jsfiddle.net/yudLxsgu/

Using jQuery to insert tags into box?

What I’m looking to create is something like the Stack overflow tag insert. I want to be able to type the tag into the insert box and when I click the ‘Add’ button, it adds it to the box above. I also want it to push the new tag into the ‘SelectedTags’ array. If the user removes it from the box, it'll need to be removed from the array. I guess I would need to push into the array first then populate the box based on the arrays content? I’ve tried creating it in JSFiddle but can’t get it working. Can someone help using the JSFiddle example? http://jsfiddle.net/uVxXg/117/
I assume this is what make it look like a tag?
$("#tags").tagit({
availableTags: SelectedTags
});
This is how you do it:
$(document).ready(function() {
var sampleTags = [];
$('#tags').tagit({
availableTags: sampleTags,
afterTagRemoved: function(evt, ui) {
console.log(ui.tagLabel)
for(var i = 0; i < sampleTags.length; i++) {
if (sampleTags[i] == ui.tagLabel) {
sampleTags.splice(i, 1); //Here is the update
}
}
}
});
$('form').submit(function(e) {
var inp = $('#tagInput').val();
$('#tagInput').val('');
$('#tags').tagit('createTag', inp);
sampleTags.push(inp);
e.preventDefault();
console.log(sampleTags)
});
$("#array").click(function(e){
console.log("MyArray",sampleTags)
})
});
Try out the fiddle, and when you add something to the SelectedTags array you will then have the tags as "find wile type" in the tags input.

Changing a dynamically created label's text with keyup() issue

I am creating a form dynamically and therefore edit the form elements’ properties. When attempting to change the label, assigning an auto-generated id works fine but when changing this label using the generated id, the function or keyup() from jQuery keeps calling all the previously created label id(s). this means when i want to edit one label, it ends up editing every label.
HTML
<input type="text" id="change-label"><br><br>
<button id="add-button">add label</button>
<div id="add-label"></div>
JavaScript/jQuery
$('#add-button').click(function(){
var div = document.createElement('div');
var textLabel = document.createElement('label');
var labelNode = document.createTextNode('untitled');
textLabel.appendChild(labelNode);
textLabel.id = autoIdClosure();
$('#change-label').val('untitled');
div.appendChild(textLabel);
$('#add-label').append(div);
});
var autoIdClosure = (function(){
var counter = 0;
var labelId = "textInputLabel";
return function(){
counter += 1;
var id = labelId + counter;
editLabelWrapper(id)
return id;
}
})();
function editLabelWrapper(id){
function editLabel(){
var value = $(this).val();
$("#"+id).text(value);
}
$("#change-label").keyup(editLabel).keyup();
}
I’ve already found an alternative using onkeyup="$('#'+globaID).text($(this).val());", but I need to understand what I was doing wrong so I can learn from it.
JSFiddle
I think you are overthinking the matter...
Instead of using an unique id, rather use classes, makes it easier to handle.
So change <div id="add-label"></div> to <div class="add-label"></div>
Then what you want to do is, when a value is given in #change-label you want it in the last div.add-label.
So the function will become this:
$("#change-label").on('keyup', function() {
$('.add-label:last').text( $(this).val() );
});
Next what you want to do is bind a function to #add-button. Once it gets clicked, we want to add a new div.add-label after the last one. And empty the #change-label. You can do that by using this function:
$('#add-button').on('click', function() {
$('.add-label:last').after('<div class="add-label"></div>');
$('#change-label').val('');
});
Updated Fiddle

jQuery++, problems on .selection()

everybody.
I have a little problem; I'm trying to build a WYSIWYG, but I encountered some problems.
I have a contenteditable div with id = desc2, and some buttons. Let's take, for example, the button "bold".
<div class="magic" magic_id="desc2">
<div class="magicbutton one" magic="[b]%s[/b]">
<span style="font-weight:bold;">Bold</span>
</div>
</div>
And I have some jQuery++ selection application in:
$('#desc2').on('mouseup', function() {
var selection = $(this).selection(),
text = $(this).text().substring(selection.start, selection.end);
console.log(text);
});
I have erased the other part of the script, because if I manage to get this to work, I'm done :D
So, as I was saying, if I do this, everything is good: I sleect a part on the div and on the console is outputted the content.
But this is not what I want to do. I wrote this:
$('.magicbutton.uno').on('click', function(){
var id = $(this).parent().attr("magic_id");
var selection = $("#"+id).selection(),
text = $("#"+id).text().substring(selection.start, selection.end);
console.log(text);
});
Everytime I click, it takes the ID of the div to change and should output the selected text, but it doesn't.
The code is the same, and i checked that $(this) in the first script is the same as $("#"+id) in the second.
What can I do? Thanks!
EDIT: jsFiddle
When DIV loses focus, selection is nullified. As a workaround, you could use data object:
DEMO
$('.magicbutton.one').on('click', function(){
var id = $(this).parent().attr("magic_id"); //id = desc2, i used this because i could have multiple forms in a page
var selection = $("#"+id).data('selection');
alert(selection);
}); //This doesn't work
$('#desc2').on('mouseup', function() {
var selection = $(this).selection(),
text = $(this).text().substring(selection.start, selection.end);
$(this).data('selection', text);
});

Recursive IDs and duplicating form elements

I have the following fiddle:
http://jsfiddle.net/XpAk5/63/
The IDs increment appropriately. For the first instance. The issue is when I try to add a sport, while it duplicates, it doesn't duplicate correctly. The buttons to add are not creating themselves correctly. For instance, if I choose a sport, then fill in a position, and add another position, that's all fine (for the first instance). But when I click to add another sport, it shows 2 positions right away, and the buttons aren't duplicating correctly. I think the error is in my HTML, but not sure. Here is the JS I am using to duplicate the sport:
$('#addSport').click(function(){
//increment the value of our counter
$('#kpSport').val(Number($('#kpSport').val()) + 1);
//clone the first .item element
var newItem = $('div.kpSports').first().clone();
//recursively set our id, name, and for attributes properly
childRecursive(newItem,
// Remember, the recursive function expects to be able to pass in
// one parameter, the element.
function(e){
setCloneAttr(e, $('#kpSport').val());
});
// Clear the values recursively
childRecursive(newItem,
function(e){
clearCloneValues(e);
});
Hoping someone has an idea, perhaps I've just got my HTML elements in the wrong order? Thank you for your help! I'm hoping the fiddle is more helpful than just pasting a bunch of code here in the message.
The problem is in your clearCloneValues function. It doesn't differentiate between buttons and other for elements that you do want to clear.
Change it to:
// Sets an element's value to ''
function clearCloneValues(element){
if (element.attr('value') !== undefined && element.attr('type') !== 'button'){
element.val('');
}
}
As #PHPglue pointed out in the comments above, when new positions are added, they are incorrectly replicated (I'm assuming here) to the newly cloned for
There is a similar problem with the add years functionality.
A quick fix would be to initialize a variable with a clone of the original form fields:
var $template = $('div.kpSports').first().clone();
Then change your addSport handler to:
$('#addSport').click(function () {
//increment the value of our counter
$('#kpSport').val(Number($('#kpSport').val()) + 1);
//clone the first .item element
var newItem = $template.clone();
…
});
However, there are no event bindings for the new buttons, so that functionality is still missing for any new set of form elements.
Demo fiddle
Using even a simple, naive string based templates the code can be simplified greatly. Linked is an untested fiddle that shows how it might be done using this approach.
Demo fiddle
The code was simplified to the following:
function getClone(idx) {
var $retVal = $(templates.sport.replace(/\{\{1\}\}/g, idx));
$retVal.find('.jsPositions').append(getItemClone(idx, 0));
$retVal.find('.advtrain').append(getTrainingClone(idx, 0));
return $retVal;
}
function getItemClone(setIdx, itemIdx) {
var retVal = itemTemplate.replace(/\{\{1\}\}/g, setIdx).replace(/\{\{2\}\}/g, itemIdx);
return $(retVal);
}
function getTrainingClone(setIdx, trainingIdx) {
var retVal = trainingTemplate.replace(/\{\{1\}\}/g, setIdx).replace(/\{\{2\}\}/g, trainingIdx);
return $(retVal);
}
$('#kpSportPlayed').on('click', '.jsAddPosition', function() {
var $container = $(this).closest('.kpSports');
var containerIdx = $container.attr('data_idx');
var itemIdx = $container.find('.item').length;
$container.find('.jsPositions').append(getItemClone(containerIdx, itemIdx));
});
$('#kpSportPlayed').on('click', '.jsAddTraining', function() {
var $container = $(this).closest('.kpSports');
var containerIdx = $container.attr('data_idx');
var trainIdx = $container.find('.advtrain > div').length;
$container.find('.advtrain').append(getTrainingClone(containerIdx, trainIdx));
});
$('#addSport').click(function () {
var idx = $('.kpSports').length;
var newItem = getClone(idx);
newItem.appendTo($('#kpSportPlayed'));
});

Categories

Resources