0

I have found several different methods for doing this online but for some reason i just cant get any of them to work for me, it may be they way im calling them or something but it also might involve my lack of expereince with JS but regardless I have decided to reach out.

here is the code i have found and so far is the only code that seems to give me a reaction on my page

$(":checkbox").on("change", function(){
  var checkboxValues = {};
  $(":checkbox").each(function(){
    checkboxValues[this.id] = this.checked;
  });
  $.cookie('checkboxValues', checkboxValues, { expires: 7, path: '/' })
}

function repopulateCheckboxes(){
  var checkboxValues = $.cookie('checkboxValues');
  if(checkboxValues){
    Object.keys(checkboxValues).forEach(function(element) {
      var checked = checkboxValues[element];
      $("#" + element).prop('checked', checked);
    });
  }
}

$.cookie.json = true;
repopulateFormELements();

This code will work im sure i just cant seem to get it to run right with the rest of my Javascript

here is my HTML, please don’t judge me on hideous code lol

<?php 
                            $query=mysqli_query($con, "SELECT * FROM userprofile")or die(mysqli_error($con));
                            $rownumber= NULL;
                            while($row=mysqli_fetch_array($query)){
                            $rownumber++;
                            $id=$row['id'];
                            ?>
                            <script type="text/javascript">

                            function checkOne<?php echo $id; ?>(){
                                if(    document.getElementById('<?php echo $id; ?>').checked $$ document.getElementById('chkSelectDeselectAll').checked){
                                     document.getElementById('chkSelectDeselectAll').checked = true;
                                }
                                else{
                                     document.getElementById('chkSelectDeselectAll').checked = false;
                                }
                              }
                              </script>
                                        <tr>
                                         <td style="text-align:center;">
                                         <input type="checkbox" id="<?php echo $rownumber; ?>" onclick="checkOne<?php echo $id; ?>()" name="selector[]" value="<?php echo $id; ?>">
                                         </td>
                                         <td><?php echo @$row['subscriber_acct_#'] ?></td>
                                         <td><?php echo @$row['company_name_sos'] ?></td>
                                         <td><?php echo @$row['username'] ?></td>
                                         <td><?php echo @$row['contact'] ?></td>
                                         <td><?php echo @$row['phone'] ?></td>
                                         <td><?php echo @$row['name'] ?></td>
                                         <td><?php echo @$row['account'] ?></td>
                                         <td><?php echo @$row['repo_sale_date'] ?></td>
                                         <td><?php echo @$row['num_of_prints'] ?></td>
                                         <td><?php echo @$row['num_of_coversheets'] ?></td>
                                </tr>
                                  <?php } ?>

this is how my row will output, i know my JS is suppose to affect every single checkbox on the page and then check to see if it has been checked and stored locally, and if not then set to false. But what its doing now is messing up my check all function by disabling it, and then stopping my ajax calls as well. Have i set this code snippet up incorrectly? or am i already doing something that messing with it instead?

here is my ajax call just for reference

function print_notice(){
  // var note_text=$('#note_text').val();
  // var cnotes=$('#cnotes').val();
  // var  formData = "note_text="+note_text+"&cnotes="+cnotes;
  var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    }
    else {
        throw new Error("Ajax is not supported by this browser");
    }

  var notice_data = $("#print_notice_form").serialize(); // gets all data from your form

  $.ajax({
    url : "http://localhost/xampp/process_notice/print_notice/mpdf/examples/print_notice.php",
    type: "POST",
    data: notice_data,
      success: function(data, textStatus, jqXHR)
      {
      //data - response from server
      alert(data);

      // reloads page after user clicks ok on the response
      location.reload(true);
    },
  });

}

Thank you all for the support and the assistence, I wish you the best :D

Edited by berserk

4
Contributors
17
Replies
90
Views
2 Years
Discussion Span
Last Post by AleMonteiro
Featured Replies
  • berserk, take a deep breathe and debug the code! You need to understand where it fails so you can figure out how to fix it. First of all, when you check a checkbox, does it trigger the change listener? Does it save in the cookies? Does it save correctly? Read More

0

I see a reload command in ajax. Why? Usually the whole joint of Ajax is that you don't reload.

Perhaps a bit more context would shed more light on the subject. WHat exactly are you trying to achieve and why?

