Compare the values of array in javascript - javascript

I have two checkboxes, A and B, and when either of them is clicked the event should be triggered. I need to keep track of the checked values in an array.
Possible Values.
[eA,eB] -> if both are checked.
[] -> if A and B are unchecked.
[eA] -> if A is checked and also if B is unchecked.
[eB] -> if B is checked and also if A is unchecked.
I tried some thing like this,
var all = new Array();
getValues = function(e) {
for (i = 0; i < e.length; i++) {
all[i] = e[i];
if (e[i] == "eB") {
refreshFlag = true;
}
}
if (e.length == 0) {
//need to check whether eB was checked before and set the flag
}
if (e.length == 1) {
//need to check whether eB was checked before and set the flag
}
}
How can I do this?

I included jQuery but here is an example of what you would need to do:
$(document).ready(function() {
var outputArr = [];
$('input[type="checkbox"]').click(function(e) {
var val = $(this).val();
var index = outputArr.indexOf(val);
if (index === -1) {
outputArr.push(val);
}
else {
outputArr.splice(index, 1);
}
$('#output').val(JSON.stringify(outputArr));
});
});
<!DOCTYPE html>
<html>
<head>
<style>label { display: block; }</style>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<form id="form">
<label><input type="checkbox" value="eA" /> Checkbox A</label>
<label><input type="checkbox" value="eB" /> Checkbox B</label>
</form>
<textarea id="output" disabled>[]</textarea>
</body>
</html>

Related

Loop Over Input Fields; Stop After Two Iterations

I have five form fields that will initially NOT be pre-populated with any values.
If a user fills out one of the fields, the next time they visit the form that field will be pre-populated with the value from the previous visit.
Here's what I'm trying: I'd like to create a loop that iterates through the fields. It will always check to see if there are empty fields. After finding 2 empty fields, the loop will stop and only show those 2 empty fields, while the other fields are hidden.
Here's what I have so far...I just can't figure how to stop after iterating through two fields,
HTML:
<form action="">
<input id="first" type="text" value="" />
<input id="second" type="text" value="" />
<input id="third" type="text" value="" />
<input id="fourth" type="text" value="" />
<input id="fifth" type="text" value="" />
</form>
JS:
$(document).ready(function() {
$('input').hide();
var firstValue = $('input[id="first"]').val(),
secondValue = $('input[id="second"]').val(),
thirdValue = $('input[id="third"]').val(),
fourthValue = $('input[id="fourth"]').val(),
fifthValue = $('input[id="fifth"]').val();
var firstField = $('input[id="first"]'),
secondField = $('input[id="second"]'),
thirdField = $('input[id="third"]'),
fourthField = $('input[id="fourth"]'),
fifthField = $('input[id="fifth"]');
var formValues = [firstValue, secondValue, thirdValue, fourthValue, fifthValue];
var fieldIds = [firstField, secondField, thirdField, fourthField, fifthField];
for (var i = 0; i < fieldIds.length; i++) {
for (var i = 0; i < formValues.length; i++) {
if ( formValues[i] === '' ) {
fieldIds[i].show();
return false;
}
}
}
});
Take all input fields, take the first two empty fields and show them; finally, take the complement of that to hide the rest:
var $inputFields = $('form input:text'),
$emptyFields = $inputFields
.filter(function() { return this.value == ''; })
.slice(0, 2)
.show();
$inputFields
.not($emptyFields)
.hide();
Demo
$(document).ready(function() {
$('input').hide().each( function(){
var index=0; //initilialize the counter
if( $(this).val().length ){ //check for input's length
if(index < 2) {
$(this).show();
index=index+1 //or index++ if you like
}
else {
break;
}
}
}
)};
If you want to include select and textarea fields in your eligible input population, use $(':input').hide().each(...). If you have multiple forms on your page, you would want to include that in your selector, too: $('#intended_form').find(':input').hide().each(...).
http://api.jquery.com/each/
I think that Jack provides the best answer, but this should work too. here, i use a second counter j and break the loop when j % 2 == 0, so at this time its found two empty fields. this is known as a modulus or the modulo operator.
$(document).ready(function() {
$('input').hide();
var firstValue = $('input[id="first"]').val(),
secondValue = $('input[id="second"]').val(),
thirdValue = $('input[id="third"]').val(),
fourthValue = $('input[id="fourth"]').val(),
fifthValue = $('input[id="fifth"]').val();
var firstField = $('input[id="first"]'),
secondField = $('input[id="second"]'),
thirdField = $('input[id="third"]'),
fourthField = $('input[id="fourth"]'),
fifthField = $('input[id="fifth"]');
var formValues = [firstValue, secondValue, thirdValue, fourthValue, fifthValue];
var fieldIds = [firstField, secondField, thirdField, fourthField, fifthField];
var j = 0;
for (var i = 1; i < fieldIds.length; i++) {
if ( formValues[i] === '' ) {
fieldIds[i].show();
j++;//we found an empty field
if (j % 2 == 0)
{
break;
}
}
}
});

getElementByTagName not working

When I click delete button without clicking any checkbox, it should show alert, but in this coding, if first checkbox checked, it doesn't show alert. If second checkbox checked, it show alert.
HTML:
<div id="checkbox">
<input type="CHECKBOX" name="MyCheckbox" class="checkbox" value="This..." >
<input type="CHECKBOX" name="MyCheckbox" class="checkbox" value="This..." >
<input type="CHECKBOX" name="MyCheckbox" class="checkbox" value="This..." >
<input type="CHECKBOX" name="MyCheckbox" class="checkbox" value="This..." >
</div>
<form action="DeleteServer" onsubmit="return checkCheckBoxes(this);">
<input type="SUBMIT" value="Delete!">
</form>
script function:
function checkCheckBoxes() {
var chk = document.getElementById("checkbox").getElementsByTagName("input");
for(var i=0; i<chk.length;i++){
if (document.getElementById("checkbox").getElementsByTagName("input")[i].checked == false)
{
alert ('You didn\'t choose any of the checkboxes!');
return false;
} else {
return true;
}
}
}
getElementsByTagName has an s in it. It is plural. It returns a NodeList not a single Element.
Given your HTML, that NodeList will include 2 separate inputs.
You have to loop over it (as if it was an Array) and test the checked property of each input in turn.
This should solve your problem:
var inputs = document.querySelectorAll('#checkbox input');
is_checked = false;
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type == 'checkbox' && inputs[i].name == 'MyCheckbox') {
is_checked = inputs[i].checked;
if(is_checked) break;
}
}
if(!is_checked){
alert('You didn\'t choose any of the checkboxes!');
}
Here is a fiddle
function checkCheckBoxes() {
var inputs = document.querySelectorAll('#checkbox input');
is_checked = false;
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type == 'checkbox') {
is_checked = inputs[i].checked;
if(is_checked) return true;
}
}
if(!is_checked){
alert('You didn\'t choose any of the checkboxes!');
return false;
}
}

