Display the value on click of check box in an array - javascript

I have an array of 10 checkboxes. onclick of checkbox i want to get the value of that particular checkbox. That I am able to achieve using my code.When I click in serial order it is working fine. When I click on checkbox 5 after clicking on checkbox 7 the value of checkbox 5 ie..5 is getting added befor 7. I dont want in that order. I want the values to displayed in whatever order I click. My js file is as follows
var selected = new Array();
$(document).ready(function(){
checkBoxTest();
});
function checkBoxTest() {
alert("checkbox test");
for(i = 0; i < 10; i++){
$("#catalog_table").append('<tr><td>Checkbox<input type="checkbox" name ="chkbox" value="' +i+' "/><td></tr>');
test();
}
}
function test() {
$('#catalog_table input:checkbox').change(function() {
var emails = [];
$('#catalog_table input:checkbox:checked').each(function() {
emails.push($(this).val());
});
var textField = document.getElementById("root");
textField.value = emails;
});
}
My HTML code is something like this
<table id="catalog_table"> </table>
<textarea id="root"></textarea>
Can any one please tell me how to do this?
Demo

Its messy, but it works:
http://jsfiddle.net/za7m8/1/
var selected = new Array();
$(document).ready(function(){
$("input[type='checkbox']").on('change', function() {
// check if we are adding, or removing a selected item
if ($(this).is(":checked")) {
selected.push($(this).val());
} else {
for(var i = 0; i<selected.length;i++) {
if (selected[i] == $(this).val()) {
// remove the item from the array
selected.splice(i, 1);
}
}
}
// output selected
var output = "";
for (var o = 0; o<selected.length; o++) {
if (output.length) {
output += ", " + selected[o];
} else {
output += selected[o];
}
}
$("#root").val(output);
});
});

You just have to change your javascript like this.
var selected = new Array();
$(document).ready(function(){
checkBoxTest();
});
function checkBoxTest() {
alert("checkbox test");
for(i = 0; i < 10; i++){
$("#catalog_table").append('<tr><td>Checkbox<input type="checkbox" name ="chkbox" value="' +i+' "/><td></tr>');
test();
}
}
var emails = [];
function test() {
$('#catalog_table input:checkbox').change(function() {
if (this.checked)
{
if ( emails.indexOf( $(this).val() ) === -1 )
{
emails.push($(this).val());
}
} else
{
if ( emails.indexOf( $(this).val() ) !== -1 )
{
var index = emails.indexOf( $(this).val() );
emails.splice(index, 1);
}
}
var textField = document.getElementById("root");
textField.value = emails;
});
}

You need to clear up your code a bit, like this:
I assume that unchecking removes the value from the array, and checking adds.
var selected = new Array(); // What for is this here ?
$(document).ready(function () {
checkBoxTest();
});
function checkBoxTest() {
for (i = 0; i < 10; i++) {
$("#catalog_table").append('<tr><td>Checkbox<input type="checkbox" name ="chkbox" value="' + i + ' "/><td></tr>');
}
test();
}
function test() {
var emails = [],
textField = document.getElementById("root");
$('#catalog_table input:checkbox').change(function () {
var val = $(this).val();
// if you don't want removal of values on `uncheck`, comment out everything below excluding `emails.push(val)` and the last line
if(this.checked){ // if checked
emails.push(val); // add it
}else{
emails.splice(emails.indexOf(val), 1); // remove it if not checked
}
textField.value = emails; // set the value
});
}
DEMO

Related

Table loop if not checked checkbox in javascript

