Insert checkboxes values(name) into input with jQuery - javascript

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>

Related

How to know if a checkbox is checked onmouseover corresponding label

I want to perform certain actions when hovering over checkbox-labels, but only when the checkboxes are checked.
How can I retrieve that information?
HTML
<input clrcheckbox="" type="checkbox" id="checks">
<label for="checks">Check</label>
JS
document.querySelector('label').onmouseover = () => {
//so here should be something like:
//if(checkbox is checked) {console.log('checked')}
console.log('over');
}
Here a solution with jQuery
<input clrcheckbox="" type="checkbox" id="checks">
<label for="checks">Check</label>
<script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
<script>
$(document).ready(function(){
var isChecked = function(){
if ($('#checks').filter(':checked').length > 0){
console.log('Do some action')
}
}
$('#checks').mouseover(isChecked)
$('label').mouseover(isChecked)
})
</script>
https://codesandbox.io/s/strange-sunset-nkq5q

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.

Get label names only for those inputs whose checkbox is checked

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

jQuery Store Values of checkboxes in div

How can I get this list of checkboxes to be added to a div prior to their selected state, so if they are selected, they should be added to the div, if not they are removed from the list if not selected.
<div id="selected-people"></div>
<input type="checkbox" value="45" id="Jamie" />
<input type="checkbox" value="46" id="Ethan" />
<input type="checkbox" value="47" id="James" />
<input type="checkbox" value="48" id="Jamie" />
<input type="checkbox" value="49" id="Darren" />
<input type="checkbox" value="50" id="Danny" />
<input type="checkbox" value="51" id="Charles" />
<input type="checkbox" value="52" id="Charlotte" />
<input type="checkbox" value="53" id="Natasha" />
Is it possible to extract the id name as the stored value, so the id value will be added to the div instead of the value - the value needs to have the number so that it gets added to a database for later use.
I looked on here, there is one with checkboxes and a textarea, I changed some parts around, doesn't even work.
function storeuser()
{
var users = [];
$('input[type=checkbox]:checked').each(function()
{
users.push($(this).val());
});
$('#selected-people').html(users)
}
$(function()
{
$('input[type=checkbox]').click(storeuser);
storeuser();
});
So you want to keep the DIV updated whenever a checkbox is clicked? That sound right?
http://jsfiddle.net/HBXvy/
var $checkboxes;
function storeuser() {
var users = $checkboxes.map(function() {
if(this.checked) return this.id;
}).get().join(',');
$('#selected-people').html(users);
}
$(function() {
$checkboxes = $('input:checkbox').change(storeuser);
});​
Supposing you only have these input controls on page I can write following code.
$.each($('input'), function(index, value) {
$('selected-people').append($(value).attr('id'));
});
Edited Due to More Description
$(document).ready(function() {
$.each($('input'), function(index, value) {
$(value).bind('click', function() {
$('selected-people').append($(value).attr('id'));
});
});
});
Note: I am binding each element's click event to a function. If that doesn't work or it isn't a good for what you are supposed to do then change it to on "change" event.
Change:
users.push($(this).val());
to:
users.push($(this).attr('id'));
This is for to bind the comma seperated values to input checkbox list
$(".chkboxes").val("1,2,3,4,5,6".split(','));
it will bind checkboxes according to given string value in comma seperated.

hiding div based on unchecking checkboxes

I have multiple checkboxes in a form. Based on clicking those checkboxes, I show a div section. But if I uncheck even one checkbox, that div section gets hidden. How do I make sure that div section is hidden only if all checkboxes are unchecked. Crude way can be to write my own 'display' method which will check if all checkboxes are unchecked and then hide the div section. Any easier solution??
HTML:
<input type="checkbox" class="group" name="check1">
<input type="checkbox" class="group" name="check2">
<input type="checkbox" class="group" name="check3">
<input type="checkbox" class="group" name="check4">
jQuery:
$(function() {
var $checks = $('input:checkbox.group');
$checks.click(function() {
if($checks.filter(':checked').length == 0) {
$('#div').hide();
} else {
$('#div').show();
}
});
});
The following code will show the div if one or more checkboxes has been checked:
jQuery
Version 1:
$("input[name='mycheckboxes']").change(function() {
$("#showme").toggle($("input[name='mycheckboxes']:checked").length>0);
});
Version 2 (more efficient):
var MyCheckboxes=$("input[name='mycheckboxes']");
MyCheckboxes.change(function() {
$("#showme").toggle(MyCheckboxes.is(":checked"));
});
HTML
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<div id="showme" style="display: none">Show me</div>
Code in action (Version 1).
Code in action (Version 2).
--- Different Checkbox Names Version ---
For different named checkboxes, wrap them in a DIV with an identifier. E.g.
jQuery
var MyCheckboxes=$("#checkboxgroup :checkbox");
MyCheckboxes.change(function() {
$("#showme").toggle(MyCheckboxes.is(":checked"));
});
HTML
<div id="checkboxgroup">
<input type="checkbox" name="mycheckbox1" />
<input type="checkbox" name="mycheckbox2" />
<input type="checkbox" name="mycheckbox3" />
<input type="checkbox" name="mycheckbox4" />
</div>
<div id="showme" style="display: none">Show me</div>
This code in action.
Not really, you need Javascript for this one... Or maybe... Let's say:
<html>
<head>
<style type="text/css">
#input_container > input + input + input + div {display:none}
#input_container > input:checked + input:checked + input:checked + div {display:block}
</style>
</head>
<div id="input_container">
<input type="checkbox">blah1
<input type="checkbox">blah2
<input type="checkbox">blah3
<div>To show/hide</div>
</div>
</body>
</html>
I'd create a function that uses a variable that tracks the number of checkboxes checked:
var numberOfChecks = 0;
function display(ev) {
var e = ev||window.event;
if (this.checked) {
numberOfChecks++;
} else {
numberOfChecks--;
}
if (!numberOfChecks) {
//hide div code
} else {
//display div code
}
}
Use that function for each onClick event for every checkbox. In the ideal world this would be done inside some initialization function so that numberOfChecks and display aren't in the global namespace.
Plain Javascript:
HTML
<div id="checkboxes">
<input type="checkbox" name="check1">
<input type="checkbox" name="check2">
<input type="checkbox" name="check3">
<input type="checkbox" name="check4">
</div>
<div id="hiddendiv"><!-- more stuff --></div>
Javascript
(function() { //Create clousre to hide the checked variable
var checked = 0;
var inputs = document.getElementById('checkboxes').getElementsByTagName('input');
for (var i=0, l=inputs.length; i<l; i++) {
if (inputs[i].type == 'checkbox') {
if (inputs[i].checked) checked++; //Count checkboxes that might be checked on page load
inputs[i].onchange = function() {
checked += this.checked ? 1 : -1;
var hiddendiv = document.getElementById('hiddendiv');
if (!checked) hiddendiv.style.display = "none";
else hiddendiv.style.display = "";
};
}
}
}());
The other option is to simply iterate through each checkbox every time the change event is fired rather than relying on counting, which is probably more error prone. Obviously jQuery is more concise, but a little verbosity never hurt anyone.
function toggleCheckbox(id) {
if ($("input[id=" + id + "]").is(':checked')) {
$( "#"+id ).prop( "checked", false );
} else {
$( "#"+id ).prop( "checked", true );
}
}
Just pass the id of your checkbox

Categories