Each value checked checkbox in var - javascript

I've run into a bit of an issue. Here's a brief explanation.
I have 8 check boxes on a standard form. What I need to do is loop through each value checked checkbox in var .
But i got always the same value of the first checbox?
So far, I've got this bit of code.
var ref_idee = "";
$('.ajaxupdate:checked').each(function () {
var sThisVal = $( this.checked ).val();
//var sThisVal = (this.checked ? $('.ajaxupdate').val());
ref_idee += (ref_idee=="" ? sThisVal : "," + sThisVal);
});
console.log (ref_idee);

Apart from the typo $(this.checked ).val(); instead of $(this).val();, you still have remnants of a useless and incorrect ternary only needed when all checkboxes were retrieved instead of only the checked ones
The complete code could be
var ref_idee = [];
$('.ajaxupdate:checked').each(function() {
ref_idee.push(this.value);
});
console.log(ref_idee.join(","));
//Or simpler
ref_idee = $('.ajaxupdate:checked').map(function() {
return this.value;
}).get();
console.log(ref_idee.join(","));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="checkbox" class="ajaxupdate" value="1" checked />
<input type="checkbox" class="ajaxupdate" value="2" />
<input type="checkbox" class="ajaxupdate" value="3" checked />

Try this code.
Replace $(this.checked).val(); to $(this).val();
var ref_idee = "";
$('.ajaxupdate:checked').each(function () {
var sThisVal = $(this).val();
ref_idee += (ref_idee=="" ? sThisVal : "," + sThisVal);
});
console.log (ref_idee);

Related

trying to get all checkboxes from full page

I am trying to get all checked chckboxes value of a full page.
the full has all sort of html tags defined.
There is another piece to it which is div which has a parent class of "syllabus". except that class div and any checkboxes inside it will be ignored when the other checkboxes of complete page is checked
I am trying some like this:
$('input[type=checkbox]').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
});
Maybe something like this:
var checkedValues = [];
$('input[type=checkbox]:checked').each(function(){
checkedValues.push($(this).val());
});
console.log(checkedValues);
Or (using .map() and .get())
var checkedValues = $("input[type=checkbox]:checked").map(function() {
return $(this).val();
}).get();
console.log(checkedValues);
More info
Here you go with a solution
var sThisVal = [];
$('input[type=checkbox]').each(function () {
sThisVal.push((this.checked ? $(this).val() : ""));
});
console.log(sThisVal);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked value="1">Checkbox 1
<input type="checkbox" value="2">Checkbox 2
<input type="checkbox" checked value="3">Checkbox 3
<input type="checkbox"value="4">Checkbox 4
Hope this will help you.

Possibility to find a clicked number in a value using jQuery