0

Hi beserk.

First detail: you're missing an ');' on the jQuery :checkbox change event listener.

Where do you call repopulateFormELements() ? On window load? It isn't explicit in your code.

And one more thing... why do you handle checkbox with jQuery and also with inline onClick?
I'd remove the checkOne function and would update the change listener to something like this:

var $checks = $(":checkbox");
$checks.on("change", function(){
  var checkboxValues = {}, allChecked = true;
  $checks.each(function(){
        checkboxValues[this.id] = this.checked;
        allChecked = allChecked && (this.checked === true || this.checked === "checked" );
  });
  $.cookie('checkboxValues', checkboxValues, { expires: 7, path: '/' })
  if ( allChecked ) {
    $('#chkSelectDeselectAll').attr("checked", "checked");
  }
  else {
    $('#chkSelectDeselectAll').removeAttr("checked");
  }
});
0

Im gonnag give my suggestion like this although this is only an example

Use localStorage for it.

Here is JSFiddle Example of it. Link

Code behind it:

HTML Code:

<input type="checkbox">

JS Code:

$(function(){
    var test = localStorage.input === 'true'? true: false;
    $('input').prop('checked', test || false);
});

$('input').on('change', function() {
    localStorage.input = $(this).is(':checked');
    console.log($(this).is(':checked'));
});
0

to answer diafols question, i used the reload in ajax cause i needed to update values in my table after printing something off. I know its odd because usually you use ajax for the soul purpose of not refreshing, lol i admit thats an odd one but it seems to do what i want. if you know of a better way then please let me know, like i said before im still learning ajax, and i find incredibly useful :D.

In response to AleMonterio, I used your code but couldnt get anything to work, would there be something im not including in all this to show what im doing wrong? Im still very confused :/

in response to JoshuaJames.delecruz, that solution was the first one I tried when i started doing this, it didnt work for me :/

0

beserk, take a look at this fiddle: http://jsfiddle.net/aLhkoeed/6/
Your method is repopulateCheckboxes, but you're calling repoulateFormElements();

If you wanna do it with localStorage, take a look at this similar thread: https://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/494426/keeping-sortable-order-on-refresh

About the reload question from Diafol, if you're using AJAX to send some data to the server, you should also use it to get some data. I mean, the response from your AJAX method could be the updated table so you can update the user interface without reloading.
Another way is to make another AJAX request when the first one is completed.

0

I see what you mean now witht he get data functionality for ajax, i didnt know about that before, i will see what i can come up with to avoid the page refresh entirely, that actually would ultimatly solve my issue lol

also AleMonterio i tried the code you made, what i dont get is in JSfiddle it works just fine but in my program it does nothing? whats up with that?

also i mean if i can avoid having to refresh the page all together thats fine too but i would still like to figure this out for educational purposes just in case i ever come across it again.

but for now the none refresh will work, is the get function the same and the post in ajax?

Edited by berserk

0

In your page you should wrap that JS code inside a <script> tag and only call it on the page load, like:

$(function() {

    // ...Code to be executed when the DOM has finished loading

});

You should also use Developer Console to see if any errors are ocurring, and debug the script if needed.

0

I apologize for my confussion im just not that comfortable with JS yet, YET! but i have wrapped my code inside a script tag already, and the only real difference is that it wasnt inside the function call you listed. Now it is but i still seem to get nothing from the page. im going to include all that i can of my page because it has to be something im doing, these codes are working fine in JSfiddle and since its not working inside my code its confussing me and i really dont want it to.

here is the code i can incluse in full
(also note that i am including all my libraries like jquery but they are in another file but they work fine)

$con = mysqli_connect($host,$uname,$pass,$database) or die(mysqli_error($con));
?>
<script type="text/javascript">

function print_notice(){
  // var note_text=$('#note_text').val();
  // var cnotes=$('#cnotes').val();
  // var  formData = "note_text="+note_text+"&cnotes="+cnotes;
  var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    }
    else {
        throw new Error("Ajax is not supported by this browser");
    }

  var notice_data = $("#print_notice_form").serialize(); // gets all data from your form

  $.ajax({
    url : "http://localhost/xampp/process_notice/print_notice/mpdf/examples/print_notice.php",
    type: "POST",
    data: notice_data,
      success: function(data, textStatus, jqXHR)
      {
      //data - response from server
      alert(data);

      // reloads page after user clicks ok on the response
      location.reload(true);
    },
  });

}

