Dynamically display list of checked checkboxes values js/jquery - javascript

I would like to display dynamically a list of the chosen options using javascript or jQuery when the user changes his options.
PS: I'm using Django + Python to generate the options and bootstrap to style them.
Here is my code:
{% for option in options %}
<div class="input-group" style="margin-bottom: 7px;">
<div class="input-group-prepend">
<div class="input-group-text">
<input type="checkbox" name="checks[]" aria-label="Radio button for following text input" class="option_choice" class="ipad_pro" value="{{ option.name }}">
</div>
</div>
<input style="background-color: #fff;" type="text" class="form-control" disabled=True value="{{ option.name }} {{ option.price }}€" aria-label="Text input with radio button">
</div>
{% endfor %}
<ul id='options_display'></ul>
Here's what I've attempted:
var getChecked= function() {
var n = $("input:checked");
var options_display = $("#options_list")
console.log(n)
if (n.length != 0) {
$.each(n, function(index, value) {
options_display.append("<li>" + value.defaultValue + "</li>")
});
}
else {
options_display.html("<h3 class'text-center'>No Options</h3>")
}
};
getChecked()
$( "input[type=checkbox]" ).on( "click", getChecked);
The problem with that is that it doesn't reset the content of the <ul> which means that I get elements twice when I select a new one.
Please help me if you know the answer to my problem.

You can empty options_display on each click like
$("#options_list").empty();
before the condition.

Related

How do you implement input( or form) dependent on a select menu(drop down list)?