I want to learn, can we find the same number in two input values.
For example:
<input type="hidden" id="multinumber" value="1,2,3,4,5">
<input type="hidden" id="justonenumber" value="3">
<div class="click">Click and test the same number</div>
JS
$(document).ready(function(){
$("body").on("click",".click", function(){
var multiple = $("#multinumber").val();
var single = $("#justonenumber").val();
});
});
When onClick event on the .click button then check the same number in the #multinumber and #justonenumber input values and get the result in an alert box.
Is there a way to do this ? Anyone can help me here please?
Just use indexOf or includes on your multiple string. :)
$(document).ready(function(){
$("body").on("click",".click", function(){
var multiple = $("#multinumber").val();
var single = $("#justonenumber").val();
var doesMultipleIncludeSingle = multiple.includes(single);
// OR
var doesMultipleIncludeSingle = multiple.indexOf(single) > -1;
});
});
As per the problem explained in the comment, it seems the requirement does involve splitting the array.
$(document).ready(function(){
$("body").on("click",".click", function(){
var multiple = $("#multinumber").val().split(',');
var single = $("#justonenumber").val();
var doesMultipleIncludeSingle = multiple.includes(single);
// OR
var doesMultipleIncludeSingle = multiple.indexOf(single) > -1;
});
});
You can get the value of first input box. Split it by , and check with .indexOf for the other input. If it's there, you can put the result in alert box like
$(".click").click(function(){
var x = $("#multinumber").val().split(",");
var y = $("#justonenumber").val();
if(x.indexOf(y) > 0){
alert(x.find(o=> o==y))
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="hidden" id="multinumber" value="1,2,3,4,5">
<input type="hidden" id="justonenumber" value="3">
<div class="click">Click and test the same number</div>
is this what you want?
$(document).ready(function(){
$("body").on("click",".click", function(){
var multiple = $("#multinumber").val();
var single = $("#justonenumber").val();
if(multiple.indexOf(single) > -1) alert(single + " is found");
else alert(single + " isn't found");
});
});

Select at least 1 checkbox in a loop of checkboxes group

I'm trying to get this thing work for a while but I guess I need to tweak the code from somewhere. I thought, someone here could better guide me instead of banging my head to my coding screen :)
here's the actual process:
<input type="hidden" name='oneSelectionChk_1'>
<input type="checkbox" name='awp_group_1' id='id1'>
<input type="checkbox" name='awp_group_1' id='id2'>
<input type="checkbox" name='awp_group_1' id='id3'>
<input type="checkbox" name='awp_group_1' id='id4'>
<input type="hidden" name='oneSelectionChk_2'>
<input type="checkbox" name='awp_group_2' id='id5'>
<input type="checkbox" name='awp_group_2' id='id6'>
<input type="checkbox" name='awp_group_2' id='id7'>
<input type="checkbox" name='awp_group_2' id='id8'>
<input type="hidden" name='oneSelectionChk_3'>
<input type="checkbox" name='awp_group_3' id='id9'>
<input type="checkbox" name='awp_group_3' id='id10'>
<input type="checkbox" name='awp_group_3' id='id11'>
<input type="checkbox" name='awp_group_3' id='id12'>
what I'm using for jQuery is:
var chkFields = $("input[name='oneSelectionChk']");
$.each(chkFields, function(i, field){
var groupID = field.id.split('_'); // Getting the ID of the group
var chkGroupBoxes = $('input[name="awp_group_"'+groupID[1]);
if(field.value==1)
{
//$.each(chkGroupBoxes, function(j, thisChkBox){
//alert(thisChkBox.value + " #"+j);
alert( $('input[name="awp_group_"'+groupID[1]).filter(':checked').length);
if($('input[name="awp_group_"'+groupID[1]+':checked').length > 0 )
{
//$.scrollTo( '#awp_container', 1200 );
alert($('input[name="awp_group_"'+groupID[1]+':checked').length+" Selected ");
//alert( "Class AlertMsgText Should be removed Now");
$("#selectInstruction_"+groupID[1]).removeClass("AlertMsgText");
//return
}
else
{
alert($('input[name="awp_group_"'+groupID[1]+':checked').length+" Still not selected ");
//alert("Please select atleat 1 from Option #"+groupID[1]);
$("#selectInstruction_"+groupID[1]).addClass("AlertMsgText");
$.scrollTo( '#awp_container', 1200 );
//return;
}
//});
}
});
This code always giving me 0 length of checkboxes, I'm not sure if I need to loop through again for each checkbox or this might work?
Any quick help should be appreciated!
Try
var chkFields = $('input[name^="oneSelectionChk"]');
$.each(chkFields, function (i, field) {
var groupID = field.name.replace('oneSelectionChk_', '')
var chkGroupBoxes = $('input[name="awp_group_' + groupID + '"]');
if (chkGroupBoxes.filter(':checked').length == 0) {
alert('please select at least one checkbox under: ' + field.name)
}
});
Demo: Fiddle
There is no element with name attribute of oneSelectionChk in your markup, the hidden inputs have name attributes that start with oneSelectionChk, you have to use attribute starts with selector.
In case that elements are siblings you can select the target elements using .nextUntil() method:
var $hidden = $('input[type=hidden]').filter('[name^=oneSelectionChk]');
$hidden.each(function(){
var $chekboxes = $(this).nextUntil('input[type=hidden]'),
$checked = $checkboxes.filter(':checked'),
$unchecked = $chekboxes.not($checked);
});
Using name attributes:
var $hidden = $('input[type=hidden]').filter('[name^=oneSelectionChk]'),
$checkboxes = $('input[type=checkbox]');
$hidden.each(function() {
var n = this.name.split('_')[1];
var $grp = $checkboxes.filter('[name="awp_group_'+ n +'"]');
// ..
});

Get the value of checked checkbox?

So I've got code that looks like this:
<input class="messageCheckbox" type="checkbox" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" value="1" name="mailId[]">
I just need Javascript to get the value of whatever checkbox is currently checked.
EDIT: To add, there will only be ONE checked box.
None of the above worked for me but simply use this:
document.querySelector('.messageCheckbox').checked;
For modern browsers:
var checkedValue = document.querySelector('.messageCheckbox:checked').value;
By using jQuery:
var checkedValue = $('.messageCheckbox:checked').val();
Pure javascript without jQuery:
var checkedValue = null;
var inputElements = document.getElementsByClassName('messageCheckbox');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value;
break;
}
}
I am using this in my code.Try this
var x=$("#checkbox").is(":checked");
If the checkbox is checked x will be true otherwise it will be false.
in plain javascript:
function test() {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
alert(i + (cboxes[i].checked?' checked ':' unchecked ') + cboxes[i].value);
}
}
function selectOnlyOne(current_clicked) {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
cboxes[i].checked = (cboxes[i] == current);
}
}
This does not directly answer the question, but may help future visitors.
If you want to have a variable always be the current state of the checkbox (rather than having to keep checking its state), you can modify the onchange event to set that variable.
This can be done in the HTML:
<input class='messageCheckbox' type='checkbox' onchange='some_var=this.checked;'>
or with JavaScript:
cb = document.getElementsByClassName('messageCheckbox')[0]
cb.addEventListener('change', function(){some_var = this.checked})
$(document).ready(function() {
var ckbox = $("input[name='ips']");
var chkId = '';
$('input').on('click', function() {
if (ckbox.is(':checked')) {
$("input[name='ips']:checked").each ( function() {
chkId = $(this).val() + ",";
chkId = chkId.slice(0, -1);
});
alert ( $(this).val() ); // return all values of checkboxes checked
alert(chkId); // return value of checkbox checked
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" name="ips" value="12520">
<input type="checkbox" name="ips" value="12521">
<input type="checkbox" name="ips" value="12522">
Use this:
alert($(".messageCheckbox").is(":checked").val())
This assumes the checkboxes to check have the class "messageCheckbox", otherwise you would have to do a check if the input is the checkbox type, etc.
<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="1" name="mailId[]">
function getValue(value){
alert(value);
}
None of the above worked for me without throwing errors in the console when the box wasn't checked so I did something along these lines instead (onclick and the checkbox function are only being used for demo purposes, in my use case it's part of a much bigger form submission function):
function checkbox() {
var checked = false;
if (document.querySelector('#opt1:checked')) {
checked = true;
}
document.getElementById('msg').innerText = checked;
}
<input type="checkbox" onclick="checkbox()" id="opt1"> <span id="msg">Click The Box</span>
If you're using Semantic UI React, data is passed as the second parameter to the onChange event.
You can therefore access the checked property as follows:
<Checkbox label="Conference" onChange={(e, d) => console.log(d.checked)} />
Surprised to see no working vanilla JavaScript solutions here (the top voted answer does not work when you follow best practices and use different IDs for each HTML element). However, this did the job for me:
Array.prototype.slice.call(document.querySelectorAll("[name='mailId']:checked"),0).map(function(v,i,a) {
return v.value;
});
If you want to get the values of all checkboxes using jQuery, this might help you. This will parse the list and depending on the desired result, you can execute other code. BTW, for this purpose, one does not need to name the input with brackets []. I left them off.
$(document).on("change", ".messageCheckbox", function(evnt){
var data = $(".messageCheckbox");
data.each(function(){
console.log(this.defaultValue, this.checked);
// Do something...
});
}); /* END LISTENER messageCheckbox */
pure javascript and modern browsers
// for boolean
document.querySelector(`#isDebugMode`).checked
// checked means specific values
document.querySelector(`#size:checked`)?.value ?? defaultSize
Example
<form>
<input type="checkbox" id="isDebugMode"><br>
<input type="checkbox" value="3" id="size"><br>
<input type="submit">
</form>
<script>
document.querySelector(`form`).onsubmit = () => {
const isDebugMode = document.querySelector(`#isDebugMode`).checked
const defaultSize = "10"
const size = document.querySelector(`#size:checked`)?.value ?? defaultSize
// 👇 for defaultSize is undefined or null
// const size = document.querySelector(`#size:checked`)?.value
console.log({isDebugMode, size})
return false
}
</script>
Optional_chaining (?.)
You could use following ways via jQuery or JavaScript to check whether checkbox is clicked.
$('.messageCheckbox').is(":checked"); // jQuery
document.getElementById(".messageCheckbox").checked //JavaScript
To obtain the value checked in jQuery:
$(".messageCheckbox").is(":checked").val();
In my project, I usually use this snippets:
var type[];
$("input[name='messageCheckbox']:checked").each(function (i) {
type[i] = $(this).val();
});
And it works well.

how to read the value of checkbox in jquery?

<li>
<input type= "checkbox" name="paradigm" id="id_1" value="3"/>
<label for="name_3">foo</label>
</li>
<li>
<input type= "checkbox" name="paradigm" id="id_2" value="4"/>
<label for="name_4">bar</label>
</li>
Here is two checkbox. If I checked checkbox id_1, using jquery I want to read the label foo. If I checked both then it should be ['foo','bar'].
$("input:checkbox:checked").map(function(){
return $(this).next().text();
}).get();
See a working demo
As long as the <label> elements immediately follow their <input> elements, then you can do something like this:
var a = [ ];
$('input[name=paradigm]:checked').next('label').each(function() {
a.push($(this).text());
});
A better solution would be to set proper for attributes on your label elements (i.e. make sure they match up with the id attributes on their checkboxes) and then:
var a = [ ];
$('input[name=paradigm]:checked').each(function() {
a.push($('label[for=' + this.id + ']').text());
});
var checkedLabels = [];
$(':checkbox').each(function() {
if (this.checked) {
var label = $('label[for="' + this.id + '"]').text();
checkedLabels.push(label);
}
});
Try this one:
var vSring = "";
$("input:checkbox[name='paradigm']").click(function(){
if($("input:checkbox[name='paradigm']").filter(":checked").length==2)
{
vSring="";
$("input:checkbox[name='paradigm']").each(function(){
var vText = $(this).next().text();
if(vSring=="")
vSring = vText+",";
else
vSring = vSring+vText+",";
});
alert(vSring);
}
else
{
if($(this).is(":checked"))
{
vSring="";
vSring=$(this).next().text();
alert(vSring);
}
}
});
CLICK HERE TO SEE THE DEMO

Categories