Add/Remove values to field from checkbox values in Javascript - javascript

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" />

Related

WordPress: Allow to only check one checkbox in a fieldset

I'm using Gravity Forms and the quiz add-on to build a survey.
Every question should have only one accepted answer. But all answers should be "correct".
The quiz add-on works in a different way. It allows only one correct answer for radio buttons. I couldn't limit checkboxes to only one answer.
So I guess I have to work with custom JavaScript to allow only one answer or checked box per fieldset.
The fieldset for a question looks like this:
<fieldset id="field_3_1" class="gfield" data-field-class="gquiz-field">
<legend class="gfield_label gfield_label_before_complex">Question 1</legend>
<div class="ginput_container ginput_container_checkbox">
<div class="gfield_checkbox" id="input_3_1">
<div class="gchoice gchoice_3_1_1">
<input class="gfield-choice-input" name="input_1.1" type="checkbox" value="gquiz21dc402fa" id="choice_3_1_1">
<label for="choice_3_1_1" id="label_3_1_1">Answer 1</label>
</div>
<div class="gchoice gchoice_3_1_2">
<input class="gfield-choice-input" name="input_1.2" type="checkbox" value="gquiz3414cb0c0" id="choice_3_1_2">
<label for="choice_3_1_2" id="label_3_1_2">Answer 2</label>
</div>
<div class="gchoice gchoice_3_1_3">
<input class="gfield-choice-input" name="input_1.3" type="checkbox" value="gquiz21d0214b9" id="choice_3_1_3">
<label for="choice_3_1_3" id="label_3_1_3">Answer 3</label>
</div>
</div>
</div>
</fieldset>
It's not clear how many fieldsets/questions are present at the end. So I need a flexible solution.
I found some JS Code here:
$(function () {
$('input[type=checkbox]').click(function () {
var chks = document.getElementById('<%= chkRoleInTransaction.ClientID %>').getElementsByTagName('INPUT');
for (i = 0; i < chks.length; i++) {
chks[i].checked = false;
}
if (chks.length > 1)
$(this)[0].checked = true;
});
});
But I'm not sure how to adapt it for my use case
This script will make each checkbox per fieldset exclusive.
jQuery(function($) {
$('fieldset input[type="checkbox"]').on('change', function() {
// Set the checkbox just checked.
let just_checked = $(this);
// Get all of the checkboxes in the fieldset.
let all_checkboxes = just_checked.closest('fieldset').find('input[type="checkbox"]');
$.each(all_checkboxes, function(i, v) { // Loop through each of the checkboxes.
if (just_checked.prop('id') === $(v).prop('id')) {
// Check the one just checked.
$(v).prop('checked', true);
} else {
// Uncheck the others.
$(v).prop('checked', false);
}
})
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset id="field_3_1" class="gfield" data-field-class="gquiz-field">
<legend class="gfield_label gfield_label_before_complex">Question 1</legend>
<div class="ginput_container ginput_container_checkbox">
<div class="gfield_checkbox" id="input_3_1">
<div class="gchoice gchoice_3_1_1">
<input class="gfield-choice-input" name="input_1.1" type="checkbox" value="gquiz21dc402fa" id="choice_3_1_1">
<label for="choice_3_1_1" id="label_3_1_1">Answer 1</label>
</div>
<div class="gchoice gchoice_3_1_2">
<input class="gfield-choice-input" name="input_1.2" type="checkbox" value="gquiz3414cb0c0" id="choice_3_1_2">
<label for="choice_3_1_2" id="label_3_1_2">Answer 2</label>
</div>
<div class="gchoice gchoice_3_1_3">
<input class="gfield-choice-input" name="input_1.3" type="checkbox" value="gquiz21d0214b9" id="choice_3_1_3">
<label for="choice_3_1_3" id="label_3_1_3">Answer 3</label>
</div>
</div>
</div>
</fieldset>
An alternative solution could be to use radio buttons, and use css to make them look like checkboxes. But UX says that checkboxes shouldn't be used as radio buttons, and vice versa. For whatever that's worth.

Adding +1 in the end of the class

I have been studying JavaScript/JQuery lately on my free time. I am trying to make script choose between 2 checkboxes. If first checkbox is true then the second is false, if first one is false then second is true. This one works but it doesn't work on multiple classes. I have added 2 classes .checkbox-group1 and .checkbox-group2. I tried to make script add +1 to .checkbox-group 2 times but it only adds so I would get classes .checkbox-group1 and .checkbox-group2 but I only get .checkbox-group1.
Javascript/JQuery
$(document).ready(function(){
var i = 0;
if(i<2){
i++;
}
else{
i = 1;
}
$('.checkbox-group'+ i +' input:checkbox').click(function() {
$('.checkbox-group'+ i +' input:checkbox').not(this).prop('checked', false);
});
});
HTML CHECKBOXES
<div class="checkbox-group1 required">
Yes: <input type="checkbox">
No: <input type="checkbox">
</div>
<div class="checkbox-group2 required">
yes: <input type="checkbox">
No: <input type="checkbox" >
</div>
You dont need a loop, you can get the right checkbox in a var and then set all checkbox of the div to false. Finally, you set the right one to checked.
I commented my code.
$(document).ready(function(){
// we get div with class name starting like : checkbox-group
$("div[class^='checkbox-group'],div[class*='checkbox-group']").click(function(event) {
// we save current clicked element in a var
var getCurrentChecked = event.target;
// we set all input checked to false
$(this).find('input:checkbox').prop('checked', false);
// then we check the right one
$(getCurrentChecked).prop('checked', true);
console.log($(this).attr('class') + ' - ' + $(getCurrentChecked).val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
HTML CHECKBOXES
<div class="checkbox-group1 required">
Yes: <input type="checkbox" value="0">
No: <input type="checkbox" value="1">
</div>
<div class="checkbox-group2 required">
yes: <input type="checkbox" value="0">
No: <input type="checkbox" value="1">
</div>

Create a dynamic link based on checkbox values

What I'm trying to achieve is this:
Default state of page = no checkboxes ticked, no link shown
User ticks one (or more) checkboxes
Link appears, dynamically generated from the checkbox values, in the following format: http://example.com/?subject=Products&checked=Blue,Green,Purple (where the selected checkbox values are "Blue", "Green" and "Purple")
Thus far, based on advice from another question (Using JavaScript to load checkbox Values into a string), I've been able to get the values in the proper format (as part of the required url) printed to console.log via a button:
$("button").on("click", function(){
var arr = []
$(":checkbox").each(function(){
if($(this).is(":checked")){
arr.push($(this).val())
}
})
var vals = arr.join(",")
var str = "http://example.com/?subject=Products&" + vals
console.log(str)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="checkbox" id="selected" name="selected" value="Blue" class="products"> Blue<br>
<input type="checkbox" id="selected" name="selected" value="Green" class="products"> Green<br>
<input type="checkbox" id="selected" name="selected" value="Purple" class="products"> Purple
<br>
<button>button</button>
However, they're not loading dynamically based on the selected checkboxes (it requires you to press the button in order to generate the url) and the link hasn't been printed to the page for use by visitors (it's stuck in console.log, visible but not usable).
I've been advised that .change() might be the way to go here, in terms of generating the link dynamically. Something like: jQuery checkbox change and click event.
How can I merge the two approaches to achieve the result I'm looking for?
This would work to give you a url of
http://example.com/?subject=Products&checked=Blue,Green,Purple
(see below for a possibly better way):
$(document).on("change", ".mod-link", function() {
var arr = []
$(".mod-link:checked").each(function() {
arr.push($(this).val());
})
var vals = arr.join(",")
var str = "http://example.com/?subject=Products&checked=" + vals;
var link = arr.length > 0 ? 'Click me': '' ;
$('.link-container').html(link);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="mod-link" name="selected" value="Blue" class="products">Blue
<br>
<input type="checkbox" class="mod-link" name="selected" value="Green" class="products">Green
<br>
<input type="checkbox" class="mod-link" name="selected" value="Purple" class="products">Purple
<br>
<div class="link-container"></div>
However
I would do it a bit different.
I would opt for the following url structure:
http://example.com/?subject=Products&checked[]=Blue&checked[]=Green&checked[]=Purple
When that is recieved by PHP, checked will be an array like ['Blue','Green','Purple'] instead of a string like 'Blue,Green,Purple'
$(document).on("change", ".mod-link", function() {
var arr = []
$(".mod-link:checked").each(function() {
arr.push($(this).val());
})
var vals = 'checked[]=' + arr.join("&checked[]=")
var str = "http://example.com/?subject=Products&" + vals;
var link = arr.length > 0 ? 'Click me': '' ;
$('.link-container').html(link);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="mod-link" name="selected" value="Blue" class="products">Blue
<br>
<input type="checkbox" class="mod-link" name="selected" value="Green" class="products">Green
<br>
<input type="checkbox" class="mod-link" name="selected" value="Purple" class="products">Purple
<br>
<div class="link-container"></div>
I believe that you were on the right track, if I understood your question correctly. I added the change event on you checkboxes as you suggested. Try the modified code below.
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="checkbox" name="selected" value="Blue" class="products"> Blue<br>
<input type="checkbox" name="selected" value="Green" class="products"> Green<br>
<input type="checkbox" name="selected" value="Purple" class="products"> Purple
<br>
<span class="link"></span>
JavaScript
$("input[type=checkbox]").on("change", function(){
var arr = []
$(":checkbox").each(function(){
if($(this).is(":checked")){
arr.push($(this).val())
}
})
var vals = arr.join(",")
var str = "http://example.com/?subject=Products&checked=" + vals
console.log(str);
if (vals.length > 0) {
$('.link').html($('<a>', {
href: str,
text: str
}));
} else {
$('.link').html('');
}
})
Working CodePen
Your button is no longer being used. Is this what you were looking for?

jquery syntax for .on("change","input[name^=

Project Focus
Toggle Checkbox(es)
Special Requirement
Need to bind the new(dynamically) added div.id container that holds these checkboxes. Note: this div.id has been dynamically generated (client-side).
Status
My Working Fiddle successfully toggles between 1(one) or 0(none) checkboxes.
The HTML
<div id="bind_id">
<input type="checkbox" name="iso_01[]" class="setTitlePre1" value="L/R" />
<label for name "iso_01" class="isoVar1">No.1</label>
<input type="checkbox" name="iso_01[]" class="setTitlePre2" value="Alt" />
<label for name "iso_01" class="isoVar2">No.2</label>
</div>
Working Script
var checkboxes;
checkboxes = $("input[name^=iso_01]").change(function (e) {
checkboxes.not(this).prop("checked", false);
}
});
Desired Result
I'm having trouble with syntax for updating .click() to .on("click","input..." see Bound Fiddle
Updated Script
var checkboxes;
checkboxes = $("#bind_id").on("change", "input[name^=iso_01]", function (e) {
if (this.checked) {
checkboxes.not(this).prop("checked", false);
}
});
Your issue is,
checkboxes = $("#bind_id").on
is not doing what you think it is doing. It is not storing all the matched nodes.
Try this instead:
In the callback, change
checkboxes.not(..)
to
$('input[name^=iso_01]').not(this).prop("checked", false);
Working fiddle
Or if they are loaded dynamically, you can use $('#bind_id').find('input[name^=iso_01]')
This is not what checkboxes are for. You should be using radio buttons:
<input type="radio" name="example" value="1" id="1">
<label for="1">one</label>
<input type="radio" name="example" value="2" id="2">
<label for="2">two</label>
The problem is checkboxes is the #bind_id element, not the checkboxes. You would need to find the children from that element, to get the child checkbox elements.
Working Example:
var wrapper;
wrapper = $("#bind_id").on("change", "input[name^=iso_01]", function (e) {
if (this.checked) {
wrapper.find("input[name^=iso_01]").not(this).prop("checked", false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="bind_id">
<input type="checkbox" name="iso_01[]" class="setTitlePre1" value="L/R" />
<label for name "iso_01" class="isoVar1">No.1</label>
<input type="checkbox" name="iso_01[]" class="setTitlePre2" value="Alt" />
<label for name "iso_01" class="isoVar2">No.2</label>
</div>

How to access an array of ID using an event trigger with checkboxes?

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);
});
});

Categories