Dynamic add button show wrong value jquery - javascript

<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>

Related

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.

How to add working dropify inputs dynamically

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.

localstorage how to save a button

I managed to save the text that is in the input field but the problem is that i do not know how to save the button. The buttons turn white when i click on them and the price of that seat will be visible in the input field. The price saves but the button does not stay white.
<script>
function changeBlue(element) {
var backgroundColor = element.style.background;
if (backgroundColor == "white") {
element.style.background = "blue";
add(-7.5)
} else {
element.style.background = "white";
add(7.5)
}
}
function add(val) {
var counter = document.getElementById('testInput').value;
var b = parseFloat(counter,10) + val;
if (b < 0) {
b = 0;
}
document.getElementById('testInput').value = b;
return b;
}
function save(){
var fieldValue = document.getElementById("testInput").value;
localStorage.setItem("text", fieldValue)
var buttonStorage = document.getElementsByClass("blauw").value;
localStorage.setItem("button", buttonStorage)
}
function load(){
var storedValue = localStorage.getItem("text");
if(storedValue){
document.getElementById("testInput").value = storedValue;
}
var storedButton = localStorage.getItem("button");
if(storedButton){
document.getElementsByClass("blauw").value = storedButton;
}
}
</script>
<body onload="load()">
<input type="text" id="testInput"/>
<input type="button" id="testButton" value="Save" onclick="save()"/>
<input class="blauw" type="button" id="testButton2" value="click me to turn white"
style="background-color:blue" onclick="changeBlue(this)">
<input class="blauw" type="button" id="testButton2" value="click me to turn white"style="background-color:blue" onclick="changeBlue(this)">
</body>
i made a small sample of what i want to do. And i do not want to use the Id's of the buttons because i have like 500 of them in a table.
That's because getElementsByClass (it's getElementsByClassName btw) returns a node list of all the elements with that class.
To make it work, you need to go through all the items in the list, using a for-loop, and set the value of each individual element to the localStorage-value.
See these links for more information:
Link 1
Link 2
Very small mockup to give you an idea:
(In the JS, I put in comments the lines of code you would be using for your situation.)
function changeValues() {
var list = document.getElementsByClassName("child"); //var list = document.getElementsByClassName("blauw");
for (var i=0; i<list.length; i++) {
list[i].innerHTML = "Milk"; //list[i].value = storedButton;
}
}
<ul class="example">
<li class="child">Coffee</li>
<li class="child">Tea</li>
</ul>
<p>Click the button to change the text of the first list item (index 0).</p>
<button onclick="changeValues()">Try it</button>

My JS/JQuery wont update my text field value

Hey guys I'm still fairly new to js and JQuery so I really need some help. I've tried several ways to do this. I basically need the value of my text box increased by 1 when a user clicks the plus button, and decreased by 1 when they click the minus button. I haven't coded for the minus as I haven't figured out the plus. My $('#itemQuant1').val(+1); call works, but stops at 1. Here is my js:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<script>
$(document).ready(function(){
var current_count = $('#itemQuant1').val();
var plus_count = current_count + 1;
var minus_count = current_count - 1;
//var minusCount = document.getElementById('minusItem').value;
$("#plusItem1").on('click', function(){
current_button = $(this);
if (current_button.attr('id') == "plusItem1")
{
$('#itemQuant1').val(+1);
//current_count.val() + plus_count;
//plus_count.val() + 1;
//$('#itemQuant1').value = current_count.value + 1;
}
});
});
</script>
Here is the html:
<body>
<div>
<table style= "border:solid;border-width:thin;">
<tr>
<td style= "border:solid;border-width:thin;"><p><input class"comfirmItem" type="checkbox">1-FLUE CONNECTOR ASSEMBLY PACKAGE (0005812) +$665.10<button id="plusItem1" class="more_Item" style="float:right;">+</button><button id="minusItem" class="less_Item" style="float:right;">-</button><input id="itemQuant1" class"itemCount" type="textbox" value=0 style="width:30px;text-align:center;margin-left:5px;margin-right:5px;float:right;"></p></td>
</tr>
<tr>
<td style= "border:solid;border-width:thin;"><p><input class"comfirmItem" type="checkbox">2-DUCT BOX ASSEMBLY (0005875) +$305.01<button id="plusItem" class="more_Item" style="float:right;">+</button><button id="minusItem" class="less_Item" style="float:right;">-</button><input id="itemQuant2" class"itemCount" type="textbox" style="width:30px;text-align:center;margin-left:5px;margin-right:5px;float:right;"></p></td>
</tr>
</table>
</div>
</body>
</html>
You just need to do this - http://jsfiddle.net/jayblanchard/rCM5d/
$('#itemQuant1').val( parseInt($('#itemQuant1').val()) + 1);
For up and down buttons it might be an idea to wrap all the button logic together like so: http://jsbin.com/kikitule/1/edit
Your HTML would look like this:
<button class="items-button" data-sum="1" data-target="#itemQuant1">+</button>
<button class="items-button" data-sum="-1" data-target="#itemQuant1">-</button>
<input id="itemQuant1" class="itemCount" type="textbox" value=0>
And JQuery like this:
$(document).ready(function(){
$(".items-button").on('click', function(){
var $button = $(this);
var $quantity = $($button.attr('data-target'));
var sum = parseInt($button.attr('data-sum'), 10);
var total = parseInt($quantity.val(), 10) + sum;
if (total < 0) {
total = 0;
}
$quantity.val(total)
});
});

