Generate dynamic li elements depending on how many checkboxes are checked - javascript

I am trying to generate li elements for each checkbox that has been checked. It works when there is only one checked, but when I check 2 checkboxes, only the last checkbox and its hidden inputs (hidden inputs used to populate specific values inside the li element) are generated.
Here is the code I use now:
attachPanelListeners : function() {
$('#sc-accordion').bind('click', function(e) {
var items,
target = $(e.target);
if ( target.hasClass('submit-add-to-menu') ) {
var t = $(this).parent().parent(),
checkboxes = t.find('.sc-pagelist li input:checked');
// If no items are checked, bail.
if ( !checkboxes.length )
return false;
var structure;
$(checkboxes).each(function(){
var hidden = $(this).closest('li').find(':hidden');
structure = "<li class='menu-item menu-item-depth-0'>"+
"<div class='menu-item-bar'>"+
"<div class='menu-item-handle ui-sortable-handle'>"+
"<span class='item-title'><span class='menu-item-title'>" + hidden[0].value + "</span></span>"+
"<span class='item-controls'><span class='item-type'>Pagina</span><a href='#' class='item-edit'></a></span>"+
"</div>"+
"</div>"+
"<div class='menu-item-settings sc-clearfix' style='display:none;'>"+
"<p class='description description-wide'>"+
"<label for='edit-menu-title'>Navigatielabel</label>"+
"<input type='text' class='form-control' id='edit-menu-title' value='" + hidden[0].value + "'>"+
"</p>"+
"<fieldset class='field-move hide-if-no-js description description-wide'>"+
"<span class='field-move-visual-label' aria-hidden='true'>Verplaatsen</span>"+
"<button type='button' class='button-link menus-move menus-move-up' data-dir='up' style='display: none;'>Eén omhoog</button>"+
"<button type='button' class='button-link menus-move menus-move-down' data-dir='down' style='display: inline;' aria-label='Verplaats één omlaag'>Eén omlaag</button>"+
"<button type='button' class='button-link menus-move menus-move-left' data-dir='left' style='display: none;'></button>"+
"<button type='button' class='button-link menus-move menus-move-right' data-dir='right' style='display: none;'></button>"+
"<button type='button' class='button-link menus-move menus-move-top' data-dir='top' style='display: none;'>Naar boven</button>"+
"</fieldset>"+
"<div class='menu-item-actions description-wide submitbox'>"+
"<a class='item-delete submitdelete deletion' id='' href='#'>Verwijderen</a>"+
"</div>"+
"<input type='hidden' value='"+ $(this).val() +"'>"+
"<input type='hidden' value='"+ hidden[2].value +"'>"+
"</div>"+
"</li>";
});
$('#menu-to-edit').append(structure);
checkboxes.prop('checked', false);
};
})
},
Cheers

You're assigning the string on each loop, rather than appending - meaning you only ever get the last one.
One option is to change...
structure = "<li class='menu-item menu-item-depth-0'>"+
To...
structure += "<li class='menu-item menu-item-depth-0'>"+
An alternative option is to append the string on each loop directly...
$(checkboxes).each(function(){
var hidden = $(this).closest('li').find(':hidden');
$('#menu-to-edit').append(
"<li class='menu-item menu-item-depth-0'>"+
"<div class='menu-item-bar'>"+
...
"</div>"+
"</li>");
});

