I am using jQuery to add and remove table rows for a collection of forms within another form in Symfony 4. This was not easy, but eventually made it work. With a macro in Twig I can get this rendered result:
<table>
<div id="document-list" data-prototype="
<tr>
<td>
<fieldset class="form-group">
<div id="program_programDocument___name__" novalidate="novalidate">
<div class="form-group"><input type="text" id="program_programDocument___name___name" name="program[programDocument][__name__][name]" required="required" class="form-control"/>
</div>
</div>
</fieldset>
</td>
<td>
<button type="button"class="remove-collection-widget"data-list="#remove-collection-widget">Remove</button>
</td>
</tr>" data-widget-tags="<div></div>">
</div>
</table>
<button type="button" class="add-another-collection-widget" data-list="#document-list">Add document</button>
I cleaned up this code as much as possible to make it readable. All the HTML within data-prototype="...." is how it should be. My code works (ish) together with some jQuery:
jQuery('.add-another-collection-widget').click(function(e) {
var list = jQuery(jQuery(this).attr('data-list'));
// Try to find the counter of the list or use the length of the list
var counter = list.data('widget-counter') | list.children().length;
// grab the prototype template
var newWidget = list.attr('data-prototype');
// replace the "__name__" used in the id and name of the prototype
// with a number that's unique to your emails
// end name attribute looks like name="contact[emails][2]"
newWidget = newWidget.replace(/__name__/g, counter);
// Increase the counter
counter++;
// And store it, the length cannot be used if deleting widgets is allowed
list.data('widget-counter', counter);
// create a new list element and add it to the list
var newElem = jQuery(list.attr('data-widget-tags')).html(newWidget);
newElem.appendTo(list);
});
$(function() {
$(document).on("click", ".remove-collection-widget", function() {
$(this).closest("tr").remove();
});
});
The problem is, the rendered result when added more form rows is that they don't actually end up within the table. You can see for yourself (JSFiddle) the result looks alright, but in reality it's not.
I am pretty sure it has to do with my jQuery, but I am stuck now and hope some of you can point out what is wrong.
Putting a div as a direct child of a table isn't proper HTML, which is what's tripping it up.
Move id="document-list" data-prototype="... to table element
Get rid of div inside table
Change data-widget-tags to tr instead of div
Remove wrapping tr from data-prototype
Solution
jQuery('.add-another-collection-widget').click(function(e) {
var list = jQuery(jQuery(this).attr('data-list'));
var counter = list.data('widget-counter') | list.children().length;
var newWidget = list.attr('data-prototype');
newWidget = newWidget.replace(/__name__/g, counter);
counter++;
list.data('widget-counter', counter);
var newElem = jQuery(list.attr('data-widget-tags')).html(newWidget);
newElem.appendTo(list);
});
$(function() {
$(document).on("click", ".remove-collection-widget", function() {
$(this).closest("tr").remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="document-list" data-prototype="
<td>
<fieldset class="form-group">
<div id="program_programDocument___name__" novalidate="novalidate">
<div class="form-group"><input type="text" id="program_programDocument___name___name" name="program[programDocument][__name__][name]" required="required" class="form-control"/>
</div>
</div>
</fieldset>
</td>
<td>
<button type="button"class="remove-collection-widget"data-list="#remove-collection-widget">Remove</button>
</td>" data-widget-tags="<tr></tr>">
</table>
<button type="button" class="add-another-collection-widget" data-list="#document-list">Add document</button>
Documentation
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table (see Permitted Content)
Related
I'm trying to use the .each() function to capture values from the inputs, however it only works with the inputs present in the DOM.
I am using jQuery to insert more HTML entries. These added inputs are not bound in the DOM, so .on() is used to attach these fields to the DOM.
My goal is to add up all the values of each input added by the user.
Here is an excerpt from the code:
$("form").on("click", "#calc", function () {
var total = 0;
$('#1 .val').each(function(){ /* HERE IS THE PROBLEM */
var valor = Number($(this).val());
if (!isNaN(valor)) total += valor;
});
alert(total);
});
JSBIN for my website
The issue is due to a missing " character delimiting the id you give to the input elements you append, as such the class is lost.
To fix this you can use template literals, which remove the need for spaghetti string concatenation, and also you can remove the id attribute on the dynamic content as it's an anti-pattern. This will leave you with simpler code that's more extensible and far easier to maintain.
Try this:
$(document).ready(function() {
$("form").on("click", ".add-campo", function() {
let $container = $(this).closest('.descricao_rot');
let qtd_input = $container.find('.val').length;
if (qtd_input < 10) {
$container.append(`<br><label for="valor">Valor</label> <input type="number" name="valor[]" placeholder="e aqui..." required="" class="val">`);
} else {
alert("Ainda não é possivel adicionar mais descrições");
}
});
$("form").on("click", "#calc", function() {
var total = 0;
$('.val').each((i, el) => total += Number(el.value) || 0);
alert(total);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="add-pub" method="POST">
<div id="formulario">
<br/>
<hr>
<div class="corpo-form" id="corpo1">
<h4>Dia 1</h4>
<br/><br/>
<div class="descricao_rot">
<label for="valor">Valor</label>
<input type="number" name="valor[]" placeholder="e aqui..." required="" class="val">
<button type="button" class="add-campo"> + </button>
</div>
</div>
</div>
<br/><br/>
<div class="botoes">
<button type="button" id="calc"> Calcular </button>
</div>
</form>
I basically on click need to insert the data- into a form. The issue is that both forms use the same element classes and when I perform one function it inserts the data but as soon as I click to run the other function it clears the original data. Here is my code:
HTML
<div class="inbox-widget nicescroll mx-box">
<a data-dismiss="modal" data-toggle="modal" href="#con-close-modal">
<div class="inbox-item" data-tag="Followers" data-social_type="twitter">
<p class="inbox-item-date">Click to add</p>
</div>
<div class="inbox-item" data-tag="Friends" data-social_type="twitter">
<p class="inbox-item-date">Click to add</p>
</div>
</a>
<a data-dismiss="modal" data-toggle="modal" href="#con-close-modal">
<div class="inbox-item2" id="chosen_account" data-social_id="12345">
<p class="inbox-item2-date">Click to add social ID</p>
</div>
</a>
<a data-dismiss="modal" data-toggle="modal" href="#con-close-modal">
<div class="inbox-item" id="chosen_account" data-social_id="6789">
<p class="inbox-item-date">Click to add social ID</p>
</div>
</a>
</div>
<form>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="input" id="social_id" type="text" name="social_id" />
<input type="input" id="social_type" type="text" name="social_type" />
<input type="input" id="chart_type" type="text" name="chart_type" value="line"/>
<input type="input" id="chart_tag" type="text" name="chart_tag"/>
</form>
My Jquery:
$('.inbox-item').click(function() {
var social_type_value = $(this).data('social_type');
var social_type_input = $('#social_type');
social_type_input.val(social_type_value);
var chart_tag_value = $(this).data('tag');
var chart_tag_input = $('#chart_tag');
chart_tag_input.val(chart_tag_value);
var social_id_value = $(this).data('social_id');
var social_id_input = $('#social_id');
social_id_input.val(social_id_value);
});
I also created a fiddle to show whats happening: https://jsfiddle.net/p18f3dow/1/
if i got your problem right, you'd want to use one function - but depending on the clicked element add different data... but don't overwrite the already entered data, when clicked element don't contains relevant data...
why not checking, if the data tag exists, in the first place:
$('.inbox-item').click(function() {
if ($(this).data('social_type')) {
var social_type_value = $(this).data('social_type');
var social_type_input = $('#social_type');
social_type_input.val(social_type_value);
}
if ($(this).data('tag')) {
var chart_tag_value = $(this).data('tag');
var chart_tag_input = $('#chart_tag');
chart_tag_input.val(chart_tag_value);
}
if ($(this).data('social_id')) {
var social_id_value = $(this).data('social_id');
var social_id_input = $('#social_id');
social_id_input.val(social_id_value);
}
});
this would be the quick and dirty solution, though.
better one would be like storing the complete clicked data objects and iterating through them, filling the correct fields. see https://jsfiddle.net/p18f3dow/4/
therefore you have to ensure that the part behing the data- in your html always matches your id in the form. (had to change it from data-tag to data-chart_tag)
then all you need is a simple function like that:
$('.inbox-item').click(function() { //when clicked
var stored_data = $(this).data(); //save everything in an object
for (var key in stored_data) { //iterate through the object
if (stored_data.hasOwnProperty(key)) {
$('#' + key).val(stored_data[key]) //create an id with #+key and insert the value
}
}
});
I want to be able to display the same piece of html code 10 times under the div called: <div id="add_remove_product_name"> By clicking on the button called: <button id="add_another_product_name">. I think I need some kind of a for loop for the job but are not sure. Any suggestion will be helpful, thanks.
My HTML code:
<div id="product_name">
<input id="skriv_produktnavn" placeholder="Skriv Produktnavn her" required></label>
<button id="add_another_product_name">Tilføj endnu et produktnavn</button>
<div id="add_remove_product_name">
<input id="added_product_name" placeholder="Skriv Produktnavn her" required></label>
<button id="remove_product_name">X</button>
</div>
Use a for loop to concatenate 10 copies of the HTML code. Then use .after() to put this after the DIV.
$("#add_another_product_name").click(function() {
var html = '';
for (var i = 0; i < 10; i++) {
html += 'html code that you want to repeat';
}
$("#add_remove_product_name").after(html);
}
You can use jQuery clone() however when cloning an element all the attributes will be the same. Fo example they will all have the same id attribute which will cause problems and it is not valid html
So in order to do the clone correctly you have fix the cloned element
DEMO: http://jsfiddle.net/rpyt445e/
var $tpl = $('#product_name').clone();
var num = 0
$('#clone').click(function () {
num++;
var $cloned = $tpl.clone();
$cloned.attr('id', $tpl.attr('id') + '_' + num);
$(':not([id=""])', $cloned).each(function(){
$(this).attr('id', $(this).attr('id') + '_'+num);
});
$cloned.appendTo('#wrapper');
});
HTML:
<div id="wrapper">
<div id="product_name">
<input id="skriv_produktnavn" placeholder="Skriv Produktnavn her" required />
<button id="add_another_product_name">Tilføj endnu et produktnavn</button>
<div id="add_remove_product_name">
<input id="added_product_name" placeholder="Skriv Produktnavn her" required />
<button id="remove_product_name">X</button>
</div>
</div>
</div>
<button id="clone">Clone</button>
A technique for adding the additional elements without having to create ugly strings of html in the JavaScript is to start with one hidden set of the elements in the html. At page load time, you remove that set, but keep a reference to it. Then when you want to add a set to the page, you clone the set you removed. All of this is easier if you add a container div around the additional inputs.
You also need to make sure id attribute values are unique. In the case of the remove buttons, you can replace the id with a class. As for the input id values, if you really need them, you can add an index value to them.
Since the remove buttons are dynamically added, I suggest using event delegation when binding the click-handler.
HTML:
<div id="product_name">
<input id="skriv_produktnavn" placeholder="Skriv Produktnavn her" required="required"/>
<button id="add_another_product_name">Tilføj endnu et produktnavn</button>
<div id="additional_product_names">
<div class="add_remove_product_name" style="display: none;">
<input id="added_product_name" placeholder="Skriv Produktnavn her" required="required"/>
<button class="remove_product_name">X</button>
</div>
</div>
</div>
JavaScript:
$(function() {
var MAX = 10;
var $addBtn = $('#add_another_product_name'),
$additionalContainer = $('#additional_product_names');
$TEMPLATE = $additionalContainer.children(':first').remove();
function update() {
var $additonalDivs = $additionalContainer.children();
// Enable/disable the add button.
$addBtn.prop('disabled', $additonalDivs.length >= MAX);
// Re-index the "id" attributes.
$additonalDivs.find('input').attr('id', function(i) {
return 'added_product_name[' + i + ']';
});
}
$addBtn.click(function() {
$TEMPLATE.clone().appendTo($additionalContainer).show();
update();
});
$('#product_name').on('click', '.remove_product_name', function() {
$(this).closest('.add_remove_product_name').remove();
update();
});
});
jsfiddle
I'm trying to add the rows dynamically plus auto-increment of a counter.I want to start with 1 then 2 then 3 and so on . I have added my code on plunker ,in which every time the max value is getting in first column like 4 then 1,1,2,3.Where am i going wrong ?i Want it to be 1,2,3,4.
Here is the plunker link http://plnkr.co/edit/GuDbJ3SHOPvWkHfNfd8E?p=preview
var _counter = 0;
function Add() {
_counter++;
var oClone = document.getElementById("template").cloneNode(true);
oClone.id += (_counter + "");
document.getElementById("placeholder1").appendChild(oClone);
document.getElementById("myVal").value=_counter;
}
<div id="placeholder1">
<div id="template">
<div>
Value:<input type="text" id="myVal" placeholder="1">
Quantity:<input type="text" placeholder="Qty">
<input type="button" onClick="Add()" value="Click! ">
</div>
</div>
I think it is because you have multiple divs with the id="myVal". The id attribute should be unique on the page. If not, your page will still load, but you may have unexpected behavior.
You are changing the id of the template div, but not the myVal div.
I assume you are looking for something like this:
var _counter = 0;
function Add() {
_counter++;
var oClone = document.getElementById("template").cloneNode(true);
oClone.id += (_counter + "");
document.getElementById("placeholder1").appendChild(oClone);
oClone.getElementsByClassName("myVal")[0].value = _counter;
}
<div id="placeholder1">
<div id="template">
<div>
Value:
<input type="text" class="myVal" placeholder="1">Quantity:
<input type="text" placeholder="Qty">
<input type="button" onClick="Add()" value="Click! ">
</div>
</div>
</div>
In your original you are cloning your template with the same id for the input. So when you do document.getElementById("myVal").value=_counter;, you only get the first input. I changed it to use class instead and get the input with the appropriate class that is a child of the cloned node.
Right now my code is very "hard-coded" and repetitive. I'd like to know if there is a cleaner way to do the following. Ideally, I want to iterate through my forms fields with a loop and calculate the results with one statement, but I'm struggling to figure out how best to do so.
Summary: I have ten form fields, each with a distinct decimal value that a user may or may not supply. When the user hits submit, it should add the value in the input field with a value being displayed on the current HTML page, then insert into the DB.
First, I grab that value from the form input field and convert it into a number with two decimal places. I then grab the current total from the HTML and add the two numbers together. After that I inject that total back into the form input field so that it can be stored in $_POST and inserted into a database.
How can I make my code more DRY (ie, Don't Repeat Yourself)? Below are just two examples but they are exactly the same except for the element calls:
var subtotal = Number($("#housing").val());
subtotal = (subtotal).toFixed(2);
var currentTotal = $('#output-housing').html().replace("$", "");
var total = Number(subtotal) + Number(currentTotal);
$('#housing').val(total);
var subtotal = Number($("#utilities").val());
subtotal = (subtotal).toFixed(2);
var currentTotal = $('#output-utilities').html().replace("$", "");
var total = Number(subtotal) + Number(currentTotal);
$('#utilities').val(total);
I would like to iterate through my input fields like so, but I'm trying to figure out how I could display the logic inside:
var input = $('.form-expenses :input');
input.each(function() {
// Insert switch statement here?? Some other construct??
});
HTML: (Uses Bootstrap 3 classes)
FORM:
<form class="form-expenses form-horizontal" role="form" method="post" action="/profile/update">
<div class="form-group">
<label for="housing" class="control-label col-sm-3">Housing</label>
<div class="input-group input-group-lg col-sm-9">
<span class="input-group-addon">$</span>
<input type="text" class="form-control" name="housing" id="housing" />
</div>
</div>
<div class="form-group">
<label for="utilities" class="control-label col-sm-3">Utilities</label>
<div class="input-group input-group-lg col-sm-9">
<span class="input-group-addon">$</span>
<input type="text" class="form-control" name="utilities" id="utilities" />
</div>
</div>
...
<button class="btn btn-lg btn-primary btn-block" id="update-expenses" type="submit"> Update</button>
</form>
OUTPUT:
<tr>
<td>Housing</td>
<td id="output-housing">$<?php echo $total['housing']?></td>
</tr>
<tr>
<td>Utilities</td>
<td id="output-utilities">$<?php echo $total['utilities']?></td>
</tr>
Something like this should work. Assumes the same prefixing relationship of output/input ID's
$(function() {
$('form.form-expenses').submit(function() {
updateValues();
return false/* prevent submit for demo only*/
})
})
function updateValues(){
$('.form-expenses :input').not('#update-expenses').each(function(){
var $input=$(this), inputId=this.id;
var curr=$('#output-'+inputId).text().replace("$", "");
$input.val(function(i,val){
return (1*(val ||0) + 1*curr).toFixed(2);
})
});
}
DEMO
From a UI perspective, this seems very counter intuitive to change values that user just input.
To create ajax data object instead of updating the display values:
function getAjaxData(){
var ajaxData={}
$('.form-expenses :input').not('#update-expenses').each(function(){
var $input=$(this), inputId=this.id;
var curr=$('#output-'+inputId).text().replace("$", "");
ajaxData[this.name] =(1*(val ||0) + 1*curr).toFixed(2);
});
return ajaxData
}
/* in submit handler*/
$.post('path/to/server', getAjaxData(), function(response){/*do something with reponse*/})
"if I allow a user to add/remove fields, then this could get a bit sticky"
In that case, give your fields a class name. As long as that exists on added fields, they will all be calculated.
<input type="text" class="form-control calculate-me" name="housing" id="housing" />
And iterate though all, using their ids as a reference
$(".calculate-me").each(function(){
var ref=this.id;
var subtotal = Number($("#" + ref).val());
subtotal = (subtotal).toFixed(2);
var currentTotal = $('#output-' + ref).html().replace("$", "");
var total = Number(subtotal) + Number(currentTotal);
$('#' + ref).val(total);
});