create div dynamically by passing css id and class to jquery method - javascript

I have div which needs to be repeated(create dynamically) on a button click.i have a working code,but it needs to be used many places across pages so i would like to make it a generic one,like i need to pass only particular div id as an input parameter to that method.
function textbox_add(id){
console.log(id)
var counter = 0;
$('#'+id).on('click','.newField', function () {
console.log(counter);
if(counter >= 3){
alert("Reached Maximum");
return false
}
var newthing=$('div.addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').end();
$('#'+id).append(newthing);
counter++;
});
$('#'+id).on('click','.remove', function () {
if (counter == 0)
{
return false
}
$(this).parent().remove();
counter--;
});
}
if i use it outside the method it works perfect.The goal is to create 4 text boxes dynamically and if i remove it should remove one by one.
here is my fiddle
Demo
Issues facing when i place inside method are:
On first click it creates single div on second click it creates two div's then continues for further click's.
On clicking remove it works like create.
when i click new again it creates the total of removed,created(earlier) all the div's.
I am not able to find where am missing.

I am not too sure what you are trying to do with the id (I assume it is your div id) that you are adding but you can try replacing your counter with a count of the elements:
function textbox_add(id){
$('#'+id).on('click','.newField', function () {
if($("#" + id + " > .addNew").length >= 4){
alert("Reached Maximum");
return false
}
var newthing=$('div.addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').end();
$('#'+id).append(newthing);
});
$('#'+id).on('click','.remove', function () {
if ($("#" + id + " > .addNew").length == 1)
{
return false
}
$(this).parent().remove();
});
}
textbox_add('test');
working Fiddle
OP basically wants an onclick(html) on the add button, like:
function textbox_add(id) {
if ($("#" + id + " > .addNew").length >= 4) {
alert("Reached Maximum");
return false;
}
var newthing = $('#'+id+' .addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').attr('onclick','').end();
$('#' + id).append(newthing);
$("#" + id + " > .addNew").on('click', '.remove', function () {
if ($("#" + id + " > .addNew").length === 1) {
return false;
}
$(this).parent().remove();
});
}
working codePen

It works fine, fiddle
You need to pass a wrapper id since you're cloning the .addNew content.
Example:
<div class="container" id="test">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
JS
textbox_add('test');

Your code was actually working well when you use id as selector, but worked wrong (adding multiple times new inputs for example) when you were using class as selector (because multiple elements share the same class).
I have edited it so you can use with id and class selectors:
HTML
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" />
<br />
<br />
</div>
</div>
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" />
<br />
<br />
</div>
</div>
<div id="other_container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" />
<br />
<br />
</div>
</div>
JS
function textbox_add(selector){
console.log(selector);
var max_allowed = 3;
$(selector).on('click','.newField', function () {
console.log($(this).parents(selector).find(".addNew").length);
if($(this).parents(selector).find(".addNew").length > max_allowed){
alert("Reached Maximum");
return false
}
var newthing=$('div.addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').end();
console.log($(this).parents(selector));
$(this).parents(selector).append(newthing);
});
$(selector).on('click','.remove', function () {
if (!$(this).parents(selector).find(".addNew").length > 1){
return false
}
$(this).parent().remove();
});
}
textbox_add(".container");
textbox_add("#other_container");
And here is the working JSFiddle.

I think that this is not the correct way to approach the problem, but the OP really wants to do it this way.
HTML
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" onClick="textbox_add(this)" />
<br />
<br />
</div>
</div>
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" onClick="textbox_add(this)"/>
<br />
<br />
</div>
</div>
JS
function textbox_add(element){
var max_allowed = 3;
if($(element).parents(".container").find(".addNew").length > max_allowed){
alert("Reached Maximum");
return false
}
var newthing = $('div.addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').attr('onclick','textbox_remove(this)').unbind('click').end();
$(element).parents(".container").append(newthing);
}
function textbox_remove(element){
if (!$(element).parents(".container").find(".addNew").length > 1){
return false
}
$(element).parent().remove();
}
Working JSFiddle

I think this might be what you are trying to do. The main thing I'm not sure of is what you intend to pass in as the id parameter. But tell me if this fills the bill.
http://jsfiddle.net/abalter/xdsacvdm/12/
html:
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" />
<br />
<br />
</div>
</div>
JavaScript:
$('#createField').on('click', function () {
//alert('new field clicked');
var el = createField('some-id', $('#generator').val());
$('.container').append(el);
});
function createField(id, text) {
var numFields = $('.container').find('.added').length;
if (numFields>3)
{
alert("Maximum reached");
return false;
}
var $outerDiv = $('<div>').addClass('newOne').addClass('added').attr('id', id);
var $textBox = $('<input>').attr({'type': 'text','value': text});
var $button = $('<input>').attr({'type': 'button' , 'value': 'Remove Field!'});
$outerDiv.append($textBox);
$outerDiv.append($button).append('<br/>').append('<br/>');
$button.on('click', function(){
$(this).closest('div').remove();
});
return $outerDiv;
}

Related

