I have a number of checkboxes which I am wanting to check if they are checked (1) or not checked (0). I want to place the results in an array so that I can send them to the server to saved in a table. I have tried the below code:
<input class="publish" id="chkBox1" type="checkbox" checked>
<input class="publish" id="chkBox2" type="checkbox" checked>
<input class="publish" id="chkBox3" type="checkbox" checked>
<input class="publish" id="chkBox4" type="checkbox" checked>
<input class="publish" id="chkBox5" type="checkbox" checked>
<script>
$('#save-btn').click(function(evt){
evt.preventDefault();
var numberOfChBox = $('.publish').length;
var checkArray = new Array();
for(i = 1; i <= numberOfChBox; i++) {
if($('#chkBox' + i).is(':checked')) {
checkArray[i] = 1;
} else {
checkArray[i] = 0;
}
}
alert(checkArray);
});
</script>
but the alert outputs this:
,1,0,1,0,1,1
The values are correct except the first index in undefined. There are only a total of 5 checkboxes and yet the array is 6 indexes long. Why is this?
Try this efficient way bruvo :) http://jsfiddle.net/v4dxu/ with proper end tag in html: http://jsfiddle.net/L4p5r/
Pretty good link: https://learn.jquery.com/javascript-101/arrays/
Also in your html end your tag /> i.e.
<input class="publish" id="chkBox4" type="checkbox" checked>
rest should help :)
Code
var checkArray = new Array();
$('input[type=checkbox]').each(function () {
this.checked ? checkArray.push("1") : checkArray.push("0");
});
alert(checkArray);
As mentioned in the answers above the problem is with the index(i). But if you want to simplify the code further, How about the following code?
var checkArray = [];
$('input.publish').each(function () {
checkArray.push($(this).is(':checked'));
});
alert(checkArray);
Take into account that the first element you write is checkArray[1], as i starts with 1, instead of checkArray[0].
Replace checkArray[i] with checkArray[i-1] inside the for bucle
Related
I have two checkboxes That I would like to have complementary states.
for example: one checkbox is initially selected, so automatically, the other one is unchecked. If I toggle each one of them, the other one toggles too, but with a complementary state.
How can I do this with html and ko.js?
No need any library to do it. You can use it with pure JavaScript as below.
var cb = document.querySelectorAll('input[type=checkbox]');
let toggleCb = function(i){
let index = i ? 0 : 1;
cb[index].checked = !cb[index].checked;
}
for(let i=0; i<=1; i++){
cb[i].onclick = function(){
toggleCb(i);
}
}
<input type="checkbox" id="cb1" checked />
<input type="checkbox" id="cb2" />
Edit:
After seeing your comments, hope I've got this right.
You want the initial values to come from another viewmodel.
Both checkboxes can be unchecked but only 1 can be checked at a time after the initial setting is done. Correct? In this case writable computed observables are no longer required.
var viewmodel1 = function(){
var self = this;
self.initialValueCheckA = false;
self.initialValueCheckB = true;
};
var viewmodel2 = function(data){
var self = this;
self.checkA = ko.observable(data.initialValueCheckA);
self.checkB = ko.observable(data.initialValueCheckB);
self.checkA.subscribe(function(newAValue){
if(newAValue){
self.checkB(false);
}
});
self.checkB.subscribe(function(newBValue){
if(newBValue){
self.checkA(false);
}
});
};
var instance1 = new viewmodel1();
var instance2 = new viewmodel2({
initialValueCheckA: instance1.initialValueCheckA,
initialValueCheckB: instance1.initialValueCheckB
});
ko.applyBindings(instance1, document.getElementById('section1'));
ko.applyBindings(instance2, document.getElementById('section2'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div id="section1">
A
<input type="checkbox" data-bind="checked: initialValueCheckA" />
B
<input type="checkbox" data-bind="checked: initialValueCheckB" />
</div>
<div id="section2">
A
<input type="checkbox" data-bind="checked: checkA" />
B
<input type="checkbox" data-bind="checked: checkB" />
</div>
i am trying to get the value of selected radio buttons so i can submit my form using Ajax i searched here for some help but i couldn't find any useful solution
<input type="radio" id="answer" name="answer<?php echo $function::escape_string($question_row->question_id); ?>"
value="<?php echo $function::escape_string($answer_row>answer_id); ?>"/>
-HTML Output
<input type="radio" id="answer" name="answer16" value="107"/>
<input type="radio" id="answer" name="answer17" value="109"/>
<input type="radio" id="answer" name="answer15" value="104"/>
i found this function here
function findSelection(field) {
var test = document.getElementsByName(field);
var sizes = test.length;
alert("Size is " + sizes);
for (i=0; i < sizes; i++) {
if (test[i].checked==true) {
alert(test[i].value + ' you got a value');
return test[i].value;
}
}
}
var radioinputs = findSelection("answer");
But I do not know what to change so I can make it work with me properly
You can structure like this:
function findSelection(field) {
var test = document.getElementsByClassName(field);
var sizes = test.length;
//alert("Size is " + sizes);
result = [];
// result[16]=107;
// result[17]=109;
// result[15]=104;
for (i=0; i < sizes; i++) {
var index = test[i].dataset.index;
if(test[i].checked == true){
result[index] = test[i].value;
}else{
result[index] = undefined; // for a answer doesn't have a value
}
}
return result;
}
function checkfunction(){
var radioinputs = findSelection("radioanswer");
console.log(radioinputs);
console.log(radioinputs[15]);
};
<form id="form1">
<input type="radio" class="radioanswer" name="answer16" data-index="16" value="107"/>
<input type="radio" class="radioanswer" name="answer17" data-index="17" value="109"/>
<input type="radio" class="radioanswer" name="answer15" data-index="15" value="104"/>
<button type="button" onclick="checkfunction();"> Check </button>
</form>
A class can has multiple instances, but id has only one! And you can see document about data attributes here: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
From the looks of it you have a dynamic name field, i.e. name="answer2", name="answer3", etc. Because of that your query document.getElementByName(field) will not find a field matching "answer".
To remedy this either get rid of the dynamic name or if you really need it then I would say add a class to all those radio buttons and use document.getElemenetsByClassName.
I have following html:
<input type="checkbox" id="perlengkapans" data-stok="[1]" onchange="ambil($(this))"> name item 1
<input type="checkbox" id="perlengkapans" data-stok="[4]" onchange="ambil($(this))"> name item 2
<input type="checkbox" id="perlengkapans" data-stok="[0]" onchange="ambil($(this))"> name item 3
jquery :
function ambil(x){
var limit = x.data('stok')
var cnt = $('#perlengkapans:checked').length
if (cnt>limit){
x.prop('checked', '')
alert('you can maximum '+ limit)
}
}
I want to show a message as "you can maximum <variable_limit_value>", if the stock has reached the limit.
But it is not showing the message. Please help.
Change Input attribute - onchange="ambil((this))"
And your function to -
function ambil(x) {
limit = $(x).data('stok')
cnt = $('#perlengkapans:checked').length
if (cnt > parseInt(limit,10) ) {
$(x).prop('checked', '')
alert('you can maximum ' + limit)
}
}
Not sure, what you are achieving with you code.
But, depending upon your code, following are corrections:
1) In HTML DOM, there should be only one id for one element. In short id is a unique property. In your case, there were three elements with same id. Need to fix it.
2) Change id property to name and access the same. There can be multiple elements with same name.
Corrected Code:
<input type="checkbox" name="perlengkapans" data-stok="[1]" onchange="ambil($(this))"> name item 1
<input type="checkbox" name="perlengkapans" data-stok="[4]" onchange="ambil($(this))"> name item 2
<input type="checkbox" name="perlengkapans" data-stok="[0]" onchange="ambil($(this))"> name item 3
<script>
function ambil(x){
var limit = x.data('stok')
var cnt = $('[name=perlengkapans]:checked').length; // observe what is changed here.
if (cnt>limit){
x.prop('checked', '')
alert('you can maximum '+ limit)}}
</script>
First of all, IDs should not be repeated and the logic seems to be wrong. Try something like below.
<input type="checkbox" id="perlengkapans1" name="perlengkapans" data-stok="1" value="name item 1" />
<input type="checkbox" id="perlengkapans2" name="perlengkapans" data-stok="4" value="name item 2" />
<input type="checkbox" id="perlengkapans3" name="perlengkapans" data-stok="0" value="name item 3" />
In js file add this
$("input[name='perlengkapans']").on("change", function(){
if($("input[name='perlengkapans']":checked").length > $(this).data('stok')) {
// Display Alert
}
});
});
I wanna ask about little tricky javascript, this is about if/else if/else question.
I want make question about 'YES' or 'NO', this is the logic : If question1 is 'yes' and question2 is 'yes' and question3 is 'NO' the result is 'good', and if question1 is 'yes' and question2 is 'no' and question3 is 'yes'the result is 'not good'. I was make the code for this case but not working properly, this is my codes, i use checkbox in html for choice answers :
javascript
<script type="text/javascript">
var question1 = document.getElementById("a");
question2 = document.getElementById("b");
question3 = document.getElementById("c");
answer1 = document.getElementById("d");
answer2 = document.getElementById("e");
answer3 = document.getElementById("f");
answer4 = document.getElementById("g");
answer5 = document.getElementById("h");
answer6 = document.getElementById("i");
function TheResult(form){
if(question1 == answer1 && question2 == answer3 && question3 == answer6 ){
document.write('good');
}else if(question1 == answer1 && question2 == answer4 && question3 == answer5 ){
document.write('not good');
}else {
document.write('ERROR');
}
}
html
<form>
<p id = "a"><b>Question1</b></p>
<input type="checkbox" name="a1" value="YES" id = "d">YES
<input type="checkbox" name="a1" value="NO" id = "e">NO<br><br>
<p id = "b"><b>Question2</b></p>
<input type="checkbox" name="a2" value="YES" id = "f" >YES
<input type="checkbox" name="a2" value="NO" id = "g" >NO<br><br>
<p id = "c"><b>Question3</b></p>
<input type="checkbox" name="a3" value="YES" id = "h">YES
<input type="checkbox" name="a3" value="NO" id = "i">NO<br><br>
<input type="button" name="Submit" value="Result" style="margin-left:100px;" onClick="TheResult(this.form)" >
</form>
my codes always print out 'good' in every situation, please help.
I'm actually pretty confused by the logic that you're presenting. As many have pointed out, you're trying to compare elements against each other. This won't give you the result that you want. You'll want to use .innerHTML or .value depending on the element type.
The next problem that I see is that your HTML structure, the Questions & Answers aren't associated with each other in any way.
Another problem I see comes when you are declaring your JS variables. You're trying to chain your declarations, which is fine. Although you need to be using , instead of ;. The ; should only be on the last one to be declared.
I assume most of these problems just came from you giving us some sample code. I expect your real code doesn't look like this, or you'd be having other problems noted in your question.
Regardless, I have a solution for you. I rewrote it in a way that makes more sense to me:
View Demo Here - JSFiddle
HTML:
<form>
<label for="a1" id="a">Question 1</label>
<input type="radio" name="a1" value="YES" id="d">YES
<input type="radio" name="a1" value="NO" id="e">NO
<br>
<br>
<label for="a2" id="b">Question 2</label>
<input type="radio" name="a2" value="YES" id="f">YES
<input type="radio" name="a2" value="NO" id="g">NO
<br>
<br>
<label for="a3" id="c">Question 3</label>
<input type="radio" name="a3" value="YES" id="h">YES
<input type="radio" name="a3" value="NO" id="i">NO
<br>
<br>
<input type="button" name="Submit" value="Result" style="margin-left:100px;" onClick="theResult()">
</form>
I made 2 changes. I got rid of the <p> elements in favor of <label>. And then I changed the checkboxes to radio buttons.
The JS
function theResult(){
var inputs = document.getElementsByTagName('input');
var question = [ {selected: '', expected: 'YES'},
{selected: '', expected: 'YES'},
{selected: '', expected: 'NO'}
];
var tmpSelected = [];
for(var i = 0; i < inputs.length; i++){
var tmp = inputs[i];
if(tmp.type == 'radio' && tmp.checked){
tmpSelected.push(tmp.value);
}
}
for(var i = 0; i < tmpSelected.length; i++){
question[i].selected = tmpSelected[i];
}
validateResults(question);
};
function validateResults(results){
var status = '';
for(var i = 0; i < results.length; i++){
if(results[i].selected != results[i].expected){
status = 'Not Good'
break;
} else {
status = 'Good';
}
}
console.log(status);
return status;
}
As you can see, I've made a lot of changes to this one. I wanted to make a better mapping between selected answer & the expected.
We then go through and grab all the inputs on the page. In the first loop, we make sure that we're only accepting radio buttons & only looking at the ones that have been checked or selected. We stuff those off into an array tmpSelected for a bit.
Then we assign the values of tmpSelected to our question object, specifically to .selected. This will make it easy to compare against the expected answer.
Then we'll make a call to a different function to validate the results (this logic could've been kept in the previous function, I just like splitting things up a bit to make them more modular).
the validateResults() simple compares .selected with .expected. If they don't match, we break our loop and return the status of 'Not Good'. Otherwise we keep evaluating. I did it this way because it seemed like your code was just returning a success/failure type message, and not necessarily saying which answers were incorrect.
The results are correctly logged to the console. So you'd just need to change that back to your document.write().
Try using this in each case:
var question1 = document.getElementById("a").innerHTML;
var answer1 = document.getElementById("d").innerHTML;
if(question1 == answer1 ){
document.write('good');
}
Start simple and build up.
I'm very new to Javascript and would appreciate ANY help! I'm also using a jQuery library if that changes anything.
What I need is that if the first checkbox was ticked the output should be 100kcal, while if both were ticked then it should add up to 300kcal. My problem is that when I untick it adds the variables AGAIN.
HTML:
<input type=checkbox onchange="myFunction(100)" value="scrambledEggs">Scrambled Eggs</input>
<input type=checkbox onchange="myFunction(200)" value="bacon">Bacon</input>
<p id="output">0kcal</p>
JS:
var result = 0;
function myFunction(x) {
if (this.checked) {
result -= x;
document.getElementById("output").innerHTML = result + "kcal";
}
else {
result += x;
document.getElementById("output").innerHTML = result + "kcal";
}
}
Firstly if you're using jQuery, you should use it to attach the event handlers instead of onchange attributes. Secondly, the input tag is self closing - your current HTML is invalid. Finally, you can use a data attribute to store the kcal value for the option:
<label><input type="checkbox" class="food-option" data-kcals="100" value="scrambledEggs" />Scrambled Eggs</label>
<label><input type="checkbox" class="food-option" data-kcals="200" value="bacon" />Bacon</label>
<p id="output"><span>0</span>kcal</p>
Then you can use jQuery to attach the event and total up all the checked values and display them:
$('.food-option').change(function() {
var totalKcals = 0;
$('.food-option:checked').each(function() {
totalKcals += parseInt($(this).data('kcals'), 10);
});
$('#output span').text(totalKcals);
});
Example fiddle
In your case you can use this code:
HTML
<input type="checkbox" value="scrambledEggs" data-kcal="100">scrambledEggs</input>
<input type="checkbox" value="bacon" data-kcal="200">bacon</input>
<p id="output"> 0 kcal</p>
it have data-kcal tag which is container for your kcal value.
JS
var result = 0;
$('input[type="checkbox"]').on("change", function() {
if($(this).attr('checked'))
{
result += parseInt($(this).attr("data-kcal"));
}else{
result -= ($(this).attr("data-kcal"));
}
$("#output").text(result + " kcal");
});
Also you can check how it works on this jsFiddle.
Your HTML should be like below
<input type='checkbox' value="100">Scrambled Eggs </input>
<input type='checkbox' value="200"> Bacon </input>
<p id="output">0kcal </p>
Then you better use JQuery, less code written, more readability. The code below will achieve your needs.
$('input[type=checkbox]').change(function (e) { //This will trigger every check/uncheck event for any input of type CheckBox.
var res = 0;
$('input[type=checkbox]:checked').each(function() { //Loop through every checked checkbox.
res += parseInt($(this).val()); //Sum it's value.
});
$('#output').text(res); //Add the final result to your span.
});
Demo
Pass the element that is clicked into the function...
HTML
<input type=checkbox onchange="myFunction(this, 200)" value="bacon">Bacon</input>
JAVASCRIPT
function myFunction(element, value) {
console.log(element.checked);
}
Check this JSFiddle for a demo.
Better way of doing it is like this...
HTML
<div id="checkboxes">
<input type=checkbox value="bacon">Bacon</input>
<input type=checkbox value="Other">Other</input>
</div>
<p id="output">0kcal</p>
JAVASCRIPT
var checkboxes = document.getElementById("checkboxes");
checkboxes.onchange = function (e) {
alert("Target: " + e.target.value + " Checked: " + e.target.checked);
};
See this fiddle for a demo.