Insert a multiple choice in a html page - javascript

What I have to do is to make the user select some languages among those present on a page and get an array or a string that contains all the selected languages.
Do you know how can I do?
The string or array it will serve subsequently in a JavaScript method.

you could use some checkboxes and save the values in an array like this:
var lang = [];
$('.cbLang').on('change', function() {
this.checked ? lang.push(this.value) : removeLang(this.value);
console.log(lang);
});
//REMOVE UNCHECKED LANGUAGE
function removeLang(removeLang){
lang = jQuery.grep(lang, function(value) {
return value != removeLang;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="cbLang" type="checkbox" value="English">English
<input class="cbLang" type="checkbox" value="German">German
<input class="cbLang" type="checkbox" value="French">French
EDIT: If you also need a way to remove it from the array, check the JQuery grep(): http://api.jquery.com/jquery.grep/
EDIT2: I've added a function to remove a unchecked language from the array. This method calls, when a checkbox was unchecked and gives the value of the language as parameter. It should work like this.
Cheers

javascript
var lang = [];
$('.cbLang').on('change', function() {
''
this.checked ? lang.push(this.value) : removeLang(this.value);
console.log(lang);
});
html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="cbLang" type="checkbox" value="English">English
<input class="cbLang" type="checkbox" value="German">German
<input class="cbLang" type="checkbox" value="French">French

Related

How do I change the "checked" attribute of a check box when clicked?

I am currently trying to build a list with checkboxes that can be easily checked/unchecked to be included or excluded. When the page loads most of the list items will have the checkbox "checked" attribute to show that the item is included. Im trying to change the checkbox attribute when the user changes the selection so that I can save the results.
I Have tried a few combinations that I have found here on Stackoverflow but none are changing the attribute, Im not sure what Im doing wrong.
function check() {
if ($("#working").prop("checked", true)) {
$("#working").prop("checked", false)
} else {
$("#working").prop("checked", true)
}
}
var data = {
id: document.getElementById('workingId').value,
visible: document.getElementById('working').checked
};
$(document).on("click", ".save", function() {
alert(data);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="workingId" value="13245">
<input type="checkbox" name="working" id="working" onclick="check(this);" checked> I am a check box
<button type="button" class="btn save"> Save</button>
I am hoping to print an array that has an ID for the checkbox (12345) and whether the checkbox is now checked/unchecked. Any help with this would be greatly appreciated.
I don't know if I understand your question right. Is this what you want ?
var data = {};
function check() {
if ($("#working").prop("checked")) {
data = {
id: document.getElementById('workingId').value,
visible: document.getElementById('working').checked
};
} else {
data = {};
}
}
$(document).on("click", ".save", function() {
console.log(data);
});
check();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="workingId" value="13245">
<input type="checkbox" name="working" id="working" onclick="check(this);" checked> I am a check box
<button type="button" class="btn save"> Save</button>
here's a way to do it with multiple checks:
var data = {};
function check() {
data = {};
$("[name=working]").each((ign, o)=>{
if ($(o).prop('checked'))
data[o.id] = $(o).attr('data-val');
});
}
$(document).on("click", ".save", function() {
console.log(data);
});
check();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" data-val="13245" name="working" id="working1" onclick="check(this);" checked> I am a check box
<br>
<input type="checkbox" data-val="23245" name="working" id="working2" onclick="check(this);" checked> I am other check box
<br>
<input type="checkbox" data-val="33245" name="working" id="working3" onclick="check(this);" checked> I am yet another check box
<button type="button" class="btn save"> Save</button>
Try this:
var $checkBox = $("#working");
var data = {
id: $("#workingId").val(),
visible: $checkBox.is(":checked")
};
$(".save").on("click", function () {
data.visible = $checkBox.is(":checked");
alert(JSON.stringify(data));
});
// Do other things with the 'data' object...
No onclick="check(this);" logic is needed.
Notes:
Consider switching to the latest JS. I see that you're still writing in ES5.
Consistency is very importing when developing. If already importing jQuery, consider using it across the board. I see in your initial logic that you use it for some element selection and not others.
When accessing the DOM via JS, with or without jQuery, try to stay as DRY as possible. For example, if you need to access the working div in more than one place, store the query selection in a variable. Resource-wise, DOM access/manipulation is not as cheap as variable creation.
Additionally, you can use an HTML data-* attribute in your checkbox element to store the "workingId" and remove your hidden element(s) entirely.

Check one checkbox when other is selected [duplicate]

I want the checkbox with the value 2 to automatically get checked if the checkbox with the value 1 is checked. Both have the same id so I can't use getElementById.
html:
<input type="checkbox" value="1" id="user_name">1<br>
<input type="checkbox" value="2" id="user_name">2
I tired:
var chk1 = $("input[type="checkbox"][value="1"]");
var chk2 = $("input[type="checkbox"][value="2"]");
if (chk1:checked)
chk2.checked = true;
You need to change your HTML and jQuery to this:
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
chk1.on('change', function(){
chk2.prop('checked',this.checked);
});
id is unique, you should use class instead.
Your selector for chk1 and chk2 is wrong, concatenate it properly using ' like above.
Use change() function to detect when first checkbox checked or unchecked then change the checked state for second checkbox using prop().
Fiddle Demo
Id should be unique, so that set different ids to your elements, By the way you have to use .change() event to achieve what you want.
Try,
HTML:
<input type="checkbox" value="1" id="user_name1">1<br>
<input type="checkbox" value="2" id="user_name2">2
JS:
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
chk1.change(function(){
chk2.prop('checked',this.checked);
});
You need to change the ID of one. It is not allowed by W3C standard (hence classes vs ID's). jQuery will only process the first ID, but most major browsers will treat ID's similar to classes since they know developers mess up.
Solution:
<input type="checkbox" value="1" id="user_name">1<br>
<input type="checkbox" value="2" id="user_name_2">2
With this JS:
var chk1 = $('#user_name');
var chk2 = $('#user_name2');
//check the other box
chk1.on('click', function(){
if( chk1.is(':checked') ) {
chk2.attr('checked', true);
} else {
chk2.attr('checked', false);
}
});
For more information on why it's bad to use ID's see this: Why is it a bad thing to have multiple HTML elements with the same id attribute?
The error is probably coming here "input[type="checkbox"]
Here your checkbox is out of the quotes, so you query is looking for input[type=][value=1]
Change it to "input[type='checkbox'] (Use single quote inside double quote, though you don't need to quote checkbox)
http://api.jquery.com/checked-selector/
first create an input type checkbox:
<input type='checkbox' id='select_all'/>
$('#select_all').click(function(event) {
if(this.checked) {
$(':checkbox').each(function() {
this.checked = true;
});
}
});

Pass Array HTML Element(s) in JavaScript

I have array of checkboxes like below,
<input type="checkbox" value="1" id="a_r_id[1]" name="a_r_id[1]">
<input type="checkbox" value="1" id="a_r_id[2]" name="a_r_id[2]">
<input type="checkbox" value="1" id="a_r_id[3]" name="a_r_id[3]">
<input type="checkbox" value="1" id="a_r_id[4]" name="a_r_id[4]">
in my page... and i want to submit only the checked one via JavaScript (jQuery AJAX)... how can i do that ?
EDITED :
Actually, i want to get all array keys on the checked checkbox so that i can post it via ajax. Something like "1,4" as a string.
var keys = [],
keystring;
$('input[name^="a_r_id"]:checked').each(function () {
keys.push($(this).attr('name').replace(/a_r_id\[(\d+)\]/, '$1'));
});
keystring = keys.join();
Of course, there are better ways of doing this, but this answers your question as you've framed it.
Finally, i found an answer for my question above. I'll write it down right here.
Problem :
how can i get "key" from array HTML element(s) ? (in my case, only checked checkbox i want to get)
my answer code is something like this :
//first, i get every checked checkbox using jQuery selector,
//as mentioned by DerekHenderson.
var list_agent = $('input[name^="a_r_id"]:checked');
var l_c_agent = new Array();
//then, i create a loop to loop each object returned.
for(var i=0;i<list_agent.length;i++){
//after that, i'm using Regular Expression ( match() ) on every returned object id and throw it into some array.
l_c_agent[i] = list_agent[i].id.match(/[0-9]+/);
}
//finally, i join the array using javascript join() method so that i can pass it using jQuery AJAX as a string to my controller and process it.
var clean_agent_list = l_c_agent.join();
var add_url = 'test.php';
$.ajax({
url: add_url,
type: "GET",
data : { 'list_agent' : clean_agent_list },
success: function(data_return) {
//alert(data_return);
}
});
the output will be something like this (if using my example question above and we're check element with id 1,3 and 4 only)
1,3,4
if anybody have a better code, please write it here so that we can discuss which is better to solve my problem.
The method you want seems a bit backwards; the browser will already submit only the checked checkboxes, but here goes:
var re = /\[(\d+)\]$/,
numbers = [];
$('input[name^="a_r_id\\["]:checked').each(function() {
numbers.push(+this.name.match(re)[1]);
});
console.log(numbers.join(','));
It selects all checked boxes whose name starts with "a_r_id[". Then, a regular expression is used to extract the number portion between square brackets and added to the list of values.
I think you want to do something like this
<input type="checkbox" value="1" id="a_r_id_1" name="a_r_id[]">
<input type="checkbox" value="2" id="a_r_id_2" name="a_r_id[]">
<input type="checkbox" value="3" id="a_r_id_3" name="a_r_id[]">
<input type="checkbox" value="4" id="a_r_id_4" name="a_r_id[]">
Radio Buttons seems to be more applicable here rather than checkboxes try this:
<input type="radio" name="radiogroup" value="1" id="a_r_id[1]" name="a_r_id[1]">
<input type="radio" name="radiogroup" value="2" id="a_r_id[2]" name="a_r_id[2]">
<input type="radio" name="radiogroup" value="3" id="a_r_id[3]" name="a_r_id[3]">
You can get the selected value using
$("input:radio[name=radiogroup]").click(function() {
var value = $(this).val();
//
do something with var
//
});

keep checkboxes checked after page refresh

I have a couple of checkboxes. when any of them are clickd/checked and the search button is clicked, will grab their values and pass to the url as querystring and refresh the page returning results matching the passed query values.
like this: mysite.com/result.aspx?k="Hospital" OR "Office" OR "Emergency"
I am able to grab the values after 'k='. I have "Hospital" OR "Office" OR "Emergency" captured and stored in a variable. Now I need to reset the checked state of checkboxes based on these values after the page reloads and forgets the previous state of the controls. I couldn't move any further than this. Can someone help me?
var checkedOnes=decodeURI(location.href.match(/\&k\=(.+)/)[1]);
if (value.length == 2) {
$('input[name="LocType"][value="' + value[1] + '"]').prop('checked', true);
}
This is how I am capturing the checkboxes values and passing to the URL:
var checkboxValues = $("input[name=LocType]:checked").map(function() {
return "\"" + $(this).val() + "\"";}).get().join(" OR ");
window.location= url+checkboxValues;
<div class="LocTypeChkBoxesSearch">
<div class="LocTypeChkBoxes">
<input name="LocType" type="checkbox" value="Hospital"/>HOSPITALS  
<input name="LocType" type="checkbox" value="Office"/> PHYSICIAN OFFICES  
<input name="LocType" type="checkbox" value="Emergency"/>EMERGENCY CENTERS  
<input name="LocType" type="checkbox" value="Out-Patient"/>OUT-PATIENT CENTERS  
<input name="LocType" type="checkbox" value="Facility"/>FACILITIES
</div>
<div class="searchBtnHolder"><a class="searchButton" href="#" type="submit" ><span>GO</span></a></div>
</div>
I've faced same problem, and my solution is HTML5 Local Storage.
Add an function for colect checkboxes values
function(){
var data = $('input[name=checkboxName]:checked').map(function(){
return this.value;
}).get();
localStorage['data']=JSON.stringify(data);
}
And onload function to check checkboxes
function(){
if(localStorage&&localStorage["data"]){
var localStoredData=JSON.parse(localStorage["data"]);
var checkboxes=document.getElementsByName('checkboxName');
for(var i=0;i<checkboxes.length;i++){
for(var j=0;j<localStoredData.length;j++){
if(checkboxes[i].value==localStoredData[j]){
checkboxes[i].checked=true;
}
}
}
localStorage.removeItem('data');
}
}
It's work fine to me.
You shouldn't need JavaScript for this. You can check the $_GET parameters in your back-end code, and serve the page with the proper form element attributes.
In PHP, for example:
<input name="LocType" type="checkbox" value="Facility" <?php if (isset($_GET['LocType'] && $_GET['LocType'] == 'Facility') { ?> checked="checked" <?php } ?> /> FACILITIES
Try this.
//Split the url parameter value and get all the values in an array
var checkedOnes = decodeURI(location.href.match(/\&k\=(.+)/)[1]).split(" OR ");
//Find all the checkbox with name="LocType" and cache them in local variable
var $checkBoxes = $('input[name=LocType]');
//Loop through the array and find the corresponding checkbox element using filter
$.each(checkedOnes, function(i, val){
$checkBoxes.filter('value=[' + $.trim(val.replace(/\"/g, '')) +']').prop('checked', true);
});
I am splitting the value of k by OR which will give all the values in an array. Next, loop through the array and find the corresponding checkbox by matching its value attribute and set its checked property to true using prop method.

Select values of checkbox group with jQuery

I'm using Zend_Form to output a set group of checkboxes:
<label style="white-space: nowrap;"><input type="checkbox" name="user_group[]" id="user_group-20" value="20">This Group</label>
With a normal HTTP Post these values are passed as an array, but when I'm somewhat stumped on how to grab all the values using jQuery. I figured I can select the group using:
$("input[#name='user_group[]']").val()
but that just grabs the value of the first checkbox in the list regardless of if it is checked of not. Any ideas?
You could use the checked selector to grab only the selected ones (negating the need to know the count or to iterate over them all yourself):
$("input[name='user_group[]']:checked")
With those checked items, you can either create a collection of those values or do something to the collection:
var values = new Array();
$.each($("input[name='user_group[]']:checked"), function() {
values.push($(this).val());
// or you can do something to the actual checked checkboxes by working directly with 'this'
// something like $(this).hide() (only something useful, probably) :P
});
I'm not sure about the "#" used in the selector. At least with the latest jQuery, I had to remove the # to get this to function with two different checkbox arrays, otherwise all checked items were selected for each array:
var items = [];
$("input[name='items[]']:checked").each(function(){items.push($(this).val());});
var about = [];
$("input[name='about[]']:checked").each(function(){about.push($(this).val());});
Now both, items and about work.
Use .map() (adapted from the example at http://api.jquery.com/map/):
var values = $("input[name='user_group[]']:checked").map(function(index,domElement) {
return $(domElement).val();
});
With map in instead of each it is possible to avoid the array creation step:
var checkedCheckboxesValues =
$('input:checkbox[name="groupName"]:checked')
.map(function() {
return $(this).val();
}).get();
From the map() page of the docs:
Pass each element in the current matched set through a function, producing a new jQuery object containing the return values
get() turns those values into an array.
mhata dzenyu mese. its actually
var selectedGroups = new Array();
$(".user_group[checked]").each(function() {
selectedGroups.push($(this).val());
});
I just shortened the answer I selected a bit:
var selectedGroups = new Array();
$("input[#name='user_group[]']:checked").each(function() {
selectedGroups.push($(this).val());
});
and it works like a charm, thanks!
I'm not 100% entirely sure how you want to "grab" the values. But if you want to iterate over the checkboxes you can use .each like so:
("input[#name='user_group[]']").each( function() {
alert($(this).val());
});
Of course a better selector is available:
$(':checkbox')
var values = $("input[name='user_group']:checked").map(function(){
return $(this).val();
}).get();
This will give you all the values of the checked boxed in an array.
You can have a javascript variable which stores the number of checkboxes that are emitted, i.e in the <head> of the page:
<script type="text/javascript">
var num_cboxes=<?php echo $number_of_checkboxes;?>;
</script>
So if there are 10 checkboxes, starting from user_group-1 to user_group-10, in the javascript code you would get their value in this way:
var values=new Array();
for (x=1; x<=num_cboxes; x++)
{
values[x]=$("#user_group-" + x).val();
}
$(document).ready(function(){
$('#btnskillgroup').click(function(){
getCheckedGroups('skills');
});
$('#btncitiesgroup').click(function(){
getCheckedGroups('cities');
});
var getCheckedGroups = function(groupname){
var result = $('input[name="'+groupname+'"]:checked');
if (result.length > 0) {
var resultstring = result.length +"checkboxes checked <br>";
result.each(function(){
resultstring += $(this).val()+" <br>"; //append value to exsiting var
});
$('#div'+groupname).html(resultstring);
}else{
$('#div'+groupname).html(" No checkbox is Checked");
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Skills:<input type="checkbox" name="skill" value="Java"> Java
<input type="checkbox" name="skill" value="Jquery"> Jquery
<input type="checkbox" name="skill" value="PHP"> PHP
<br>
<input type="checkbox" name="cities" value="Pune"> Pune
<input type="checkbox" name="cities" value="Baramati"> Baramati
<input type="checkbox" name="cities" value="London"> London
<input type="submit" id="btnskillgroup" value="Get Checked Skill group">
<input type="submit" id="btncitiesgroup" value="Get cities checked group">
<div id="divskills"></div>
<div id="divcities"></div>

Categories

Resources