How to add new element with some changes on clicking a button until a specific number?

HTML code:
<input type='text' id='element1' />
<button id='addNew'>Add New</button>
I want each time on clicking the button a new input is created but with number increasing like :
<input type='text' id='element2' />
<input type='text' id='element3' />
..
..
<input type='text' id='element8' />
Until number 8 , each time I click the button an input is created with increased number.
$('#addNew').click(function(){
//Create new element if it's not greater than 8
});
Assuming some inputs exist in the current DOM:
The function count increments +1 in every call.
The function count starts with the existing inputs $('[type="text"]').length.
var count = function() {
return (count.i = (count.i || $('[type="text"]').length) + 1);
}
$('#addNew').click(function(){
var i = count();
if (i > 8) return;
$('body').append($(`<input type='text' id='element${i}' value="${i}"/><p>`));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='element1' value="1" />
<p>
<button id='addNew'>Add New</button>
$('#addNew').click((function(){
var count = 0;
return function() {
if(count < 8) {
//Create new element
}
count++
}
})());
See JavaScript closures: https://www.w3schools.com/js/js_function_closures.asp
I wouldn't recomment creating id's like this.
var count =1;
$('#addNew').click(function(){
if(count<8){
$("<input type='text' id='element"+(count+1)+"'/>").insertAfter('#element'+(count++));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='element1' />
<button id='addNew'>Add New</button>
$('#addNew').click(function(){
var last_element = $(document).find('.element').last();
var new_element = last_element.clone();
var new_element_id = 'element' +(parseInt(last_element.attr('id').replace('element', ''))+1);
new_element.
attr('id', new_element_id).
insertAfter(last_element);
//for display purposes
new_element.val(new_element_id);
});
.element{
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="element1" class="element" />
<button type="button" id="addNew">Add New</button>
Try this one:
HTML:
<ul class="jsEleList">
<li><input type='text' id='element1' /></li>
</ul>
<button class="jsAddNewBtn">Add New</button>
JS:
$(document).ready(function(){
var index = 2;
$(".jsAddNewBtn").on('click', function(){
if(index <= 8) {
var data = $(".jsEleList li").first().find('input').clone();
data.attr('id', 'element' + index);
var li = $('<li>').append(data);
$(".jsEleList").append(li);
}
index++;
});
});
Also follow the naming conventions of class names that specifically used for only js operations
Hope this may help you.

jquery on click change only this input value or link data attruibe from a loop

I have a php loop that call products from database. there is a quantity input field and a ajax add to cart button.
Now ajax add cart function get product id and quantity from the add cart link data attribute. So I want that when I change the quantity field value the add cart link data-quantity will changed automatically. So I can add sent the product quantity to cart.
I tried to do this but unfortunately its change all products quantity on click, because of same class. there is any why to do this that only change the quantity where I clicked?
maybe product id class work here? but how I set a dynamic product id in jquery?
here is my code:
HTML
<div class="row">
<div class="col-md-4">
<img src="img1.jpg" /><br />
<h2>Product 1</h2>
<button class="button">+</button>
<button class="button">-</button>
<input type="number" class="input" value="1" min="1" />
Add to Cart
</div>
<div class="col-md-4">
<img src="img2.jpg" /><br />
<h2>Product 2</h2>
<button class="button">+</button>
<button class="button">-</button>
<input type="number" class="input" value="1" min="1" />
Add to Cart
</div>
<div class="col-md-4">
<img src="img3.jpg" /><br />
<h2>Product 3</h2>
<button class="button">+</button>
<button class="button">-</button>
<input type="number" class="input" value="1" min="1" />
Add to Cart
</div>
<div class="col-md-4">
<img src="img4.jpg" /><br />
<h2>Product 4</h2>
<button class="button">+</button>
<button class="button">-</button>
<input type="number" class="input" value="1" min="1" />
Add to Cart
</div>
</div>
Jquery
<script>
$(function() {
$(".button").on("click", function() {
var $button = $(this);
var oldValue = $('.input').val();
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 1) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
}
}
$('a.add-to-cart').attr('data-quantity', newVal);
$('.input').val(newVal);
});
});
</script>
CodePen: https://codepen.io/alshedupur/pen/KmMxJv
Please don't push minus before give me a solution. Maybe you know this, but I don't know. If you share your knowledge it will help me and maybe others too.
You use selector that matches all inputs as they share the class, you can either push an unique id per item or you can use selector to find only items within the same container.
E.g.
$(function() {
$(".button").on("click", function() {
var $button = $(this);
var $parent = $button.parent();
var oldValue = $parent.find('.input').val();
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 1) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
}
}
$parent.find('a.add-to-cart').attr('data-quantity', newVal);
$parent.find('.input').val(newVal);
});
});

Getting all the values inside the Div

