Get label names only for those inputs whose checkbox is checked - javascript

I have a fieldset Like Below
<div class="ui-field-contain">
<fieldset id="fieldstep1" data-role="controlgroup">
<legend>Choose Sections:</legend>
<input name="checkbox-1a" id="checkbox-1a" type="checkbox">
<label for="checkbox-1a">Morning</label>
<input name="checkbox-2a" id="checkbox-2a" checked type="checkbox">
<label for="checkbox-2a">Evening</label>
<input name="checkbox-3a" id="checkbox-3a" checked type="checkbox">
<label for="checkbox-3a">Night</label>
<input name="checkbox-4a" id="checkbox-4a" checked type="checkbox">
<label for="checkbox-4a">Snacks</label>
</fieldset>
</div>
I need to get all the label names for checked Checkbox.
Rightnow i use this code.This returns all the lable names.
$('#fieldstep1').find('label').each(function(){
var a = $(this).text();
alert(a);
});
Here is the Js fiddle - http://jsfiddle.net/sGy38/

You can do it like this:
$('#fieldstep1').find('label').each(function () {
if ($('#' + $(this).attr('for')).is(':checked')) {
var a = $(this).text();
alert(a);
}
});
Explanation: For each label $('#' + $(this).attr('for')) gets the checkbox to the label and .is(':checked') checks if it is checked.
See the updated fiddle.

Try
$('#fieldstep1 input:checkbox:checked + label').each(function(){
var a = $(this).text();
alert(a);
});
Demo: Fiddle
See
next adjacent selector
checked selector
checkbox selector
After checking the demo site:
$('#fieldstep1 input:checkbox:checked').prev().each(function () {
var a = $(this).text();
console.log(a);
});

Related

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>

Add/Remove values to field from checkbox values in 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" />

Insert checkboxes values(name) into input with jQuery

