How to add working dropify inputs dynamically - javascript

I have form which gets clone when user click on add more button .
This is how my html looks:
<div class="col-xs-12 duplicateable-content">
<div class="item-block">
<button class="btn btn-danger btn-float btn-remove">
<i class="ti-close"></i>
</button>
<input type="file" id="drop" class="dropify" data-default-file="https://cdn.example.com/front2/assets/img/logo-default.png" name="sch_logo">
</div>
<button class="btn btn-primary btn-duplicator">Add experience</button>
...
</div>
This my jquery part :
$(function(){
$(".btn-duplicator").on("click", function(a) {
a.preventDefault();
var b = $(this).parent().siblings(".duplicateable-content"),
c = $("<div>").append(b.clone(true, true)).html();
$(c).insertBefore(b);
var d = b.prev(".duplicateable-content");
d.fadeIn(600).removeClass("duplicateable-content")
})
});
Now I want every time user clicks on add more button the id and class of the input type file should be changed into an unique, some may be thinking why I'm doing this, it I because dropify plugin doesn't work after being cloned, but when I gave it unique id and class it started working, here is what I've tried :
function randomString(len, an){
an = an&&an.toLowerCase();
var str="", i=0, min=an=="a"?10:0, max=an=="n"?10:62;
for(;i++<len;){
var r = Math.random()*(max-min)+min <<0;
str += String.fromCharCode(r+=r>9?r<36?55:61:48);
}
return str;
} var ptr = randomString(10, "a");
var className = $('#drop').attr('class');
var cd = $("#drop").removeClass(className).addClass(ptr);
Now after this here is how I initiate the plugin $('.' + ptr).dropify().
But because id is still same I'm not able to produce clone more than one.
How can I change the id and class everytime user click on it? is there a better way?

Working Fiddle.
Problem :
You're cloning a div that contain already initialized dropify input and that what create the conflict when you're trying to clone it and reinitilize it after clone for the second time.
Solution: Create a model div for the dropify div you want to clone without adding dropify class to prevent $('.dropify').dropify() from initialize the input then add class dropify during the clone.
Model div code :
<div class='hidden'>
<div class="col-xs-12 duplicateable-content model">
<div class="item-block">
<button class="btn btn-danger btn-float btn-remove">
X
</button>
<input type="file" data-default-file="http://www.misterbilingue.com/assets/uploads/fileserver/Company%20Register/game_logo_default_fix.png" name="sch_logo">
</div>
<button class="btn btn-primary btn-duplicator">Add experience</button>
</div>
</div>
JS code :
$('.dropify').dropify();
$("body").on("click",".btn-duplicator", clone_model);
$("body").on("click",".btn-remove", remove);
//Functions
function clone_model() {
var b = $(this).parent(".duplicateable-content"),
c = $(".model").clone(true, true);
c.removeClass('model');
c.find('input').addClass('dropify');
$(b).before(c);
$('.dropify').dropify();
}
function remove() {
$(this).closest('.duplicateable-content').remove();
}
Hope this helps.

Try this:
$(function() {
$(document).on("click", ".btn-duplicator", function(a) {
a.preventDefault();
var b = $(this).parent(".duplicateable-content"),
c = b.clone(true, true);
c.find(".dropify").removeClass('dropify').addClass('cropify')
.attr('id', b.find('[type="file"]')[0].id + $(".btn-duplicator").index(this)) //<here
$(c).insertBefore(b);
var d = b.prev(".duplicateable-content");
d.fadeIn(600).removeClass("duplicateable-content")
})
});
Fiddle

This does what you specified with an example different from yours:
<div id="template"><span>...</span></div>
<script>
function appendrow () {
html = $('#template').html();
var $last = $('.copy').last();
var lastId;
if($last.length > 0) {
lastId = parseInt($('.copy').last().prop('id').substr(3));
} else {
lastId = -1;
}
$copy = $(html);
$copy.prop('id', 'row' + (lastId + 1));
$copy.addClass('copy');
if(lastId < 0)
$copy.insertAfter('#template');
else
$copy.insertAfter("#row" + lastId);
}
appendrow();
appendrow();
appendrow();
</script>