Dynamically add remove rows using jQuery

I have a code like this...
<html>
<head>
<title>test</title>
<script type="text/javascript">
var counter = 2;
var idCounter= 3;
function addNew() {
if(counter<=5){
// Get the main Div in which all the other divs will be added
var mainContainer = document.getElementById('mainContainer');
// Create a new div for holding text and button input elements
var newDiv = document.createElement('div');
newDiv.id='divs'+counter;
// Create a new text input
var newText = document.createElement('input');
var newText1 = document.createElement('input');
newText.type = "input";
newText.id="ans"+(idCounter);
idCounter++;
newText1.type = "input";
newText1.id="ans"+(idCounter);
idCounter++;
// newText.value = counter;
// Create a new button input
var newDelButton = document.createElement('input');
newDelButton.type = "button";
newDelButton.value = "Remove";
// Append new text input to the newDiv
newDiv.appendChild(newText);
newDiv.appendChild(newText1);
// Append new button input to the newDiv
newDiv.appendChild(newDelButton);
// Append newDiv input to the mainContainer div
mainContainer.appendChild(newDiv);
counter++;
// Add a handler to button for deleting the newDiv from the mainContainer
newDelButton.onclick = function() {
mainContainer.removeChild(newDiv);
counter--;
}
}
else{
alert('Only 5 rows are allowed');
}}sss
function removeRow(divId){
mainContainer.removeChild(divId);
counter--;
}
</script>
</head>
<body >
<div id="mainContainer">
<div><input type="button" value="Add New Row" onClick="addNew()"></div>
<div id="div1"><input type="text" id="ans1"><input type="text" id="ans2"><input type="button" value="Remove" onClick ="javascript:removeRow(div1);"></div>
</div>
</body>
</html>
I want to achieve the same using jQuery.I also need the values entered in each of these textboxes.Please help.
Okay, because I had nothing better to do, and, to be honest, I was curious, I put this together. As implied in my comment, above, I didn't particularly like the way you had it laid out, so I used the following (x)html:
<form action="#" method="post">
<fieldset id="rows">
<ul>
<li>
<input type="text" id="ans1" name="ans1" />
<input type="text" id="ans2" name="ans2" />
</li>
</ul>
</fieldset>
<fieldset id="controls">
<button id="addRow">add</button>
<button id="removeRow" disabled>remove</button>
</fieldset>
</form>
With the following jQuery (although I've clearly not optimised, or refined it, but it should meet your requirements):
$(document).ready(
function(){
$('#addRow').click(
function() {
var curMaxInput = $('input:text').length;
$('#rows li:first')
.clone()
.insertAfter($('#rows li:last'))
.find('input:text:eq(0)')
.attr({'id': 'ans' + (curMaxInput + 1),
'name': 'ans' + (curMaxInput + 1)
})
.parent()
.find('input:text:eq(1)')
.attr({
'id': 'ans' + (curMaxInput + 2),
'name': 'ans' + (curMaxInput + 2)
});
$('#removeRow')
.removeAttr('disabled');
if ($('#rows li').length >= 5) {
$('#addRow')
.attr('disabled',true);
}
return false;
});
$('#removeRow').click(
function() {
if ($('#rows li').length > 1) {
$('#rows li:last')
.remove();
}
if ($('#rows li').length <= 1) {
$('#removeRow')
.attr('disabled', true);
}
else if ($('#rows li').length < 5) {
$('#addRow')
.removeAttr('disabled');
}
return false;
});
});
JS Fiddle demo of the above
I'm not, however, sure what you mean by:
I also need the values entered in each of these textboxes.
If you can explain what that means, or how you want them to be available (and, ideally, why they're not already available to you) I'll do my best to help.
I have a solution which will help you use here is the code
<script type="text/javascript" src="js/jquery.js"></script>
<script type = 'text/javascript'>
var newRowNum = 1;
var project_id ;
$(function() {
$('#addnew').click(function()
{
newRowNum++; // This is counter
//var i = 0;
///////// <a> <td> <tr>
var addRow = $(this).parent().parent();
///////// In the line below <tr> is created
var newRow = addRow.clone();
$('input', addRow).val('');
$('td:first-child', newRow).html();
$('td:last-child', newRow).html('<a href="" class="remove span">Remove<\/a>');
var newID = 'project'+newRowNum;
var add = 'description'+newRowNum;
newRow.children().children().first('input').attr('id', newID).attr('name', newID);
newRow.children().children().eq(1).attr('id', add).attr('name', add);
$('#table').find('tr:last').after(newRow);
$('a.remove', newRow).click(function()
{
newRowNum--;
$('#table').find('tr:last').remove();
return false;
});
return false;
});
});
</script>
<table width="75%" border="0" align = "center" id = 'table'>
<tr>
<td align = "center">Project </td>
<td align = "center">Description</td>
<td align = "center">Add Row</td>
</tr>
<tr>
<td align = "center"><input type = 'text' size = '35'name = 'project[]' id="project" ></td>
<td align = "center"><input type = 'text'size = '55' name = "description[]" id = 'description'></td>
<td width = '10%'><a id="addnew" href= "" class = 'span'>Add</a></td>
</tr>
</table>
You can also give each text box unique name if you change code like this and changing these two variables
var newID = 'project'+newRowNum;
var add = 'description'+newRowNum;
if you use the first method i shown here it will be easy to post data using array. That's all.

Categories

Resources