I really cant understand what is the problem here. I want when checkbox in the form is clicked to get to the closest "h2" and to get its text.
HTML
<form action="" method="get" id="productFilterForm">
<h2 class="attribute-name">Brands</h2>
<div class="option">
<label>
<input type="checkbox" name="Royal Canin" value="163">Royal Canin
</label>
</div>
<div class="option">
<label>
<input type="checkbox" name="Brit" value="164">Brit
</label>
</div>
<div class="option">
<label>
<input type="checkbox" name="Purina Pro Plan" value="165">Purina Pro Plan
</label>
</div>
</form>
JavaScript
$(document).ready(function(){
$('#productFilterForm').on('change', 'input:checkbox', function () {
let text = $(this).closest("h2").html(); <---- UNDEFINED
//let text = $(this).find("h2").html(); <---- UNDEFINED
console.log(text);
}
});
I tried many things and methods, just cant find any element from the "input" up to the DOM tree.
try this code
$('#productFilterForm').on('change', function () {
let text = $(this).find("h2").html();
console.log(text);
})
I found a solution:
$(document).ready(function(){
$('#productFilterForm input:checkbox').on('change', function () {
let text = $(this).closest('div.option').prevAll('h2.attribute-name').html();
console.log(text);
}
});
Related
I have been trying to do this for a few hours but couldn't succeed. So I decided to ask help here.
So, I have a form:
<form id="ecommerce-form">
<input type="checkbox" id="seopremium" name="option-ecommerce" value="seopremium">
<label for="seopremium" class="lead">SEO premium</label>
<input type="checkbox" id="moyenpaiement" name="option-ecommerce" value="moyenpaiement">
<label for="moyenpaiement" class="lead">Configuration paiements</label>
<input type="checkbox" id="facturation" name="option-ecommerce" value="facturation">
<label for="facturation" class="lead">Facturation simplifiée</label>
<input type="checkbox" id="avisclients" name="option-ecommerce" value="avisclients">
<label for="avisclients" class="lead">Avis clients</label>
<input type="checkbox" id="additionnalsecurity" name="option-ecommerce" value="additionnalsecurity">
<label for="additionnalsecurity" class="lead">Sécurité supplémentaire</label>
<input type="checkbox" id="basketoptions" name="option-ecommerce" value="basketoptions">
<label for="basketoptions" class="lead">Panier avec options</label>
</form>
And I'm trying to print the label's text of checkboxes that are checked automatically into a Paragraph:
<p class="recap-option"><strong>Options:</strong></p><p class="options-selected"></p>
So if everything is checked the Paragraph would be:
<p class="recap-option"><strong>Options:</strong></p><p class="options-selected">SEO premium, Configuration paiements, facturation simplifiée, Avis clients, Sécurité supplémentaire, Panier avec options</p>
Or in clear:
Options: SEO premium, Configuration paiements, facturation simplifiée, Avis clients, Sécurité supplémentaire, Panier avec options
I found a few solutions here for problems that seemed relatively similar but I wasn't able to adapt the code for my own needs.
http://jsfiddle.net/5ryy9krn/2/
So the goal is simply appending what is between each into the paragraph element.
Thanks in advance for any help.
You need to fetch the label element and use its value to append into the selected-area.
And on uncheck, also follow the same procedure to remove the unchecked element from the selected-area
You can define the onChange function in the following way to achieve the expected behavior.
$('input[type="checkbox"]').on('change', function() {
if ($(this).is(':checked')) {
var elements = $(this).parent('div');
const checkedItem = elements.find("label").text();
$('#seleted-rows').append(`<p name="${checkedItem}">${checkedItem}</p>`);
} else {
var elements = $(this).parent('div');
const uncheckedItem = elements.find("label").text();
$('#seleted-rows').find(`p[name="${uncheckedItem}"]`).remove();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="pb-5 devis-invisible" id="devis-ecommerce">
<form id="ecommerce-form">
<div class="row pb-5">
<div class="col-4">
<input type="checkbox" id="seopremium" name="option-ecommerce" value="seopremium">
<label for="seopremium" class="lead">SEO premium</label>
</div>
<div class="col-4">
<input type="checkbox" id="moyenpaiement" name="option-ecommerce" value="moyenpaiement">
<label for="moyenpaiement" class="lead">Configuration paiements</label>
</div>
<div class="col-4">
<input type="checkbox" id="facturation" name="option-ecommerce" value="facturation">
<label for="facturation" class="lead">Facturation simplifiée</label>
</div>
</div>
<div class="row">
<div class="col-4">
<input type="checkbox" id="avisclients" name="option-ecommerce" value="avisclients">
<label for="avisclients" class="lead">Avis clients</label>
</div>
<div class="col-4">
<input type="checkbox" id="additionnalsecurity" name="option-ecommerce" value="additionnalsecurity">
<label for="additionnalsecurity" class="lead">Sécurité supplémentaire</label>
</div>
<div class="col-4">
<input type="checkbox" id="basketoptions" name="option-ecommerce" value="basketoptions">
<label for="basketoptions" class="lead">Panier avec options</label>
</div>
</div>
</form>
</div>
<div>
<p>Selected Items</p>
<div id="seleted-rows">
</div>
</div>
You seem to want something like this:
var labels = document.querySelectorAll("input:checked ~ label);
labels.foreach(function(label) {
console.log(label.textContent);
});
It isn't clear to me which paragraph you want these labels added to, so I used console.log and left it for you to put the label.texContent into your paragraph(s)
You have to gather all input[type=checkbox]:checked and the labels.
Using your example this could be done with:
var nodelistChecked = document.querySelectorAll("#ecommerce-form input[type=checkbox]:checked");
// nodelistChecked now contains a Node-list with all checked input elements
With this result you can gather the text from the labels with an Array.prototype.map function call. The result from a querySelectorAll()-call is a Nodelist and doesn't know forEach/map/or other Array-like function-calls, so you have to call it and convert it with map to an array.
var arrLabelText =
Array.prototype.map.call(nodelistChecked, function(node) {
return (document.querySelector('label[for='+node.id+']')
|| document.createElement('label')).textContent;
});
// arrLabelText contains an array with all selected labels
// the || new element is used, to avoid errors if no label is found
After this you can display the value in the element you want to display it:
document.querySelector("p.options-selected").innerText = arrLabelText.join(', ');
When you use jQuery it is a a bit shorter and it avoids some error-checking (like no label found):
function fillSelectedOptions() {
$("p.options-selected").text(
Array.prototype.slice.call( // depending on the jQuery version, this might be required
$("#ecommerce-form input[type=checkbox]:checked")
.map(function(i,node) { /* jQuery returns the index first */
return $('label[for="'+node.id+'"]').text()
})
).join(', ')
);
}
$("#ecommerce-form input[type=checkbox]").each(function(i, node) {
$(node).on('change', fillSelectedOptions);
});
I have different checkboxes generated dynamically.
Each checkboxes are contained within a div.
I would like to do the following action with jquery:
If a checkbox has an id="aucune", then remove its container (the div containing the checkbox with the id="aucune") from the html page.
I tried the following code:
// wait for DOM to be ready
$(document).ready(function() {
var empty = $("input:checkbox[id=aucune]");
if (empty == true) {
$(this).parent().remove();
}
});
Here is a the very simplified html:
<div class="wrapper-checkbox">
<input type="checkbox" class="outsider" id="xxx" name="xxx" date-name="xxx">
<label for="xxx">xxx</label>
</div>
<div class="wrapper-checkbox">
<input type="checkbox" class="outsider" id="aucune" name="aucune" date-name="aucune">
<label for="aucune">aucune</label>
</div>
Here is my codepen:
I am quite new to code, I apologize for my silly simple question.
You can directly select the id with jQuery and remove the parent.
$('#acune').parent().remove();
Or if you know the class of the parent element
$('#acune').parent('.wrapper-checkbox').remove();
You are wrongly referencing this. It should be this way:
Replace this with empty.
Replace the boolean check with count.
Note: You can also use $("#aucune") instead of the selector $("input:checkbox[id=aucune]").
// wait for DOM to be ready
$(document).ready(function() {
// Or here you can also use $("#aucune").
var empty = $("input:checkbox[id=aucune]");
// Check if it is found.
if (empty.length > 0) {
// Remove the parent.
empty.parent().remove();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper-checkbox">
<input type="checkbox" class="outsider" id="xxx" name="xxx" date-name="xxx">
<label for="xxx">xxx</label>
</div>
<div class="wrapper-checkbox">
<input type="checkbox" class="outsider" id="aucune" name="aucune" date-name="aucune">
<label for="aucune">aucune</label>
</div>
Boom! And the checkbox is gone! :)
You can directly use the aucune id selector in your JQuery and then get the closest div with class wrapper-checkbox to remove it:
$(document).ready(function() {
var empty = $("#aucune");
if (empty.length !== 0){
$(empty).closest('.wrapper-checkbox').remove();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper-checkbox">
<input type="checkbox" class="outsider" id="xxx" name="xxx" date-name="xxx">
<label for="xxx">xxx</label>
</div>
<div class="wrapper-checkbox">
<input type="checkbox" class="outsider" id="aucune" name="aucune" date-name="aucune">
<label for="aucune">aucune</label>
</div>
Try to do this..
$(document).ready(function() {
var checkbox = $("input:checkbox[id=aucune]");
if (checkbox.length > 0) {
checkbox.parent().remove();
}
});
I have two fields: one is a checkbox (built with Scala), one is an input/text field. I am trying to add and remove values from the checkbox to the input field. I am trying to take multiple values and string together with a comma.
Here are my HTML fields:
<div class="column column1">
#for(service <- servicesList) {
<label><input type="checkbox" name="selectServices" value=#service.name><span>#service.name</span></label>
}
</div>
<input name="services" id="services">
I am using jQuery in a tag to try to record the onchange event:
$(document).ready(function(){
var $services = $('#services');
var $selectServices = $('#selectServices');
$selectServices.change(function(){
for (var i = 0, n = this.length; i < n; i++) {
if (this[i].checked) {
$services.val($services.val() + this[i].value);
}
else {
$services.val($services.val().replace(this[i].value, ""));
}
}
});
});
However, it seems that this will not "fire" when checking and unchecking the checkbox. I do not receive any errors or messages, so I am guessing it is not working or the code is incorrect.
I appreciate the help!
Try this example, you don't have to search and replace all the time, just set a new value:
$(function() {
$('input[name=selectServices]').on('change', function() {
$('#services').val($('input[name=selectServices]:checked').map(function() {
return this.value;
}).get());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="column column1">
<label>
<input type="checkbox" name="selectServices" value='1'><span>1</span>
</label>
<label>
<input type="checkbox" name="selectServices" value='2'><span>2</span>
</label>
<label>
<input type="checkbox" name="selectServices" value='3'><span>3</span>
</label>
<label>
<input type="checkbox" name="selectServices" value='4'><span>4</span>
</label>
</div>
<input name="services" id="services">
does the $(function() {} go into the $(document).ready(function(){}?
No, it is short-hand or equivalent for the same.
This is just an addition on #Halcyon his answer so you can create a nicer list, in stead of the replace method. #Halcyon is most definitely the correct answer why your check boxes aren't working. This is just a better solution handling values.
$(document).ready(function(){
var $services = $('#services');
var $selectServices = $('.selectServices');
$selectServices.change(function(){
updateServices();
});
function updateServices() {
var allVals = [];
$('.selectServices:checked').each(function() {
allVals.push($(this).val());
});
$services.val(allVals);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="column column1">
<label><input class="selectServices" type="checkbox" name="selectServices[]" value="Foo"><span>Foo</span></label>
<label><input class="selectServices" type="checkbox" name="selectServices[]" value="Bar"><span>Bar</span></label>
<label><input class="selectServices" type="checkbox" name="selectServices[]" value="FooBar"><span>FooBar</span></label>
</div>
<input name="services" id="services">
$('#selectServices') selects by id, there are no elements with that id. Ids must be unique so you can't use them in this case. I also wouldn't recommend using name because input elements should have unique names. You can use class:
<label><input type="checkbox" class="selectServices" ...
Then use .selectServices in jQuery. And:
var $selectServices = $('.selectServices');
$selectServices.change(function(){
if (this.checked) {
$services.val($services.val() + this.value);
} else {
$services.val($services.val().replace(this.value, ""));
}
});
Your code will fire if you add ID's to your inputs:
<input type="checkbox" name="selectServices" id="selectServices" value="" />
and
<input name="services" id="services" type="text" />
I have the following form :
<form class="form-inline" role="form">
<div class="col-xs-3">
<div class="pic-container">
<div class="checkbox">
<label>
<input type="checkbox" name="discounting" onchange='handleChange(this);' id='check11' > Show only price-discounted products
</label>
</div>
</div>
</div>
<div class="col-xs-3">
<div class="pic-container">
<div class="checkbox" id='check21'>
<label>
<input type="checkbox" name="discounting" onchange='' id='check21'> Show only price-discounted products
</label>
</div>
</div>
</div>
</form>
I'd like to be able to check the second checkbox automatically with JavaScript once I check the first one. I tried using the following script :
<script>
function handleChange(cb) {
if(cb.checked == true) {
alert('Message 1');
document.getElementById("check21").checked = true;
} else {
alert('Message 2');
var x = document.getElementById("check21").disabled= false;
}
}
</script>
But it doesn't work since I think with bootstrap is a question of classes.
The problem as Didier pointed out is that you have two elements with the same ID:
<div class="checkbox" id='check21'>
and
<input type="checkbox" name="discounting" onchange='' id='check21'>
The call to document.getElementById('check21') will probably (because the behavior is undefined) return the first one, which in this case is the <div> element, not the checkbox.
You must not use the same ID on two HTML elements, so you need to change the ID on one or the other of them.
http://jsfiddle.net/uywaxds5/2/
I included boostrap as an external reference.
<div class="checkbox" id='check22'>
<label>
<input type="checkbox" name="discounting" onchange='' id='check21'> Show only price-discounted products
</label>
</div>
Fixing the duplicate id seems to work.
If it does not works, the issue might be in another part of your code.
Use a different name for the second radio button
<input type="checkbox" name="discounting21">
There can only be one selected radio button belonging to the same group(ie. name).
I need your help with my problem.
I created a static form. With a lots of and checkboxes. My problem is, I am integrating a javascript code for the selection of checkboxes. When the user check the parent checkboxes it will automatically check the subcategory. I can do this one by one (hardcoded). But it is a lot of work. What I think is I will put all of the IDs in an array and create a loop or event that will access them. But I don't know how. Ok that's all.
Here's my code: I am using CI and jquery 1.5
//here's the array
var checkboxParentMenu = ["checkAllFilipino","checkAllContinental","checkAllAsian","checkAllOthers"];
var checkboxChildMenu = ["filipino_cat","continental_cat","asian_cat","others_cat"];
Now here's the manual way.
$("input[data-check='checkAllFilipino']").change(function(){
$("#filipino_cat").find("input[type=checkbox]").attr("checked",this.checked);
});
Here's the pattern sample
<div id="parentTab">
<div id="categoryTab">
<input type="checkbox" />
</div>
<div id="subCategoryTab">
<input type="checkbox" />
</div>
<div id="childOfSubCategory">
<input type="checkbox" />
</div>
....
</div>
The super easy way out would be to actually nest the divs, then you could do this:
$('input[type=checkbox]').click(function () {
$(this).parent().find('input[type=checkbox]').attr('checked', $(this).attr('checked'));
});
HTML:
<div id="parentTab">
<div id="categoryTab">
<input type="checkbox" />
<div id="subCategoryTab">
<input type="checkbox" />
<div id="childOfSubCategory">
<input type="checkbox" />
</div>
</div>
</div>
</div>
One easy way out is
var checkboxParentMenu = ["checkAllFilipino", "checkAllContinental", "checkAllAsian", "checkAllOthers"];
var checkboxChildMenu = ["filipino_cat", "continental_cat", "asian_cat", "others_cat"];
$.each(checkboxParentMenu, function (idx, name) {
$('input[data-check="' + name + '"]').change(function () {
$("#" + checkboxChildMenu[idx]).find("input[type=checkbox]").attr("checked", this.checked);
});
})
But I would recommend
<input type="checkbox" data-check="checkAllFilipino" data-target="#filipino_cat" />CHECK ALL
<br/>
then
$('input').filter('[data-check="checkAllFilipino"], [data-check="checkAllContinental"], [data-check="checkAllAsian"], [data-check="checkAllOthers"]').change(function () {
$($(this).data('target')).find("input[type=checkbox]").attr("checked", this.checked);
});
Demo: Fiddle
Use prop() in place of attr() like,
var checkboxParentMenu = ["checkAllFilipino","checkAllContinental","checkAllAsian","checkAllOthers"];
var checkboxChildMenu = ["filipino_cat","continental_cat","asian_cat","others_cat"];
$.each(checkboxParentMenu ,function(i,parentChk){
$("input[data-check='"+parentChk+'").on(change',function(){
$('#'+checkboxChildMenu[i]).find("input[type=checkbox]").prop("checked",this.checked);
});
});