function print_coversheet(){
  // var note_text=$('#note_text').val();
  // var cnotes=$('#cnotes').val();
  // var  formData = "note_text="+note_text+"&cnotes="+cnotes;
  var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    }
    else {
        throw new Error("Ajax is not supported by this browser");
    }

  var notice_data = $("#print_notice_form").serialize(); // gets all data from your form

  $.ajax({
    url : "http://localhost/xampp/process_notice/print_coversheet/mpdf/examples/print_coversheet.php",
    type: "POST",
    data: notice_data,
      success: function(data, textStatus, jqXHR)
      {
      //data - response from server
      alert(data);

      // reloads page after user clicks ok on the response
      location.reload(true);
    },
  });

}

function SelectDeselect()
{
    if(document.getElementById('chkSelectDeselectAll').checked){  
        $("INPUT[type='checkbox']").attr('checked',true); 
    }
    else  {
        $("INPUT[type='checkbox']").attr('checked',false); 
    }
}

$(function() {

  var $checks = $("input:checkbox");
  $checks.on("change", function(){
    var checkboxValues = {}, allChecked = true;
    $checks.each(function(){
          checkboxValues[this.id] = this.checked;
          allChecked = allChecked && (this.checked === true || this.checked === "checked" );
    });
    $.cookie('checkboxValues', checkboxValues, { expires: 7, path: '/' })
    if ( allChecked ) {
      $('#chkSelectDeselectAll').attr("checked", "checked");
    }
    else {
      $('#chkSelectDeselectAll').removeAttr("checked");
    }
  });

  function repopulateCheckboxes(){
    var checkboxValues = $.cookie('checkboxValues');
    if(checkboxValues){
      Object.keys(checkboxValues).forEach(function(element) {
        var checked = checkboxValues[element];
        $("#" + element).prop('checked', checked);
      });
    }
  }
  $.cookie.json = true;
});


</script>

<script type="text/javascript">
  $(function() {


  });
</script>

    <div class="row-fluid">
        <div class="span12">
            <div class="container">
                <form method="POST" action="##########.php" id="print_notice_form">
                    <br>
                    <center>
                        <a onclick="print_notice()" class="btn btn-info" name="print_notice">Print Notices</a>
                        <a onclick="print_coversheet()" class="btn btn-info" name="print_notice_coversheet">Print Coversheet</a>
                        <a class="btn btn-info" name="notice_mailed">Notices Mailed</a>
                    </center>
                    <table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered table-condensed" id="example">
                            <thead>
                                <tr>
                                    <th style="text-align:center;">
                                    <input type="checkbox" id="chkSelectDeselectAll" onclick="SelectDeselect()"/>
                                    </th>
                                    <th>Subscriber Acct #</th>
                                    <th>Company Name</th>
                                    <th>Username</th>
                                    <th>Contact</th>
                                    <th>Phone Number</th>
                                    <th>Name</th>
                                    <th>Account</th>
                                    <th>Repo Sale Date</th>
                                    <th width="5%"># of Notices</th>
                                    <th width="5%"># of Coversheets</th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php 
                            $query=mysqli_query($con, "SELECT * FROM userprofile")or die(mysqli_error($con));
                            $rownumber= NULL;
                            while($row=mysqli_fetch_array($query)){
                            $rownumber++;
                            $id=$row['id'];
                            ?>
                            <script type="text/javascript">

                            function checkOne<?php echo $id; ?>(){
                                if(    document.getElementById('<?php echo $id; ?>').checked $$ document.getElementById('chkSelectDeselectAll').checked){
                                     document.getElementById('chkSelectDeselectAll').checked = true;
                                }
                                else{
                                     document.getElementById('chkSelectDeselectAll').checked = false;
                                }
                              }
                              </script>
                                        <tr>
                                         <td style="text-align:center;">
                                         <input type="checkbox" id="<?php echo $rownumber; ?>" onclick="checkOne<?php echo $id; ?>()" name="selector[]" value="<?php echo $id; ?>"/>
                                         </td>
                                         <td><?php echo @$row['subscriber_acct_#'] ?></td>
                                         <td><?php echo @$row['company_name_sos'] ?></td>
                                         <td><?php echo @$row['username'] ?></td>
                                         <td><?php echo @$row['contact'] ?></td>
                                         <td><?php echo @$row['phone'] ?></td>
                                         <td><?php echo @$row['name'] ?></td>
                                         <td><?php echo @$row['account'] ?></td>
                                         <td><?php echo @$row['repo_sale_date'] ?></td>
                                         <td><?php echo @$row['num_of_prints'] ?></td>
                                         <td><?php echo @$row['num_of_coversheets'] ?></td>
                                </tr>
                                  <?php } ?>
                        </tbody>
                </table>
                 </div>
        </div>
    </div>

