I have a checkbox and a label side by side in an html
<div class ="followupSteps">
<input type="checkbox" id="checkboxFollowup">
<label for="checkboxFollowup" id="labelFollowup"></label>
</div>
Depending on the number of output returned from server side, there can be any number of checkbox and label. For example, if 5 outputs are returned from the server, there will be 5 rows (each row is 1 checkbox and 1 label). How do I do that?
In jQuery, I have $("#labelFollowup").text(somevar);but it will not create a new row. Rather it will keep replacing the content of the only one label defined in the html.
$(function(){
let div = '<div class ="followupSteps">'+
'<input type="checkbox" id="checkboxFollowup">'+
'<label for="checkboxFollowup" id="labelFollowup">label</label>'+
'</div>';
for(var index=0; index<5; index++)
{
$('table').append('<tr> <td>'+div+' </td> </tr>')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
</tr>
</table>
try this one.
var $followupDiv = $('.followupSteps');
var $inputClone = $('input', $followupDiv).clone().removeAttr('id');
var $labelClone = $('label', $followupDiv).clone().removeAttr('id');
var serverResponse = 5;
for (i = 1; i <= serverResponse; i++) {
$inputClone.clone().attr('id', 'checkboxFollowup' + i).appendTo($followupDiv);
$labelClone.clone().attr('id', 'labelFollowup' + i).appendTo($followupDiv);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="followupSteps">
<input type="checkbox" id="checkboxFollowup">
<label for="checkboxFollowup" id="labelFollowup"></label>
</div>
Since you doesn't provide much information, I will just post how you can achieve it using a javascript "for" loop of 10 times and following your markup:
for(i=0;i<10;i++) {
$('#checkboxFollowup').eq(0).clone().prop('id', 'clone'+i).appendTo('.followupSteps');
$('#labelFollowup').eq(0).clone().prop('id', 'clone'+i).appendTo('.followupSteps');
}
Using the following jQuery methods:
https://api.jquery.com/eq/
https://api.jquery.com/clone/
http://api.jquery.com/appendto/
http://api.jquery.com/prop/
Related
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)
I have a HTML page which have a certain number of divs and there is also one checkbox inside of each div.
Let's say:
<div class="yea" id="div1"><input type="checkbox" class="heh" id="chk1">YEAHEH1!</div>
<div class="yea" id="div2"><input type="checkbox" class="heh" id="chk2">YEAHEH2!</div>
<div class="yea" id="div2"><input type="checkbox" class="heh" id="chk3">YEAHEH3!</div>
Now I want to loop through those checkboxes and see which one is checked in JS. I've found one tutorial here http://www.randomsnippets.com/2008/05/15/how-to-loop-through-checkboxes-or-radio-button-groups-via-javascript/ but it uses form element to include all those checkboxes and use form.elements.length to get the number, however in my project form is not necessary.
Anyone? Thanks!
Use Document.querySelectorAll() with the CSS selector '.yea input[type=checkbox]:checked' like so:
document.querySelectorAll('.yea input[type=checkbox]:checked');
This will return a NodeList with the collection of checked inputs.
Example:
document.getElementById('submit').addEventListener('click', function() {
var checked = document.querySelectorAll('.yea input[type=checkbox]:checked'),
i = 0,
len = checked.length;
for (i, len; i < len; i++) {
checked[i].parentNode.classList.add('checked');
}
});
.checked {
color: red;
}
<div class="yea" id="div1"><input type="checkbox" class="heh" id="chk1">YEAHEH1!</div>
<div class="yea" id="div2"><input type="checkbox" class="heh" id="chk2">YEAHEH2!</div>
<div class="yea" id="div2"><input type="checkbox" class="heh" id="chk3">YEAHEH3!</div>
<button id="submit">Submit</button>
Try the following javascript code.
var elementsToCheck = document.getElementsByClassName('heh');
for(var i = 0; i < elementsToCheck.length; i++) {
if(elementsToCheck[i].checked) {
// your code when the checkbox is selected goes here.
}
}
To get the list of all checkboxes in your page use
document.querySelectorAll('input[type="checkbox"]')
to get the number use
document.querySelectorAll('input[type="checkbox"]').length
to get list of all chacked checkboxes use
document.querySelectorAll('input[type="checkbox"]:checked')
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.
I have a list checkbox's within a div which is not a form.
<div id="priceTree">
<div class="prices"><span class="left"><input type="checkbox" checked="checked" id="price_1"> Small </span><span class="right">5.00</span><span class="center"> </span></div>
<div class="prices"><span class="left"><input type="checkbox" checked="checked" id="price_2"> Medium </span><span class="right">10.00</span><span class="center"> </span></div>
<div class="prices"><span class="left"><input type="checkbox" checked="checked" id="price_3"> Large </span><span class="right">15.00</span><span class="center"> </span></div>
</div>
This list has injected elements so may not always have 3. How would I go about getting the id for only the checked checkboxs?
Here is a vanilla JavaScript solution:
var checkedCbs = document.querySelectorAll('#priceTree input[type="checkbox"]:checked');
var ids = [];
for (var i = 0; i < checkedCbs.length; i++) ids.push(checkedCbs[i].id);
//return ids;
Demo
Try this
$("#priceTree input:checked").each(function(){
console.log(this.id);
});
Demo
If you want an array of checked elements' ids, use:
var result = $('#priceTree input:checked').map(function() {
return this.id;
}).get();
THE WORKING DEMO.
$('input[type=checkbox]:checked').attr('id');
To iterate over all checkboxes use each:
$('input[type=checkbox]:checked').each(function(){
console.log($(this).attr('id'));
});
Or,
$('#priceTree :checked').each(function(){
console.log($(this).attr('id'));
});
To get ids of all checkboxes checked within #priceTree div:
$('#priceTree input:checked').each(function(){
alert($(this).attr('id'));
})
Here's what I want to do. Hopefully it's not too hard.
I need to create a table with a div inside each td which is created by clicking buttons... for example
Please select the number of rows in the table
Please select the number of columns in the table..
Result:
So if you clicked on 4 and 4 it would create a table 4 X 4. If you clicked 3 X 1, you would create a table 3 X 1, etc...
Any help would be greatly appreciated!!
Here's a jfiddle of something I'm trying to get working. I'm still looking over all your comments!
http://jsfiddle.net/irocmon/7WD8v/
I know I need to add in the Javascript how to get the element by id.
I would use 2 forms, 1 for the top row of numbers and one for the second row of numbers, where each number is a predefined value of the user input.
Assign the submit button to each of the numbers using javascript for each form and from there grab the results with javascript and perform the code/script that is required to complete the task in mind.
I would recommend using jquery for this.
Have fun...
you should be able to achieve this with some pretty simple if statements or a switch
if you have 2 variables rows & columns
//loop for number of rows
for "x" number of rows{
document.write("<tr>");
if(columns > 0)
{
switch statement to output column
1: document.write("<td></td>");
2: document.write("<td></td><td></td>");
}
document.write("</tr>");
}
the syntax is very very psuedo here, this code wont work but it might get you started, what are you actually wanting to do with the table once you have it?
Using javascript, have 2 local variables: width and height. Within each DIV, have an onclick function that assigns that value to the proper variable, then checks to see if both variables have been assigned (this way they can click on either height or width first). If both are, use these variables within a for loop to generate HTML code within javascript:
var HTML = '<table>';
for(var i = 0; i < height; i++)
{ HTML += '<tr>';
for(var j = 0; j < width; j++)
{ HTML += '<td>...</td>';}
HTML += '</tr>';}
document.getElementById('where_you_want_the_table').innerHTML = HTML;
This is tested and work of note it doesn't handle if they keep trying to build the tables over and over it will keep adding cols and rows but I will let you handle that. :)
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
var Rows = 0;
var ColString = "";
var TableBuilder;
$(document).ready(function () {
$("#Rows input").click(function () { Rows = $(this).val(); });
$("#Cols input").click(buildCols);
$("#Submit").click(CreateTable);
});
function buildCols() {
for (i = 0; i < $(this).val(); i++) {
ColString = ColString + "<td></td>";
}
return ColString;
}
function CreateTable() {
if (Rows == 0 || ColString == "") {
$("#PleaseSelect").removeClass("displayNone");
}
else {
for (i = 0; i < Rows; i++) {
TableBuilder = TableBuilder + "<tr>" + ColString + "</tr>";
}
$("#table tbody").html(TableBuilder);
}
}
</script>
<style type="text/css">
.displayNone { display: none; }
</style>
</head>
<body>
<table id="table" border="1">
<tbody>
</tbody>
</table>
<br><br>
How many Rows?
<div id="Rows">
<input type="button" value="1">
<input type="button" value="2">
<input type="button" value="3">
<input type="button" value="4">
</div>
<br />
How Many Columns?
<div id="Cols">
<input type="button" value="1" >
<input type="button" value="2">
<input type="button" value="3">
<input type="button" value="4">
</div>
<br />
<div id="PleaseSelect" class="displayNone">Please select both a column number and a row number.</div>
<input type="button" id="Submit" value="Build Table" />
</body>
</html>