I'm working on grading system and I'm currently working on the form that's deals with the user entering the students results now the form I have, has 2 drop-down list(classroom, students) that are dependent. The issue and where I'm stuck is
When the user select the classroom the second drop-down menu will only show the students in that class, I have already figure that out..the issue is I want the input fields for how much subject the student is doing to appear so that the user can enter the grades for each subject specific to that student in the class
Eg if I select classroom 1b and selected student Mary.. if Mary is doing 5 subjects then 5 input field should appear so that I can enter the mark for the subjects
Link with a video showing what I'm talking about video showing an examplehttps://drive.google.com/file/d/11FoCZyOBVdUhTcvCqA1Ke0fEgRmMVC-G/view?usp=drivesdk
Models.py
Class Classroom(models.Models): name = models.charfield()
Class marks (models.Models): classroom = models.foreignkey(Classroom) Grade = models.Floatfield()
Html form
<div class="container-fluid">
<form id="result-form" method="post">
{% csrf_token %}
<!-- Modal -->
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel"> {% block modal-title%} Add Result {% endblock%}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12" id="msg8" style="font-size: 2rem; color:rgb(255, 144, 47)"></div>
<div class="col-md-12 form-group p-2">
<label class="form-label">Class Name</label>
{% render_field form.room class+="form-control" %}
</div>
<div class="col-md-12 form-group p-2">
<label class="form-label">Exam Name</label>
{% render_field form.exam class+="form-control" %}
</div>
<div class="col-md-12 form-group p-2">
<label class="form-label">Student</label>
{% render_field form.student class+="form-control select2" %}
</div>
<div class="hidden" id="subject-fields"></div>
<div class="form-group mb-3 pt-2">
<button type="button" id="resBtn" class="btn btn-info" title="Add">Submit</button>
</div>
</div>
</div>
</form>
</div>
{% block script%}
{% endblock%
script
$(document).on('click', '#submit-btn', function(event){
var response_data = []
var subject_name= $('.course');
var subject_objs = $('.subject_id');
for(i=0;i<subject_name.length;i++){
var subject_id = $(subject_objs[i]).find('input').val();
var grade_input = {
"Marks": subject_id,
}
response_data.push(grade_input);
}
$.ajax({
type: "POST",
url: "{% url 'marks' %}",
data: response_data,
success: function(response){
alert("Success");
}
});
});
This is how your view should look like.
def question_choice_view(request):
if request.method == "POST":
question_choice_data = request.POST['data']
I am not a jQuery User. As far as i can see i would put a eventlistener on the student form via .addEventListener('change', (event)See here. This would fire a function every time something changes on the select option. With that you could also collect the selected option values of the classroom and student name and make a request to get the subject names for the chosen student. After successful response i would insert the subject fields via JavaScript in the DOM.
**
function createInput(item) {
// This function takes a item and creates a new input
var newLabel = ' <br><label for="$item-mark">$item:</label>'
var newInput = '<input type="text" id="$item-mark-id" name="$item-mark"><br><br>';
newLabel = newLabel.replaceAll("$item", item)
newInput = newInput.replaceAll("$item", item)
// combine into a single str
newInput = newLabel + newInput
var studInput = document.getElementById("student-id");
// insert element inputs after student
studInput.insertAdjacentHTML('afterend', newInput);
}
function cleanOldInputs(item) {
var oldELement = item + "-mark-id"
oldELement = document.getElementById(oldELement)
if (oldELement) {
// remove old label and input
oldELement.previousSibling.remove()
oldELement.remove()
} else {}
}
function getAPIcall() {
// This is what your API sends
var responsObject = ["writing", "creativity"];
// loop throug
responsObject.forEach(item => {
// if you already picked a student clean old inputs from DOM
cleanOldInputs(item)
// send to function for input creation
createInput(item)
})
}
// get the Student Input
var studentSelect = document.getElementById("student-id");
studentSelect.addEventListener("click", function() {
// Fire anything you like
getAPIcall()
});
<form action="/action_page.php">
<label for="student">Choose a student:</label>
<select name="student" id="student-id">
<option value="harry">harry</option>
<option value="ivy">ivy</option>
</select>
</form>
Quick and dirty**

Symfony & js : button not working in certain conditions

I have a simple "plus/minus" functionality for the product quantity on the product detail page on a shopware6 site (version 6.4.8.1) (See attached image)
See here my code in /views/storefront/page/product-detail/buy-widget-form.html.twig.
{% block page_product_detail_buy_quantity_container %}
<div class="col-12 quantity-container">
<div class="row">
<div class="col-5 col-md-3 label-quantity">
<span>{{ "detail.labelQuantity"|trans|sw_sanitize }}</span>
</div>
<div class="col-7 col-md-9 quantity-input-panel">
{% block page_product_detail_buy_quantity %}
<div class="quantity-inner">
<span class="min button" id="moins" {#onclick="minus()"#}> {% sw_icon 'minus' %} </span>
<input id="amountToBasket" type="text" name="lineItems[{{ page.product.id }}][quantity]" value="{{product.minPurchase}}" autocomplete="off" maxlength="2" class="form-control">
<input id="minPurchase" type="hidden" name="minPurchase" value="{{product.minPurchase}}" autocomplete="off" class="form-control">
<input id="maxRange" type="hidden" name="maxRange" value="{{product.calculatedMaxPurchase}}" autocomplete="off" class="form-control">
<input id="purchaseSteps" type="hidden" name="purchaseSteps" value="{{product.purchaseSteps}}" autocomplete="off" class="form-control">
<span class="plus button" id="plus" {#onclick="plus()"#}> {% sw_icon 'plus' %}</span>
</div>
{% endblock %}
</div>
</div>
</div>
{% endblock %}
And here's my js file related to the plus/minus buttons.
var minPurchase = $("#minPurchase").val();
var maxRange = $("#maxRange").val();
var count = $("#amountToBasket").val();
$("#plus").click(function () {
if (count < maxRange){
count++;
$("#amountToBasket").val(count);
}
});
$("#moins").click(function () {
if (count > minPurchase){
count--;
$("#amountToBasket").val(count);
}
});
PROBLEM : This works perfectly for ALL products where the minimum purchase quantity is equal to 1. BUT if we click on the plus or the minus for every product having the minimum purchase quantity greater than 1, it's doing nothing. It gives the impression that the buttons are deactivated in this case.
Do you have any clue on what is going on?
as replied by #DarkBee, I simply needed to specify the value type of the "count" function.
var count = parseInt($("#amountToBasket").val());

Only checked specific checkbox inside a loop with jQuery

In my project, my issue is when I click Select All I want just want this row's checkbox to be checked. The 1st image below is the initial state that I want when the event click on .give-all-permissions fires. I want to be the 2nd image but my it gives me the 3rd image output how to achieve like 2nd image. Please see all the images that I tried to get this to work.
1st img
2nd img
3rd img
my HTML markup
<div class="row permission-group">
<div class="col-lg-4">
<fieldset class="mt-1 {{ $loop->last ? null : 'mb-1' }}">
<div class="checkbox checkbox-shadow">
<input type="checkbox" class="give-all-permissions" id="module_{{ md5($module->id) }}">
<label class="cursor-pointer" for="module_{{ md5($module->id) }}">Select All</label>
</div>
</fieldset>
</div>
<div class="col-lg-8">
#foreach ($module->permissions as $permission)
<fieldset class="mt-1 {{ $loop->last ? null : 'mb-1' }}">
<div class="checkbox checkbox-shadow">
<input class="checked-input" type="checkbox" id="permission_{{ md5($permission->id) }}">
<label class="cursor-pointer" for="permission_{{ $permission->id }}">{{ $permission->name }}</label>
</div>
</fieldset>
#endforeach
</div>
</div>
my code
$(document).ready(function () {
$('.give-all-permissions').click( (e) => {
// e.preventDefault();
if (e.target.checked === true) {
$('.checked-input').each(function (i, el) {
el.setAttribute("checked", "checked");
this.checked = true;
});
} else if (e.target.checked === false) {
$('.checked-input').each(function (i, el) {
el.removeAttribute("checked");
this.checked = false;
});
}
})
})

How to always get new checkboxes array, every time a different button is clicked

I'm developing an app about quizzes.
IMG1: [The added comments in this picture applies for the IMG2 too]
IMG2:
Description:
[IMG1] When one or more .js-answer-check checkbox are checked, I save the values in a js array. Then, when the #save-response button is clicked, the respective array is send to the server, to be saved in the db.
[IMG2] Then I click another question of the quiz, identified by .quiz-questions class, and when one or more .js-answer-check checkboxes of this new question are checked, the values are saved in the same js array.
The problem is that the previous checkboxes values, from the previous answers, are still present in the array, due to that answers.push(answerID).
How can I only grab the values of the respective question answers in the array each time a .quiz-questions button is clicked?
Expected values:
clicking the checkbox with label "2" in the first question => array should be [ 2 ] (the data-id="2" attribute in that checkbox)
clicking the checkboxes with label "1+3" and "8/2" in the second question => array should be [4, 5] as those checkboxes have data-id="4" and data-id="5" attributes.
Actual result: [2, 4, 5]
I tried out this code:
//if one|more options are checked...
var answers = [];
$(document).on('click', '.js-answer-check', function(){
if ($(this).is(':checked')){
var answerID = $(this).data('id');
answers.push(answerID);
} else {
var removeItem = $(this).data('id');
answers = $.grep(answers, function(value){
return value != removeItem;
});
}
});
$('#save-response').on('click', function(e){
e.preventDefault();
$.ajax({
method: 'POST',
url: Routing.generate('save_answer'),
data: { answers: answers },
success: function(resp) {
if (resp.success) {
var answersBack = resp.answers;
for (var ans in answersBack) {
console.log('answerID = ', answersBack[ans]);
}
}
//answers = [];
}
});
});
And I thought that if I do answers = [] will reset the initial array, but it didn't.
Any help is welcomed. Thanks.
LATER EDIT
<div class="row margin-top-ten">
<div class="col-6">
<input type="hidden" id="quiz-id" data-quiz="{{ quiz.id }}"/>
<div class="row question-content">{# the content (question-text + checkboxes) is coming from an AJAX request because I need to present everytime a new content based on `quiz-questions` buttons #}
</div>
</div>
</row>
<div class="row margin-top-ten">
<div class="col-12">
<button class="btn btn-primary btn-sm" type="button" id="save-response">Salveaza</button>
</div>
</div>
<div class="row margin-top-fifty">
<div class="col-12">
{% set i = 1 %}
<p>Navigator intrebari:</p>
{% for question in quiz.questions %}
<a href="" class="btn btn-info btn-sm quiz-question"
data-id="{{ question.id }}" data-quiz="{{ quiz.id }}">
{{ i }}
</a>
{% set i = i + 1 %}
{% endfor %}
</div>
</div>
The AJAX request for bringing new content for each quiz-questions buttons is:
<div class="col-12">
<div class="row">
<div class="col-12 question-text" data-question="{{ question.id }}">{{ question.content|raw }}</div>
</div>
<div class="row">
{% for answer in question.answers %}
<div class="col-12 question-answers">
<span style="display: inline-block">
<label for="">
<input type="checkbox" name="user-responses[]" class="js-answer-check" data-question="{{ question.id }}" data-id="{{ answer.id }}">
</label>
</span>
<span style="display:inline-block">{{ answer.answer|raw }}</span>
</div>
{% endfor %}
</div>
</div>
The save_answer php functionality is just returning the sent-data, for debug purposes. Nothing fancy.

pass variables to a bootstrap modal

I have a javascript confirm / cancel pop up box that dynamically unchecks a checkbox and also dynamically hides or shows a menu_entry that is part of a list that appears on the form, only when the user selects the ok button on the js confirm pop up box.
I am now trying to change the js confirm to a bootstrap modal, but I am uncertain how to pass the variables to the bootstrap modal code and get the same functionality of the js confirm pop up box.
Here is my working html code that has the call to the javascript confirm pop up box:
{% for id, menu_entry, selected, item_count in menu_entries %}
<div class="available_resume_details_height">
<input type="checkbox"
style="width:1.5em; height:1.5em;"
name="selected_items"
value="{{ id }}"
{% if selected %}checked="checked"{% endif %}
onclick="checkboxUpdated(this, {{ item_count }}, '{{ menu_entry.label }}', {{ id }});"
/>
<span style="cursor: pointer;"
rel="popover"
data-content="{{ menu_entry.tooltip }}"
data-original-title="{{ menu_entry.label }}"
{{ menu_entry.label }}
</span>
</div>
{% endfor %}
Here is my javascript code to display the confirm pop up and uncheck the checkbox and show/hide the list entry:
function checkboxUpdated(checkbox, count, label, id) {
if (checkbox.checked) {
$('#menu_entry_' + id).show();
} else {
if (count > 0) {
if (! confirm('{% trans "You have '+ count +' saved '+ label +'.\n\nAre you sure you want to delete your ' + count + ' saved ' + label +'?" %}')) {
checkbox.checked = true;
return;
}
}
$('#menu_entry_' + id).hide();
}
}
Here is the new html code that has the call to the bootstrap modal. This does make the bootstrap modal appear:
{% for id, menu_entry, selected, item_count in menu_entries %}
<div class="available_resume_details_height">
<input type="checkbox"
style="width:1.5em; height:1.5em;"
name="selected_items"
value="{{ id }}"
{% if selected %}checked="checked"{% endif %}
{% if selected %}
data-confirm="{% blocktrans with entry_label=menu_entry.label %}Are you sure you want to remove your {{ item_count }} selected {{entry_label}} Resume Details?{% endblocktrans %}"
{% endif %}
/>
<span style="cursor: pointer;"
rel="popover"
data-content="{{ menu_entry.tooltip }}"
data-original-title="{{ menu_entry.label }}"
{{ menu_entry.label }}
</span>
</div>
{% endfor %}
Here is my bootstrap modal code that is not working. I am unsure how to pass the variables and get the same functionality of the js confirm pop up:
$(document).ready(function() {
$('input[data-confirm]').click(function(ev) {
var href = $(this).attr('href');
if (!$('#dataConfirmModal').length) {
$('body').append('<div id="dataConfirmModal" class="modal modal-confirm-max-width" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true"><icon class="icon-remove"></icon></button><h4 class="modal-title" id="dataConfirmLabel">{% trans "Confirm" %} - {{ resume_detail_temp_value }}</h4></div><div class="modal-body"></div><div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">{% trans "Cancel" %}</button> <a class="btn-u btn-u-blue" id="dataConfirmOK">{% trans "Confirm" %}</a></div></div>');
}
$('#dataConfirmModal').find('.modal-body').html($(this).attr('data-confirm'));
$('#dataConfirmModal').modal({show:true});
$('#dataConfirmOK').click(function() {
// handle checkbox function here.
});
return false;
});
});
The bootstrap modal should show/hide the list entry and only uncheck the checkbox when the confirm button is selected.
EDIT: ADDED CHECKBOX CODE:
<input type="checkbox"
style="width:1.5em; height:1.5em;"
name="selected_items"
value="{{ id }}"
{% if selected %}checked="checked"{% endif %}
onclick="checkboxUpdated(this, {{ item_count }}, '{{ menu_entry.label }}', {{ id }});"/>
Data attributes may help you pass the data you need in the function in a seamless manner and also help you avoid maintenance unfriendly inline JavaScript. Set up three event listeners as follows:
function checkboxUpdated(checkbox, count, label, id) {
var checkbox = this,
count = $(checkbox).data('count'),
label = $(checkbox).data('label'),
id = checkbox.value;
if(checkbox.checked) {
$('#menu_entry_' + id).show();
} else {
if (count > 0) {
$('#confirm_modal').data('element', checkbox).find('div.modal-body p:first')
.html( 'You have ' + count + ' saved ' + label + '. Are you sure you want to delete your ' + count + ' saved ' + label + '?' ).end()
.modal('show');
return;
}
$('#menu_entry_' + id).hide();
}
}
$(function() {
$(':checkbox').on('change', checkboxUpdated).change();
$('.confirm-no').on('click', function() {
var element = $('#confirm_modal').data('element');
element.checked = true;
});
$('.confirm-yes').on('click', function() {
var element = $('#confirm_modal').data('element'),
id = element.value;
$('#menu_entry_' + id).hide();
});
});
DEMO
UPDATE
http://jsfiddle.net/n0ypwceo/3/
**HTML**
<div class="available_resume_details_height">
<input type="checkbox" data-confirm='Are you sure you want to remove? [1] ' value="id1" /> <span style="cursor: pointer;">Checkbox</span>
<br/>
<input type="checkbox" data-confirm='Are you sure you want to remove? [2]' value="id2" /> <span style="cursor: pointer;">Checkbox</span>
</div>
<div id="dataConfirmModal" class="modal modal-confirm-max-width" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true"><icon class="icon-remove"></icon></button><h4 class="modal-title" id="dataConfirmLabel">Confirm?</h4></div><div class="modal-body"></div><div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">"Cancel"</button> <a class="btn-u btn-u-blue" id="dataConfirmOK">"Confirm"</a></div></div>
<div id="menu_entry_id1" style="display:none">menu entry id 1</div>
<div id="menu_entry_id2" style="display:none">menu entry id 2</div>
JQ:
// global vars
//checkbox that is clicked
var $checkboxClicked;
//If the confirm button is clicked
var confirm=false;
$(document).ready(function () {
$('input[data-confirm]').click(function (ev) {
//box that is clicked placed in a variable
$checkboxClicked = $(this);
//get and store confirm text
var dataConfirmTxt=$checkboxClicked.attr('data-confirm')
confirm = false;
//var href = $(this).attr('href');
//append confirm text
$('#dataConfirmModal').find('.modal-body').html(dataConfirmTxt);
//show moadl
$('#dataConfirmModal').modal('show')
//if confirm button selected
$('#dataConfirmOK').click(function () {
// the confirm button is clicked
confirm=true;
// hide modal
$('#dataConfirmModal').modal('hide')
});
return false;
});
//modal event: before hide
$('#dataConfirmModal').on('hidden.bs.modal', function (e) {
//get menu id
var id=$checkboxClicked.val();
//alert(id+'/'+confirm);
if(confirm==true)
{
// check checkbox
$checkboxClicked.prop('checked', true);
// show menu entry
$('#menu_entry_' + id).show();
}
else
{
// uncheck checkbox
$checkboxClicked.prop('checked', false);
// hide menu entry
$('#menu_entry_' + id).hide();
}
})
});
I hope this could help you. You could see my code from here http://jsfiddle.net/p0mpv9e0/3/.
Why your code is not working is because you forget to put attribute 'data-confirm' to input element. It should be:
<input type="checkbox" data-confirm ... />
I'm not sure what do you mean by pas variables but if you want to get data that stored in input element you could get it using variable "this" inside the event callback.
$('input[data-confirm]').click(function() {
var self = this; // it's object that store data from input element
});

Categories