I want to put a condition to check if the checkbox is not selected. If so, there should be a prompt or alert that user must choose a checkbox.
function submit() {
var row_count = $('#adj_table_x >tbody >tr').length;
var grid = document.getElementById("adj_table_x");
var checkBoxes = grid.getElementsByTagName("INPUT");
// I want to put a condition here before the loop value will inserted
for (var i = 1; i <= row_count; i++) {
if (checkBoxes[i].checked) {
var row = checkBoxes[i].parentNode.parentNode;
var data = row.cells[1].innerHTML;
$.post('../controller/controller.php?action=submit', {
'data': data
}, function(response) {
console.log(response);
});
}
}
}
You can use the below selector
$("input:checked").length != $("input").length
You can tweak the code based on your requirement
You need to use pseudo selector 'checked' available in JQuery - Please see the link below for more info
https://api.jquery.com/checked-selector/
function submit (){
if($("#tableID input[type='checkbox']:checked").length !=
$("#tableID input[type='checkbox']").length){
alert("please check all values")
}
else{
//Put your code here
}
I think you want something like this, not really sure about your explanation, but see if it works for you.
function submit() {
var row_count = $('#adj_table_x >tbody >tr').length;
var grid = document.getElementById("adj_table_x");
var checkBoxes = grid.getElementsByTagName("INPUT");
// I want to put a condition here before the loop value will inserted
if(checkBoxes.prop('checked') == false){
alert('Please select checkbox');
return false;
}
for (var i = 1; i <= row_count; i++) {
if (checkBoxes[i].checked) {
var row = checkBoxes[i].parentNode.parentNode;
var data = row.cells[1].innerHTML;
$.post('../controller/controller.php?action=submit', {
'data': data
}, function(response) {
console.log(response);
});
}
}
}

Output object values in javascript

I have an ObjectHtmlInputElement:
for($array as $a){
echo '<input type="checkbox" name="check[]" value="'.$a.'">';
}
Javascript:
function myForm(){
var theForm=document.getElementById("myCheck");
var a = theForm.elements['check[]'];
for( var i=0; i<a.length; i++){
if(a[i].checked){
alert( a[i].value );
return true;
}
}
}
This script checks if atleast one checkbox is checked then return true(there can also be more checkboxeses checked).What i need is to output in the alert() , each checkbox that have been checked(each object value that passes 'a[i].checked'). a[i].value , outputs only the first value, so i need something else.
Based on 'dec' and 'vijay' s answer i managed to find a solution:
var checkedCheckboxes="";
for( var i=0; i<a.length; i++){
if(a[i].checked){
checkedCheckboxes += a[i].value;
}
}
for( var i=0; i<a.length; i++){
if(a[i].checked){
alert('Checked: ' + checkedCheckboxes);
return true;
}
}
Indeed the loop was stopped because of return true as dec said.And the solution was to make another loop,and insert all values in a variable so i can use it in the alert.
The first value seems to match a[i].checked and then you return and no other element is tested. So remove return true.
Try this:
function myForm() {
var theForm = document.getElementById("myCheck");
var a = theForm.elements['check[]'];
var checkedCheckboxes = "";
for (var i = 0; i < a.length; i++) {
if (a[i].checked) {
checkedCheckboxes += a[i].value + ", ";
}
}
if (checkedCheckboxes.length > 0) alert(checkedCheckboxes);
return checkedCheckboxes.length > 0;
}
http://jsfiddle.net/p5upLprk/1/
with jquery you can do:
function isThereAtLeastOneCheckActive() {
var res = false
$(':checkbox').each(function() {
if (this.checked) {
res = true
alert(this.val())
// .text() can also be used
}
})
return res
}
As you are beggining, maybe you find strange the absense of ;
There is no need for them in js: https://mislav.net/2010/05/semicolons/

Failed to sum variable in javascript

I have script to sum amount that I get from ID's of html element, this is the script :
<script type="text/javascript">
$(document).ready(function() {
/* var sum=0; */
$('#checkAll').click(function(event) { //on click
if(this.checked) { // check select status
var i = 0;
var sum = 0;
$('.checkItem').each(function() { //loop through each checkbox
this.checked = true; //select all checkboxes with class "checkbox1"
sum = sum + parseInt($('#amount'+i).val());
i++;
});
}else{
$('.checkItem').each(function() { //loop through each checkbox
this.checked = false; //deselect all checkboxes with class "checkbox1"
});
sum=0;
i=0;
}
$('#totalRecord').val(i);
$('#totalAmount').val(sum);
$('#totalAmountFake').val(ChangeToRupiah(sum));
});
});
</script>
function ChangeToRupiah(angka){
var rev = parseInt(angka, 10).toString().split("").reverse().join("");
var rev2 = "";
for(var i = 0; i < rev.length; i++){
rev2 += rev[i];
if((i + 1) % 3 === 0 && i !== (rev.length - 1)){
rev2 += ".";
}
}
return rev2.split("").reverse().join("") + ",00";
}
But when i run it, i got this message in my result element :
I guess it's about limitation of javascript variable, but it's not, I use Internet Explorer 9.

How can setTimeout save and load data back to form inputs if browser crashes, and I visit that same page again?

How can setTimeout save and load data for select form inputs? I tried to get it working with event listeners. I checked the capture and bubble which I am still trying to wrap my head around.
I need it to set or get values assigned it to respective elements from the input field depending if there is changes such as focus or blur on the fields.
Is there a feature or step I missed and where should I start looking?
answers = document.getElementsByName('answers[]');
for(var i = 0; i < answers.length; i++) {
nodeIndex = 'answer' + i;
if(answers[i] == ''){
answers[i].addEventListener('blur', function(){
localStorage.setItem(nodeIndex, answers[i].value);
});
}
else {
answers[i].addEventListener('focus', function(){
answers[i].value = localStorage.getItem(nodeIndex);
localStorage.setItem(nodeIndex, answers[i].value);
});
answers[i].addEventListener('blur', function(){
localStorage.setItem(nodeIndex, answers[i].value);
answers[i].value = localStorage.getItem(nodeIndex);
});
} // end if
} // end forloop
REVISED
I noticed only the last element is affected. When I enter text in answers[0] to answers[14], their values are saved and set/copied to only the last element. How am I using this incorrectly? I read up and seem to follow the rules...
function processAnswers(i, answers) {
setTimeout(function() {
nodeIndex = 'answer' + i;
if(localStorage.getItem(nodeIndex) === null) {
answers[i].addEventListener('blur', function(){
localStorage.setItem(nodeIndex, answers[i].value);
});
} // end if
else {
answers[i].addEventListener('focus', function(){
answers[i].value = localStorage.getItem(nodeIndex);
localStorage.setItem(nodeIndex, answers[i].value);
});
answers[i].addEventListener('blur', function(){
localStorage.setItem(nodeIndex, answers[i].value);
answers[i].value = localStorage.getItem(nodeIndex);
});
} // end else
}, 100); // end setTimeout()
} // end processAnswers();
answers = document.getElementsByName('answers[]');
for(var i = 0; i < answers.length; i++) {
processAnswers(i, answers);
}
My code was getting out of hand. I decided to start over and keep it simple... and it worked!
var answers;
var clearAnswersBtn;
var clearAnswers;
var MainLoop = function MainLoopFunction(){
answers = document.getElementsByName('answers[]');
clearAnswersBtn = document.getElementsByTagName('body')[0];
clearAnswersBtn.innerHTML = clearAnswersBtn.innerHTML + '<button id="clearanswers" style="position:fixed;bottom:0;right:0;padding:5px;margin:0 10px 10px 0;z-index:99999">Clear Saved Answers</button>';
clearAnswers = document.getElementById('clearanswers');
clearAnswers.addEventListener("click", function(){
localStorage.clear();
alert("Answers Cleared!");
});
function saveAnswers(i, answer){
if(localStorage.getItem(i)) {
answer.value = localStorage.getItem(i);
}
else {
answer.addEventListener("blur", function(){
if(!localStorage.getItem(i)) {
localStorage.setItem(i, answer.value);
}
});
}
} // end saveAnswers()
setTimeout(function(){
for( var i = 0; i < answers.length; i++) {
saveAnswers(i, answers[i]);
}
}, 0)
}();

How to check dynamically checkbox in form if there is a match

I'm using a piece of code to check in a form if a checkbox matches the content of a given variable.
Everything works great but the thing is that I'd like to have this checkbox checked if I have a match but I don't know how to do this.
my javascript code to see if there is a match :
<script type="text/javascript">
function loopForm(form,job) {
var cbResults = 'Checkboxes: ';
var radioResults = 'Radio buttons: ';
for (var i = 0; i < form.elements.length; i++ ) {
if (form.elements[i].type == 'checkbox') {
if (form.elements[i].id == job) {
// This works great but I'd like instead to have the element checked
alert(job);
}
}
}
}
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
var job = filename.split("-");
var metier = job[0];
loopForm(document.formulaire,metier);
</script>
if (form.elements[i].id == job) {
form.elements[i].checked = true;
}
just
form.elements[i].checked = true;

Categories