I'm working with Symfony and I have a lot of checkboxes with different id and value, so when I check one, i want to automatically insert its value (name) into an input and when I check other insert its value in the same input:
<input type="checkbox" name="{{ent.username}}" value="{{ent.username}}">
Thanks everyone
That does not depend on Symphony.
jQuery:
$(function() { // when page loads
$("input[type='checkbox']").on("click",function() {
if (this.checked) $("#somefield").val(this.value);
});
});
Plain JS:
window.onload=function() { // when page loads
document.querySelectorAll("input[type='checkbox']").forEach(function() {
this.onclick=function() {
if (this.checked) document.getElementById("somefield").value=this.value;
}
}
}
Steps to follow:
Add change listener on each input field of checkbox type.
Get all the selected fruit by iterating each checkbox.
Set the value of selected fruits in the field.
Running sample code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="checkbox" value="Banana">Banana</input>
<input type="checkbox" value="Apple">Apple</input>
<input type="checkbox" value="Mangeo">Mango</input>
<input type="checkbox" value="Orange">Orange</input>
</div>
<div>
Selected Fruit : <input type="text" id="fruit">
</div>
<script>
var fruit = $('#fruit');
$('input[type="checkbox"]').change(function(e){
fruit.val(getSelectedFruits());
});
function getSelectedFruits(){
var fruits = "";
$('input[type="checkbox"]').each(function(i,cb){
if($(this).is(":checked")){
fruits += $(this).val() + " ";
}
});
return fruits;
}
</script>

Repeative values occur in Autocomplete jquery

I am working in ASP.NET Project.My task is to Prevent the repative values occured in Textbox.Textbox is bound with autocomplete and appending text from checkboxlist as like in the below picture
! https://drive.google.com/file/d/0B5OPwgmPG6QpTHBTdVlFaldRaEE/view?usp=sharing
After i appended the content from checkbox list to textbox means it is repeating value,if i typed it inital time it won't.And my task is to show unique values based on the textbox content.
My project files are in the below link..please help me out guys
https://drive.google.com/file/d/0B5OPwgmPG6QpS3NMNElGN2k4RzQ/view?usp=sharing
Based on my answer I gave you in the other thread (https://stackoverflow.com/a/28828842/4569271) I extended my solution to only display unique values:
$(function() {
$('input[type="checkbox"]').change(function() {
// Reset output:
$("#output").html('');
// remeber all unique values in this array:
var tmpArray = new Array();
// Repeat for all checked checkboxes:
var checkboxes = $('input[type="checkbox"]:checked').each(function() {
// Get value from checkbox:
var textToAppend = $(this).val();
// Check if value from checkbox was added already:
if (jQuery.inArray(textToAppend, tmpArray) == -1) {
// add entry to array so it will be not added again:
tmpArray.push(textToAppend);
var existingText = $("#output").html();
// Append seperator (';') if neccessary:
if (existingText != '') {
existingText = existingText + ";";
}
// Print out append value:
$("#output").html(existingText + textToAppend);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Select:</h2>
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Mar" />Mar
<input type="checkbox" value="Mar" />Mar
<input type="checkbox" value="Mar" />Mar
<h2>Output:</h2>
<div id="output"></div>
Based on your description, I am not sure if this is the solution you were looking for? But maybe it helps.

Control Radio Buttons with a Checkbox

I'm using a CMS that hides form elements behind tags, because of some system quirks I've had to set up a checkbox that controls the radio buttons so if the checkbox is ticked the "yes" radio button is selected if not the "no" is selected. I also want the radio buttons to have option "no" checked by default but I don't have control over the line of code for the radio buttons.
I found some Javascript that does a small part of this but I want to integrate it into the jQuery that displays and hides content when the box is ticked.
Here's what I have so far:
$('#checkbox1').change(function() {
$('#content1').toggle("slow");
});
The Javascript I have is this:
function ticked(){
var ischecked = document.getElementById("checkbox").checked;
var collection = document.getElementById("hideradio").getElementsByTagName('INPUT');
if(ischecked){collection[0].checked = true;}else{collection[0].checked = false;}
}
Can you please help write a version of the Javascript but integrate with my jQuery?
Thanks,
You can try this, I assume your html as like this.
<input type="checkbox" id="checkbox1" /> Check Box
<div id="content1" >
Some Content <br />
Some Content <br />
Some Content <br />
Some Content
</div>
<div id="hideradio">
<input type="radio" name="rgroup" value="yes" /> Yes
<input type="radio" name="rgroup" value="no" /> No
</div>
JQuery
$(function(){
$('#hideradio input[type=radio][value=no]').attr('checked',true);
$('#content1').hide();
});
$('#checkbox1').on('change', function() {
$('#content1').toggle("slow");
var self = this;
if(self.checked)
$('#hideradio input[type=radio][value=yes]').attr('checked',true);
else
$('#hideradio input[type=radio][value=no]').attr('checked',true);
});
A Quick DEMO
Try this code
​
$(function(){
$('#checkbox1').on('click' , function() {
var isChecked = $(this).is(':checked');
if(isChecked){
$('#radio1').attr('checked' , true);
$('#content1').toggle("slow");
}
else{
$('#radio1').attr('checked' , false);
}
});
});​
Check [FIDDLE]
If I don't understand correctly then let me know.
I don't know your HTML code so I provide one
<form>
<input type="checkbox" name="test_ck" id="test_ck" />
<br/>
<input type="radio" name="test_radio" id="test_radio" />
</form>
<div id="content"> A content !!! </div>
and javascript jquery
$(function(){
$("#test_ck").on("change", function(){
$("#test_radio").prop("checked", $(this).is(":checked"));
$("#content").toggle("slow");
});
});
Example -> jsfiddle
UPDATED jsfiddle
http://jsfiddle.net/6wQxw/2/
jsfiddle
$(document).on('change', '#checkbox', function() { toggle(this); });
var toggle = function(obj) {
var checked = $(obj || '#checkbox').is(':checked');
$(':radio[value=no]').prop('checked', !checked);
$(':radio[value=yes]').prop('checked', checked);
$('#content').toggle(checked);
}
toggle();
This is a pure JavaScript solution, no need to use jQuery:
<body>
<label for="a">Male</label>
<input type="radio" id="a">
<br/>
<label for="b">Female</label>
<input type="radio" id="b">
<script type="text/javascript">
var nodes = document.querySelectorAll("input[type=radio]");// get elements
var arr = Array.prototype.slice.call(nodes); // convert nodes to array for use in forEach
arr.forEach(function(obj){
obj.addEventListener("change",function(e){
arr.forEach(function(obj){
obj.checked = false;//make other radio false
});
this.checked = true;// make this radio ture
});
});
</script>
</body>

Categories