</form>
</html>

if there is any code in what i have included that can help someone else with their issues, feel free :D im all about sharing!

0

You're missing the call for repopulateCheckboxes();

Try like this:

// only code to be executed on page load goes inside here, functions are better left outside so it can be used for other pieces of code 
$(function() {
  var $checks = $("input:checkbox");
  $checks.on("change", function(){
    var checkboxValues = {}, allChecked = true;
    $checks.each(function(){
          checkboxValues[this.id] = this.checked;
          allChecked = allChecked && (this.checked === true || this.checked === "checked" );
    });
    $.cookie('checkboxValues', checkboxValues, { expires: 7, path: '/' })
    if ( allChecked ) {
      $('#chkSelectDeselectAll').attr("checked", "checked");
    }
    else {
      $('#chkSelectDeselectAll').removeAttr("checked");
    }
  });
  $.cookie.json = true;
  repopulateCheckboxes();
});


  function repopulateCheckboxes(){
    var checkboxValues = $.cookie('checkboxValues');
    if(checkboxValues){
      Object.keys(checkboxValues).forEach(function(element) {
        var checked = checkboxValues[element];
        $("#" + element).prop('checked', checked);
      });
    }
  }
0

still nothing, i dont understand why its not working in my code but it works just fine in JSfiddle, is it the ajax calls? whats different?

also im prepared to justuse $_get ajax and forget about the localstorage cause i dont seem to be getting anywhere with this and i really cant see the reason why :(

0

i think i might have an idea, using the old code from above earlier i noticed something thats rather strange

in this code no matter what i do, it always comes back false, so that tells me that the input is changing but not being seen by the javascript

$(function(){
    var test = localStorage.input === 'true'? true: false;
    $('input').prop('checked', test || false);
    alert(test);
});

$('input').on('change', function() {
    localStorage.input = $(this).is(':checked');
});

that alert always comes back false, so at least i know that the function is being called but now i know that no matter whats its coming back false because the checkboxes are not connected to the function, is it a naming issue? or an id issue? i mean i figured since this was for ALL input checkboxes on the page it wouldnt matter. HEY i think we made some progress lol!

i got no errors from the console BUT i am referencing jquery AND jquery cookie those i know are in there!

Edited by berserk

0

okay now im getting more and more curious about this, i just found out that cookies are working FINE because in the code i posted above if you change the

" var test = localStorage.input === 'true'? true: false; "
to this
" var test = localStorage.input = 'true'? true: false; "

you can forcfully create a cookie and store all the checkbox values as true, the issue with this is that no matter what they are all going to be true
so at least i know that part is working, so really my issue is in something with the checkbox values not storing and checked as true or false but why?

Edited by berserk

0

welp im stuck again, this solution i thought was working was not hat i was looking for and now im back to the drawing bored. Im not sure how to get your code to work AleMonterio i keep working and working at it but i dont seem to get any response or really any type of change. whats really confussing is that i am also not getting any errors... im kinda t a lose here :(

1

berserk, take a deep breathe and debug the code!
You need to understand where it fails so you can figure out how to fix it.
First of all, when you check a checkbox, does it trigger the change listener? Does it save in the cookies? Does it save correctly?

Votes + Comments
For the deep breath quote. Ha ha ha
0

I have done some research and found out the reason my javascript was not working was that my input boxes were set up in an array and i need them to be in an array to work right so i have to use php session variables to do this correctly. Sorry for the wasted time everyone :(

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.