I made a simple example below ( as you didn't share the HTML and a bunch of code you shared is not relevant to the problem itself )
Basically you need to append to the existing HTML. WHat you are doing is replacing it with a new li every time you check a checkbox. So it overrides the previous html.
I also removed the corresponding li when the checkbox is unchecked.
THere might be a more straight forward solution out there but this is the best i came up with for now :)
var chkBox = $(".checkbox")
$(chkBox).on('change', function(){
var index = $(this).index()
var menuItem = `<li class=${index}>${index} list item</li>`
if ($(this).is(':checked') ) {
$('.menu').html($('.menu').html() + menuItem)
} else {
$(`li.${index}`).remove()
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="menu">
</ul>
<div>
<input type="checkbox" class="checkbox"/>
<input type="checkbox" class="checkbox"/>
<input type="checkbox" class="checkbox"/>
<input type="checkbox" class="checkbox"/>
<input type="checkbox" class="checkbox"/>
<input type="checkbox" class="checkbox"/>
</div>

Related

can't combine script and php div.innerHTML += "<form action='\"{{route('stock.store')}}\"' method='post'>#csrf</form>";

I have a button that calls a script method named add_Fields(). I used .innerHTML to add fields in a form.
The problem is when i put the attribute action with a value of {{route('stock.store')}} the whole script code doesn't work.
Can anybody help me with this?
var i = 0;
var d = document.getElementById("content");
d.innerHTML += "<div class='form-group row'>"+
"<span class='col-md-2'>UNIT:<input form='form"+i+"' id='unit' type='text' name='unit' class='form-control' required></span>"+
"<span class='col-md-2'>QTY:<input form='form"+i+"' id='quantity' type='number' name='quantity' class='form-control' required></span>"+
"<span class='col-md-4'>UNIT COST:<input form='form"+i+"' id='unit_cost' type='number' name='unit_cost' class='form-control' required></span>"+
"<span class='col-md-4'>AMOUNT:<input form='form"+i+"' id='unit_cost' type='number' name='unit_cost' class='form-control' required></span>"+
"</div>"+
"<form id='form"+i+"' action='\"{{route('stock.store')}}\"' method='post'>#csrf</form>"+
"";
replace below code for form tag and make sure the route is defined in routes\web.php file
"<form id='form"+i+"' action='{{route('stock.store')}}' method='post'>#csrf</form>"+

Vue.js dynamically appending HTML when clicking on a button

So basically what I am trying to achieve is allowing the user to be able to add to an existing set of information that will be passed on to Vue from JSON.
So the following code is my HTML code which comprises of the div element with the id objectiveArea that vue will render to and a hard coded button for the users to add more entries.
<div class="form-group" id="objectiveArea"></div>
<div><input type="button" value="Add Objective" id="addButton" /></div>
And here is my Javascript where I pass the JSON into vue for it to render as well as having an onclick event when the add button is triggered. The function addNewObjectiveRow serves as a template to append when the user clicks add and the objectiveElements is a template for vue to render the existing JSON to the HTML.
function addNewObjectiveRow(value) {
var $divElements = "<div class='row'>"
+ "<div class='form-inline'>"
+ "<br /><div class='form-group'><label class='control-label'>Title</label><div class=''><input type='text' class='form-control objectivetitle' placeholder='Title' /></div></div>"
+ " "
+ "<div class='form-group input-group'><label class='control-label'>Target Completion Date</label><div class=''><input readonly type='text' class='form-control targetdateinput' placeholder='Select Date' /><span class='input-group-addon'><i class='glyphicon glyphicon-calendar'></i></span></div></div>"
+ " "
+ "<div class='form-group'><label class='control-label'></label><div><input type='button' value='Remove Goal' class='btn-remove btn-danger deleteButton' /></div></div>"
+ "</div>"
+ "<br />"
+ "<div class='form-group'><label class='control-label'> Details</label><div><textarea class='form-control text-area-width goaldetails' rows='4' placeholder='Enter details here...'></textarea></div></div><hr />"
+ "</div>"
return $divElements;
}
var objectiveElements = "<div class='row'><div v-for='(objective, index) in objectivesData'>"
+ "<div class='form-inline'>"
+ "<br /><div class='form-group'><label class='control-label'>Title</label><div class=''><input type='text' class='form-control objectivetitle' placeholder='Title' v-model='decodeData(objective.Title)' /></div></div>"
+ " "
+ "<div class='form-group input-group'><label class='control-label'>Target Completion Date</label><div class=''><input readonly type='text' class='form-control targetdateinput' placeholder='Select Date' v-formatdate='objective.TargetDate' /><span class='input-group-addon'><i class='glyphicon glyphicon-calendar'></i></span></div></div>"
+ " "
+ "<div class='form-group'><label class='control-label'></label><div><input type='button' v-if='(index > 0)' value='Remove Goal' class='btn-remove btn-danger deleteButton' /></div></div>"
+ "</div>"
+ "<br />"
+ "<div class='form-group'><label class='control-label'> Details</label><div><textarea class='form-control text-area-width goaldetails' rows='4' placeholder='Enter details here...' v-model='decodeData(objective.Details)'></textarea></div></div><hr />"
+ "</div></div>";
var data = JSON.parse('[{"Title":"Title One","TargetDate":"21 June 2017","Details":"Details One"},{"Title":"Title Two","TargetDate":"22 June 2017","Details":"Details Two"}]');
var Objectives = Vue.extend({
template: objectiveElements,
data: function () {
return {
objectivesData: data
}
}
})
new Objectives().$mount('#objectiveArea');
$('#addButton').on('click', function () {
$('#objectiveArea').append(addNewObjectiveRow(""));
});//end addButton on click
However, the above code renders the existing information from the JSON just fine in the HTML but when I click on the add button, nothing happens at all. Am I missing something or getting it all wrong?
https://v2.vuejs.org/v2/guide/list.html
HTML
<ul id="example-1">
<li v-for="item in items">
{{ item.message }}
</li>
</ul>
<button #click="addItem()">Add new item</button>
JS
var example1 = new Vue({
el: '#example-1',
data: {
items: [
{ message: 'Foo' },
{ message: 'Bar' }
]
},
methods: {
addItem(){
this.items.push({message: 'new message'})
}
}
})
Clicking the button will execute addItem() method which will add a new item into data items and it will automatically render new li
there are many mistakes
the function addNewObjectiveRow(value)you don't use the parameter value.
Vue is data-driven, you should change the objectivesData, not simply append the string. Read the document

Form button add dynamically in JS

I tried to add dynamically a form in JavaScript, but when I click on the submit button nothing happens. I know that is because the button has no listener, but I don't know what I have to add in the listener for a normal sending button behavior.
Here some of my code
document.getElementById("partTwo").innerHTML += "<form id='download_report' method='post' class='form-horizontal' role='form' action='include/client.process.php'>";
document.getElementById("partTwo").innerHTML += "<input type='hidden' name='jobid' value='" + jobId + "'/>";
document.getElementById("partTwo").innerHTML += "<input type='hidden' name='job' value='" + job_details.heavyInfosJson + "'/>";
document.getElementById("partTwo").innerHTML += "<input type='hidden' name='download_report' value='1'/>";
document.getElementById("partTwo").innerHTML += "<button id='download_report_button' type='submit' class='btn btn-default btn-xs'>Télécharger le rapport</button>";
document.getElementById("partTwo").innerHTML += "</form>";
I want from the listener to juste send the form to my client.process.php
I know that it s a beginner question but any help would be appreciated.
Thanks
Working fiddle.
You should add the inputs inside form and not inside div partTwo, so your code should be like :
document.getElementById("partTwo").innerHTML += "<form id='download_report' method='post' class='form-horizontal' role='form' action='include/client.process.php'>";
document.getElementById("download_report").innerHTML += "<input type='hidden' name='jobid' value='" + jobId + "'/>";
document.getElementById("download_report").innerHTML += "<input type='hidden' name='job' value='" + job_details.heavyInfosJson + "'/>";
document.getElementById("download_report").innerHTML += "<input type='hidden' name='download_report' value='1'/>";
document.getElementById("download_report").innerHTML += "<button id='download_report_button' type='submit' class='btn btn-default btn-xs'>Télécharger le rapport</button>";
Hope this helps.
The problem is that <form> tag is autoclosed. innerHTML returns well formed html. See this question
You should consider using createElement rather than innerHTML, see 2946656
Here is a basic example of how to create a form and append it to the page:
var form = document.createElement("form");
form.setAttribute('action', 'contact.php');
form.setAttribute('method', 'POST');
var inputField = document.createElement("input");
inputField.setAttribute('value', 'example');
form.appendChild(inputField);
document.body.appendChild(form);

How to allow to select only one dynamically generated radio box?

i am trying to create a back-end for a contest page..By default here are two input boxes with a radio button stating which one is true and an add button which dynamically generates the input boxes and radio buttons through javascript..I have given same "Name" to the two radio boxes which are by default available and the ones which are dynamically generated..I have used array to name them..Still when i select one radio box still i am able to select other radio button as well..I want to unable this option..kindly help..
Here is the javascript code for dynamically generated input box and radio box
var doc_index = <?php echo $fans; ?>;//rows - 1
function AddDocRow(){
doc_index ++;
index = doc_index;
doc_html = "<tr id='doc_" + index + "'>" +
"<td>"+ (index+1) +"</td>" +
"<td>" +
"<input type='text' class='span12' id='option[" + index + "]' name='option[" + index + "]' placeholder='' />" +
"</td>" +
"<td><a href='javascript:void(0);' onclick='RemoveDocRow(" + index + ")'><i class='icon-remove red'></i></a></td>"+
"<td>"+
"<label>"+
"<input type='radio' name='right[" + index + "]' value='1' /><span class='lbl'></span>"+
"</label>"+
"</td>"+
"</tr>";
$('table#doc_rows tbody').append(doc_html);
//number ++;
}
And here is the code for the default two options..
<td>
<label>
<?php $check=($r['is_true']==1) ? 'checked="checked"' :''; ?>
<input type="radio" <?php echo $check; ?> name="right[<?php echo $counter1; ?>]" value="1" id="radio" /><span class="lbl"></span>
</label>
Please Help!!
Two or more radio button need to have the same EXACT name to give them the "unique" selection option. Your radios name are Dynamic, with different Name for each one.
The name of radio should be unique ie, what are the radio button which you want group.
"<input type='radio' name='radioGroupName' value='1' /><span class='lbl'></span>"+
You can apply index logic for id attribute.
The radio buttons do not have the same name - they must have the same name in order to be grouped as the same set of radio buttons.
I believe simply changing the name of each to name="right" should suffice
change
"<input type='radio' name='right[" + index + "]' value='1' /><span class='lbl'></span>"
to
"<input type='radio' name='right' id='right[" + index + "]' value='1' /><span class='lbl'></span>"
or
"<input type='radio' name='right' value='+ index +' /><span class='lbl'></span>"
this way you can give them same name, and differentiate between the two by id

How to append check box in jquery

How I add checkbox after span in below code.
var aaa = $('<a/>')
.html("<span>" "</span >" + " <span>""</span> ")
.attr('data-transition', 'slide')
.appendTo(li);
Your .html() has several issues with concatenation:
.html("<span>" "</span >" + " <span>""</span> ")
//------^^^^--------------------^^--------useless quotes are here.
this way:
.html("<span></span ><input type='checkbox' value='' />" + " <span>""</span> ")
this way:
.html("<span></span >" + " <span></span><input type='checkbox' value='' />")
or after both:
.html("<span></span> <input type='checkbox' value='' />" + " <span></span><input type='checkbox' value='' />")
just add the html tag for checkbox inside <span>
try this
.html("<span> <input type='checkbox' value='value' />test<input type='checkbox' value='value1' />test1</span >") ;
You can also make use of the html option.
var $a = $("<a/>", {
"data-transition": "slide",
"html": $("<input>", {
"type": "checkbox"
})
})
.appendTo(li);
It will render this HTML:
<a data-transition="slide"><input type="checkbox"></a>

Categories