Javascript Checkbox onClick Addition

I have a form with two check box.
Checkbox A = $1500
Checkbox B = $1500
What I want to do is, when Checkbox A is "checked", I want to display $1500 and add into hidden value. When unchecked, subtract $1500.
When both checkbox checked, I want each other to be performed addition, which means I want to have the value "$3000" in total, when one removed, subtracted accordingly.
Currently with my codes, I can make it work for one checkbox only, which means, when checkbox is checked, it will be $1500 and when one it's removed back, it's substracted. I don't know how to combine Checkbox A & Checkbox B.
Please see my codes and help me out.
HTML
<label>
<input type="checkbox" name="Meeting" onClick="if (this.checked) { onCheck3() } else { onUncheck3() }" value="Pre-Meeting 1" id="Meeting" />
Pre-Meeting 1
</label>
<label>
<input type="checkbox" name="Meeting" onClick="if (this.checked) { onCheck4() } else { onUncheck4() }" value="Pre-Meeting 2" id="Meeting" />
Pre-Meeting 2
</label>
<input type="text" name="PreMeetingAmount" readonly id="PreMeetingAmount" /><input type="hidden" name="PreMeetingAmounthidden" readonly id="PreMeetingAmounthidden" />
Javascript
function onCheck3(){
t = document.form1.PreMeetingAmount.value;
t2 = 0;
if (t == 0) {
document.form1.PreMeetingAmount.value = 1500;
}
}
function onCheck4(){
t = document.form1.PreMeetingAmount.value;
t2 = 0;
if (t == 0) {
document.form1.PreMeetingAmount.value = 1500;
}
}
function onUncheck3(){
t = document.form1.PreMeetingAmount.value;
t = t - 1500;
if (t == 0)
document.form1.PreMeetingAmount.value = document.form1.PreMeetingAmounthidden.value;
else
document.form1.PreMeetingAmount.value = t;
}
function onUncheck4(){
t = document.form1.PreMeetingAmount.value;
t = t - 1500;
if (t == 0)
document.form1.PreMeetingAmount.value = document.form1.PreMeetingAmounthidden.value;
else
document.form1.PreMeetingAmount.value = t;
}
You are always setting the value to 1500. You need to add 1500 rather than set it to 1500. Try changing onCheck3 and onCheck4 similar to this:
function onCheck3() {
t = Number( document.form1.PreMeeting.value );
document.form1.PreMeeting.value = t + 1500;
}

Javascript: master checkbox to control all checkboxes in a table column