I have a div that has multiple input fields. My HTML looks like this:
<div id="mainDiv">
<input type="text" id="price" /> <br/>
<input type="text" id="tax" />
<input type="text" id="others" />
</div>
<img src="img/img.gif" onclick="getAllValues();" />
After I click the image, it must get all the values inside the mainDiv. How can I do this?
$("#getallvalues").click(function() {
var values = $("#mainDiv input").map(function() {
return $(this).val()
}).get().join(",");
console.log(values)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainDiv">
<input type="text" id="price" /> <br/>
<input type="text" id="tax" />
<input type="text" id="others" />
</div>
<img src="img/img.gif" id="getallvalues" />
Loop through each input then get the value and use .map()
var price = 0;
var tax = 0;
var others = 0;
$("#getallvalues").click(function() {
$("#mainDiv input").each(function() {
if ($(this).attr("id") == "price") {
price = $(this).val()
}
if ($(this).attr("id") == "tax") {
tax = $(this).val()
}
if ($(this).attr("id") == "others") {
others = $(this).val()
}
})
console.log("price " + price)
console.log("tax " + tax)
console.log("others " + others)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainDiv">
<input type="text" id="price" /> <br/>
<input type="text" id="tax" />
<input type="text" id="others" />
</div>
<img src="img/img.gif" id="getallvalues" />
You can use .map() to iterate over element and return the value in call back along with .get() to get them in array:
function getAllValues(){
$('#mainDiv input').map({
return this.value;
}).get(); // Output: ["priceval","taxval","otherval"]
}
You can use above array to create the data in whichever format(csv,json,etc) you want for further processing.
Loop through all the inputs in mainDiv
$('#mainDiv input').each(function(){
// Do what ever
})
Another way of doing this is like follows:
$('#mainDiv').find('input').each(function (index, element) {
var yourValue = element.value; // or $(element).val();
// And rest of your code
});
$('#mainDiv input').each(function(){
console.log(this.val());
})

Issue on Checking Multi Inputs Calculation Using each()

Can you please take a look at this Demo and let me know why I am not able to do the calculation check using the each iterator?
As you can see I tried to use :
if (!parseInt($(this).val()) === ((parseInt($(this).closest('div').find('.upper').text())) - parseInt($(this).closest('div').find('.lower').text()))) {}
Which it didnt work then I used this :
if (!parseInt($(this).val()) === ((parseInt($(this).prev('.upper').text())) - parseInt($(this).prev('.lower').text()))) {
but still not validating the input?
I'm not sure if that what you want to achieve, take a look at following example :
$('#test').on('click', function (e) {
$("input").each(function () {
if ($(this).val().length === 0)
{
$(this).addClass('input-error');
} else {
var upper = parseInt($(this).prev().prev().text());
var lower = parseInt($(this).prev().text());
var current_value = parseInt($(this).val());
if (current_value != (upper-lower)){
$(this).addClass('input-error');
}else{
$(this).removeClass('input-error');
}
}
});
});
.input-error {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="upper">5</div>
<div class="lower">2</div>
<input type="text" id="txt1">
<hr />
<div class="upper">7</div>
<div class="lower">3</div>
<input type="text" id="txt2">
<hr />
<div class="upper">200</div>
<div class="lower">66</div>
<input type="text" id="txt3">
<hr />
<br />
<button type='button' id="test">Test</button>

How Could i rearrange textboxes which are named as array index

i am working on a project in which i have to render rows dynamically . but user could also delete that row have a look at my current working
JQuery
var counter = 1;
function addrow() {
var textbox = "<div id='rows" + counter + "'> </br><label> Option : </label><input type='text' name='Answers[" + counter + "]' class='ahsan required' />Remove</div>";
var form = $("#form").valid();
if (form) {
$("#TextBoxesGroup").append(textbox);
counter++;
}
else {
return false;
}
}
html
<div id="TextBoxesGroup" style="margin-left: 100px;">
<div id="rows0">
</br><label>
Option :
</label>
<input type='text' name='Answers[0]' class='ahsan required' />Remove
</div>
</div>
<div>
<input type="button" value="Add another row" onclick="addrow();" class="qa-adbtn" id='addButton' /></div>
Now , if i have 10 rows there names will be Answers[0,1,2,3,4,5] . I want to remove input when i click on remove anchor and also reoder all textbox's name
For Example if i remove input at 4th index then all textbox automatically get re arranged . Can i Do it Please Help me and Thanks in Advance
You can make it without counter. This way your answers will be always ordered in the array starting by zero.
Here's a plausible solution:
$(function(){
$("#form").validate();
this.addrow = function() {
if ($("#form").valid()) {
var textbox = "<div> </br><label> Option : </label><input type='text' name='Answers["+$("#TextBoxesGroup div").length+"]' class='ahsan required' /><a class='remove-me' href='#'>Remove</a></div>";
$("#TextBoxesGroup").append(textbox);
$('.remove-me').click(function(){
$(this).parent().remove();
return false;
});
}
else {
return false;
}
}
this.addrow();
});
and the html is simple like this:
<form id="form">
<div id="TextBoxesGroup" style="margin-left: 100px;"></div>
<div>
<input type="button" value="Add another row" onclick="addrow();" class="qa-adbtn" id='addButton' />
</div>
</form>

Categories