Try adding one class to all dropify inputs (e.g. 'dropify'). Then you can set each elements ID to a genereted value using this:
inputToAdd.attr('id', 'dropify-input-' + $('.dropify').length );
Each time you add another button, $('.dropify').length will increase by 1 so you and up having a unique ID for every button.

Related

Dynamic add button show wrong value jquery

<script type="text/javascript">
var i = 0;
var j = 1;
$("#add").click(function(){
++i;
var c = i + j;
$("#dynamicpre").append('<div class="dynamicfields mb-5"><h5>Track:' + c + '</h5></div>');
});
$(document).on('click', '.remove-tr', function(){
$(this).closest('.dynamicfields').remove();
});
</script>
In the above question I am simply append a value through c variable. Now, What happen here when I click on add button it show Track:2 but when I click on remove and click again on add button then it show Track:3 but I want to show Track:2. So, How can I do this? Please help.
Thank You
From your .remove-tr click code it seems that you will be having .remove-tr element inside .dynamicfields div then only your $(this).closest would work, so I have added .remove-tr button dymanically.
Check comments for explanation.
$("#add").click(function() {
// default track value
let c = 1;
// get last dynamicfields's h5 element inside #dynamicpre
let lastAdded = $("#dynamicpre .dynamicfields h5:last");
// check if there is any dynamicfields is there? if yes then only get track number
if (lastAdded.length) {
// get track number from last dynamicfields from its text
// get track text and replace Track: with empty value and convert it to number
c = 1 + Number(lastAdded.text().replace("Track:", ""));
}
// append new div with remove button
$("#dynamicpre").append('<div class="dynamicfields mb-5"><h5>Track:' + c + '</h5> <input type="button" class="remove-tr" value="remove" /> </div>');
});
$(document).on('click', '.remove-tr', function() {
$(this).closest('.dynamicfields').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<input type="button" id="add" value="add">
<div id="dynamicpre">
</div>
you have to -1 the value of "j" on removing function and also create a remove button at the end only and remove the last div on remove button click then it will work fine :
var i = 0;
var j = 1;
$("#add").click(function(){
++i;
var c = i + j;
$("#dynamicpre").append('<div class="dynamicfields mb-5"><h5>Track:' + c + '</h5></div>');
});
$(document).on('click', '.remove-tr', function(){
if(j>=1){
i --;
}
$(".dynamicfields:last-child").remove()
});
<input value="add" type="button" id="add" />
<div id="dynamicpre">
hammad
</div>
<input value="remove" type="button" class="remove-tr" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>

show/ hide function in one button (hide_btn)

I have to program an web-app (Mäxle) for an exam and I am a total beginner.
Hopefully s.o. can help me with that.
index.html (buttons):
<div id="buttons_container" class="container">
<div class="row">
<br>
<button type="button" id="shuffle_btn" class="btn btn-primary">shuffle</button>
<button type="button" id="hide_btn" class="btn btn-success">hide / show</button>
</div>
</div>
function.js:
function test_shuffle () {
var arr = ["11",
"21","22",
"31","32","33","34","35","36",
"41","42","43","44","45","46",
"51","52","53","54","55","56",
"61","62","63","64","65","66"];
var max_index = arr.length -1;
var zufall = Math.floor(Math.random() * max_index) + 1 ;
var final = arr [zufall];
$('#ausgabe_shuffle').html(final);
}
function test_hide () {
$("hide_btn").click(function(){
$("--").hide();
});
}
event.js:
$(document).ready(function() {
$('body').on('click', '#shuffle_btn', function (e) {
test_shuffle ();
});
$('body').on('click', '#hide_btn', function (e) {
$("*").html("--");
test_hide ();
});
});
When I click the hide_btn right now, everthing disappears and this "--" will be displayed. The click works but I want to hide the numbers I got from the array, eg. "32"
Thank you very much in advance
$("*").html("--"); // This overrides all html inside body and prints "--".
You can replace this with
$("#ausgabe_shuffle").toggle(); // This will show or hide your values printed inside #ausgabe_shuffle tag.

button onclick id change not working in Html using javascript

I wanted to change ID of textarea using onclick button. So I created two buttons across my field. Each on click run a function.
Issue: It just replace my id first time and second time when i click on second button it throws error saying "Uncaught TypeError: Cannot set property 'id' of null at ti_pos_fun (index.html:491)"
HTML code-
<div>
<label for="usr">ti:</label> <i class="glyphicon glyphicon-check" onclick="ti_pos_fun()"></i> <i class='glyphicon glyphicon-unchecked' onclick="ti_neg_fun()"></i>
</div>
I am trying to use two buttons- example
Now when you click check button- ti runs the onclick function "ti_pos_fun".
Function are as follows
function ti_neg_fun ()
{
var a = document.getElementById("jsel");
a.id = "ti_neg";
//$("#ti_neg").text('angry');
document.getElementById('ti_neg').innerHTML = 'angry';
}
function ti_pos_fun ()
{
var a = document.getElementById("jsel");
a.id = "ti_pos";
document.getElementById('ti_pos').innerHTML = 'hahahahaha';
//$("#ti_pos").text('hahahaha');
}
Textarea code where these ids are going & their text.
<div class="col-md-10">
<H3> textarea</H3>
<textarea id = "jsel"></textarea>
</div>
You click on button 1 - check button
It gets id and text in textarea
When you click on button 2- uncheck button
It fails
Its not working on 2nd click because you are overwriting the id of that element
//a.id = "ti_neg";
so on 2nd click there is no element with id jsel and below statement will return null and it will not work.
document.getElementById("jsel");
function ti_neg_fun ()
{
var a = document.getElementById("jsel");
//a.id = "ti_neg";
//$("#ti_neg").text('angry');
document.getElementById('jsel').innerHTML = 'angry';
}
function ti_pos_fun ()
{
var a = document.getElementById("jsel");
//a.id = "ti_pos";
document.getElementById('jsel').innerHTML = 'hahahahaha';
//$("#ti_pos").text('hahahaha');
}
<div>
<label for="usr">ti:</label> <i class="glyphicon glyphicon-check" onclick="ti_pos_fun()">1</i> <i class='glyphicon glyphicon-unchecked' onclick="ti_neg_fun()">2</i>
</div>
<div class="col-md-10">
<H3> textarea</H3>
<textarea id = "jsel"></textarea>
</div>
That's because the ID isn't jsel anymore you need something like this, if it can't find jsel check for the ID the other function set and visa versa. EDIT: added snip that works.
function ti_pos_fun ()
{
var a = document.getElementById("jsel");
if (a != null){
a.id = "ti_pos";
document.getElementById('ti_pos').innerHTML = 'hahahahaha';
//$("#ti_pos").text('hahahaha');
}else{
var a = document.getElementById("ti_neg");
a.id = "ti_pos";
document.getElementById('ti_pos').innerHTML = 'hahahahaha';
//$("#ti_pos").text('hahahaha');
}
}
function ti_neg_fun ()
{
var a = document.getElementById("jsel");
if(a != null){
a.id = "ti_neg";
//$("#ti_neg").text('angry');
document.getElementById('ti_neg').innerHTML = 'angry';
}else{
var a = document.getElementById("ti_pos");
a.id = "ti_neg";
//$("#ti_neg").text('angry');
document.getElementById('ti_neg').innerHTML = 'angry';
}
}
<div>
<label for="usr">ti:</label> <i class="glyphicon glyphicon-check" onclick="ti_pos_fun()">postitive</i> <i class='glyphicon glyphicon-unchecked' onclick="ti_neg_fun()">negative</i>
</div>
<div class="col-md-10">
<H3> textarea</H3>
<textarea id = "jsel"></textarea>
</div>

how to add attribute name in summernote click to edit

I want to add element attribute name in summernote click to edit
html :
<button id="edit" class="btn btn-primary" onclick="edit()" type="button">Edit 1</button>
<button id="save" class="btn btn-primary" onclick="save()" type="button">Save 2</button>
<div class="click2edit">click2edit</div>
javascript:
var edit = function() {
$('.click2edit').summernote({focus: true});
};
var save = function() {
var makrup = $('.click2edit').summernote('code');
$('.click2edit').summernote('destroy');
};
doc :
http://summernote.org/examples/#click-to-edit
You can do like this. Just find the text area add the name attribute.Hope it work.
var edit = function() {
$('.click2edit').summernote({focus: true});
$('.note-editor.note-frame.panel.panel-default').find('textarea').attr('name','mytextarea');
};
I don't think you need anything fancy here.
Use attr() on summernote selector
$('.summernote').attr('name', 'content');
Here, I assume that $('.summernote') is selector of editor applied.
Example, shows how to get instance of editor
$("#id").on("summernote.init", function(e, layoutInfo) {
// get $editor element
var $editor = layoutInfo.editor();
// add id attribute in $editor element
$editor.attr('id', $(this).attr('id') + "-of-example");
}).summernote(
// summernote options..
);
var edit = function() {
$('.click2edit').summernote({focus: true});
$('.note-editor').find('textarea').attr('name','mytextarea');
};

How to add array items to <li> Jquery

I'm working on something really simple, a short quiz, and I am trying to make the items I have listed in a 2-d array each display as a <li>. I tried using the JS array.join() method but it didn't really do what I wanted. I'd like to place them into a list, and then add a radio button for each one.
I have taken the tiny little leap to Jquery, so alot of this is my unfamiliarity with the "syntax". I skimmed over something on their API, $.each...? I'm sure this works like the for statement, I just can't get it to work without crashing everything I've got.
Here's the HTML pretty interesting stuff.
<div id="main_">
<div class="facts_div">
<ul>
</ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me">
</form>
</div>
And, here is some extremely complex code. Hold on to your hats...
$(document).ready (function () {
var array = [["Fee","Fi","Fo"],
["La","Dee","Da"]];
var q = ["<li>Fee-ing?","La-ing?</li>"];
var counter = 0;
$('.myBtn').on('click', function () {
$('#main_ .facts_div').text(q[counter]);
$('.facts_div ul').append('<input type= "radio">'
+ array[counter]);
counter++;
if (counter > q.length) {
$('#main_ .facts_div').text('You are done with the quiz.');
$('.myBtn').hide();
}
});
});
Try
<div id="main_">
<div class="facts_div"> <span class="question"></span>
<ul></ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me" />
</form>
</div>
and
jQuery(function ($) {
//
var array = [
["Fee", "Fi", "Fo"],
["La", "Dee", "Da"]
];
var q = ["Fee-ing?", "La-ing?"];
var counter = 0;
//cache all the possible values since they are requested multiple times
var $facts = $('#main_ .facts_div'),
$question = $facts.find('.question'),
$ul = $facts.find('ul'),
$btn = $('.myBtn');
$btn.on('click', function () {
//display the question details only of it is available
if (counter < q.length) {
$question.text(q[counter]);
//create a single string containing all the anwers for the given question - look at the documentation for jQuery.map for details
var ansstring = $.map(array[counter], function (value) {
return '<li><input type="radio" name="ans"/>' + value + '</li>'
}).join('');
$ul.html(ansstring);
counter++;
} else {
$facts.text('You are done with the quiz.');
$(this).hide();
}
});
//
});
Demo: Fiddle
You can use $.each to iterate over array[counter] and create li elements for your options:
var list = $('.facts_div ul');
$.each(array[counter], function() {
$('<li></li>').html('<input type="radio" /> ' + this).appendTo(list);
}
The first parameter is your array and the second one is an anonymous function to do your action, in which this will hold the current element value.
Also, if you do this:
$('#main_ .facts_div').text(q[counter]);
You will be replacing the contents of your element with q[counter], losing your ul tag inside it. In this case, you could use the prepend method instead of text to add this text to the start of your tag, or create a new element just for holding this piece of text.

Categories

Resources