I have 5 checkboxes. One of them is the header for all checkboxes. If I check the header checkbox, all should check automatically, and if I uncheck it, all should uncheck. If I uncheck any of the child checkboxes, the header should automatically uncheck.
My code is like this:
<html>
<SCRIPT LANGUAGE="JavaScript">
function checkAll()
{
if(pp_checkall.checked==true)
{
for (i = 1; i <= pp_check.length; i++)
pp_check[i].checked = true ;
}
else
{
for (i = 1; i <= pp_check.length; i++)
pp_check[i].checked = false ;
}
}
</script>
<SCRIPT LANGUAGE="JavaScript">
function checkOne()
{
for (i = 1; i <= pp_check.length; i++)
{
if(pp_check[i].checked==false)
{
pp_checkall.checked = false ;
}
}
}
</script>
<body>
<table>
<tr><th width="1px"><input type="checkbox" text="Dharan" name="pp_checkall" onclick="checkAll();"></th></tr>
<tr>
</tr>
<tr> <input type="checkbox" name="pp_check" value="1" onclick="checkOne();"></tr>
<!--<tr> <input type="checkbox" name="pp_check" value="2" onclick="checkOne();"></tr>
<tr> <input type="checkbox" name="pp_check" value="3" onclick="checkOne();"></tr>
<tr> <input type="checkbox" name="pp_check" value="4" onclick="checkOne();"></tr> -->
</table>
</body>
</html>
Its working fine too, but in some cases only one <td> checkbox will appear, which stops the code from working. Please give some solution to solve this.
Try this
<script type="text/javascript" language="javascript">
var pp_check = document.getElementsByName('pp_check');
var pp_checkall = document.getElementsByName('pp_checkall')[0];
function checkAll() {
if (pp_checkall.checked == true) {
for (i = 0; i < pp_check.length; i++)
pp_check[i].checked = true;
}
else {
for (i = 0; i < pp_check.length; i++)
pp_check[i].checked = false;
}
}
function checkOne() {
var pp_check = document.getElementsByName('pp_check');
for (i = 0; i < pp_check.length; i++) {
if (pp_check[i].checked == false)
pp_checkall.checked = false;
}
}
</script>
You can use jQuery for the same.
$('input[name="pp_checkall"]').change(function () {
$('input[name=pp_check]').attr('checked', this.checked);
});
$('input[name="pp_check"]').change(function () {
$('input[name="pp_checkall"]').prop(
'checked',
$('input[name=pp_check]:not(:checked)').length === 0 ? true : false
);
});
Demo: http://jsfiddle.net/gPeh8/1/

Javascript Internet Explorer Issue - what am I doing wrong?

I've looked through many posts to no avail. I have the following in a simple form where one of the products changes based on the number of checkboxes checked. It works in every browser except IE. What am I doing wrong?
<body>
<script type="text/javascript">
function check(){
"use strict";
var count = 0, x=0, checkboxes=document.signup.getElementsByClassName("styled");
for(;x<checkboxes.length; x++){
if(checkboxes[x].checked){
count++;
}
}
if(count<3) {
document.getElementById("variable").value = "1";
}
else if (count == 3){
document.getElementById("variable").value = "74";
}
else if (count == 4){
document.getElementById("variable").value = "75";
}
else if (count == 5){
document.getElementById("variable").value = "76";
}
}
</script>
<form name="signup" id="signup" method="post" action="/subscribers/signup.php">
<input type="checkbox" id="variable" name="product_id[]" value="" class="styled"></input>product 1 - variable</div>
<input type="checkbox" id="same" name="product_id[]" value="3" class="styled"></input>product 2
<input type="checkbox" id="same2" name="product_id[]" value="2" class="styled"></input>product 3
<input type="checkbox" id="same3" name="product_id[]" value="4" class="styled"></input><div class="check-title">product 4
<input type="checkbox" id="same4" name="product_id[]" value="44" class="styled"></input><div class="check-title">product 5
Continue</td></tr>
</form>
</body>
All versions of IE prior to IE9 do not support getElementsByClassName(). You will need to use some sort of substitute.
Instead of this piece of your code:
checkboxes = document.signup.getElementsByClassName("styled");
I would suggest using this:
checkboxes = document.getElementById("signup").getElementsByTagName("input")
getElementsByTagName() is widely support in all versions of IE. This will obviously get all input tags, but only the checkboxes will have checked set so you should be OK.
If you need to filter by class, then you could do the whole thing this way:
function check() {
"use strict";
// initialize checkbox count to 0
var count = 0, item;
// get all input tags in the form
var inputs = document.getElementById("signup").getElementsByTagName("input");
// loop through all input tags in the form
for (var i = 0; i < inputs.length; i++) {
// get this one into the local variable item
item = inputs[i];
// if this input tag has the right classname and is checked, increment the count
if ((item.className.indexOf("styled") != -1) && item.checked) {
count++;
}
}
// get object for result
var obj = document.getElementById("variable");
// check count and set result based on the count
if(count < 3) {
obj.value = "1";
} else if (count == 3) {
obj.value = "74";
} else if (count == 4) {
obj.value = "75";
} else if (count == 5) {
obj.value = "76";
}
}
IE doesnt have method getElementsByClassName... you can try to define it:
if(document.getElementsByClassName == undefined) {
document.getElementsByClassName = function(cl) {
var retnode = [];
var myclass = new RegExp('\\b'+cl+'\\b');
var elem = this.getElementsByTagName('*');
for (var i = 0; i < elem.length; i++) {
var classes = elem[i].className;
if (myclass.test(classes)) {
retnode.push(elem[i]);
}
}
return retnode;
}
};

Categories