-   Programming (
-   -   Jquery and checkboxes (

suse_nerd 11-25-2011 04:04 PM

Jquery and checkboxes

I'm trying to manipulate some jquery into doing my bidding:

It *should*
1)Wait until livevalidation returns true (line 160).
2)Check you have at least one checkbox ticked, if not popup an alert and stop
3)If you have one checkbox ticked, popup a confirmation and submit on "OK", stop on "Cancel"

I've come up with the following modification to lines 158 onwards but it doesn't work...

        var automaticOnSubmit = ExpiryDate1.form.onsubmit; 

ExpiryDate1.form.onsubmit = function(){                 
                                var valid = automaticOnSubmit();                 
                                if(valid) {
                                var boxeschecked = $('input[type=checkbox]:checked').length;
                                if (boxeschecked = 0) {alert('Tick a checkbox!'); return true;}
                                if (boxeschecked >= 1){ document.getElementById('add').submit();return false;         
                                var r=confirm('Please press OK to confirm');
                                                if (r==true) {
                                                                }                                }

Proud 11-26-2011 05:00 AM

I'm not very experienced with JQuery or much with Javascript in general, but:

Line 114, we see you're echoing the javascript from within a PHP file, and at 119 you see the usual line that means the browser will wait until the document is loaded before executing the code that will add your new function calls to the existing elements. This echo ends at 149, you then seem to have 2 closing braces, then the end script tag (I think this is unconditionally echoed, not even limited to the line 9 possible start of the second curly brace), and then a new second script is given in the page response but this time by dropping out of the PHP interpreter. Here you've not wrapped the body of the script in a similar $(document).ready().

Next, within this second script, the only JQuery seems to be the selector for checked checkboxes, the rest is plain JS. It seems there are similar examples of such event handler assignment code online, but one mentions that you shouldn't return false if the form is valid and you want to submit it. You should probably consider using JQuery for when and how to bind this function. Also in your new snippet above, you have a return false and then subsequent statements within the if (boxeschecked >= 1){}. I don't believe these will execute as you wish.

Lastly, general tips.
Lines 120, 121, I believe your JQuery would be more efficient if you used the context you've already had the browser search for, and used something like:

    $('#ID$thisvalidate').click(function( checkbox ) {
        if ($( checkbox ).is(':checked')) {

Perhaps it's $( this ) or just $() instead of $( checkbox ), but my point is you can hugely narrow the search scope.
You're using font tags, it's the 21st century, please use CSS instead. And XHTML-valid empty tags syntax such as <input />.

j-ray 11-26-2011 07:45 AM

if (boxeschecked = 0)

you should not mix == and =
as a simple = assigns a value and does not compare

another thing I saw is that you call
$(document).ready(function() {

within a loop, so probably more that once. You should avoid that, though it may work. (I don't know).
Call it once, and then assign the events to the elements.

suse_nerd 11-26-2011 02:13 PM

The script inside

$(document).ready(function() {

is written by a loop, because it depends how many rows the database returns as to how many times I want to output the lines to do the validations, if you understand?

example : 2 lines are returned, the script will loop twice.

Yes I will try and do proper tabulation of my code so it's easier to see and clean up the javascript calls. I'll let you know how I get on.

Many thanks to both

suse_nerd 11-26-2011 02:47 PM

Okay, I've updated the pastebin, with hopefully most of your suggestions?

j-ray 11-26-2011 03:06 PM

You can have 100 lines and still you just need 1 call to

$(document).ready(function() {...

Within this function you can register all event listeners, be that 1 or 1000

Proud 11-26-2011 06:23 PM

Your HTML is still a mess. IF you're going to use a table to lay out a form, at least sort the errors. Match </th>s with <th>s not <td>s.

FWIW I'm assuming each output set of form elements is for a prescription.

How about this:
Give each of your checkboxes a CSS class of something like 'prescription'. Replace

<font face='Arial, Helvetica, sans-serif'><input name='ID$count' type='checkbox' id='ID$count' value='$count'></font>

<input id='ID$count' name='ID$count' class='prescription' type='checkbox' value='$count' />
Use something like the following JS for your handler.

jQuery( document ).ready( function() {
        $( 'input.prescription' ).each( function ( presc_number, presc ) {
                $( presc ).click( function( e ) {
                        var presc_id = $( this ).val();
                        if( $( presc ).prop( "checked", true ) ) {
                                        var FirstName = new LiveValidation( 'FirstName' + presc_id, { onlyOnSubmit: false } );
                                        FirstName.add( Validate.Presence );                     
                                        var LastName = new LiveValidation( 'LastName' + presc_id, { onlyOnSubmit: false} );
                                        LastName.add( Validate.Presence );       
                                        var Num_Repeats = new LiveValidation( 'Num_Repeats' + presc_id, { onlyOnSubmit: false } );
                                        Num_Repeats.add( Validate.Presence );
                                        var ExpiryDate = new LiveValidation( 'ExpiryDate' + presc_id, { onlyOnSubmit: false } );
                                        ExpiryDate.add( Validate.Presence );
                                        ExpiryDate.add( Validate.Exclusion, { within: [ '$want_date' ] } );
                        } else {
                                $( '#FirstName' + presc_id ).disable();
                                $( '#LastName' + presc_id ).disable();
                                $( '#Num_Repeats' + presc_id ).disable();
                                $( '#ExpiryDate' + presc_id ).disable();
                } ); // end .click()
        } ); // end .each()
} ); // end .ready()

This can live in a file, your PHP echo need only be <script src="scriptPrescriptions.js" type="text/javascript"></script> once after all the blocks of prescriptions have been output, and browsers can cache the JS once rather than send the same text for every single page load/prescription on it.
In a CSS file that also need only be included once per page <head> and downloaded once per user then cached, try:

input.prescription {
        font-family: Arial, Helvetica, sans-serif;

If this code doesn't work, you should still get the gist of it, that you can produce HTML with specific IDs from the server (because each HTML element's id attribute should be unique per document), but your client-side JS can be ID-agnostic & reusable enough to apply to any prescription.

If you put your input fields in fieldsets, you could just disable the whole fieldset in one line rather than each specific individual element via code which is then tied to the exact element combo at the time of writing the JS (i.e. add another field per prescription in the PHP and your code doesn't disable them all without matching changes after the 4 JS .disable() lines; or just use a fieldset). You can even give them each IDs and find it via

          var inputs_fieldset_id = $( ).parents( 'fieldset' ).attr( 'id' );
within your .click( function( e ){ })

suse_nerd 11-27-2011 06:05 AM

That's very helpful, thanks. As you can see I'm pretty much just a novice with regards to jquery and I'm starting to get the hang of PHP. It would be nice if there was more documentation on how to get both to work together.
Note the livevalidation code I used the "disable" in the documentation from that site.

I can see it's more logical to put the loop for the fields within the <script> tag itself rather than trying to get the php to do it dynamically, right?

The whole system does the following- you're just seeing the "import" part of it.

Manages reminders for prescriptions by sending out emails appropriate to the date of expiry.

Imports prescriptions from our sales data.

Allows manual addition of prescription data.

Allow manual editing of existing data in the system.

Proud 11-27-2011 11:08 AM


Originally Posted by suse_nerd (Post 4535106)
I can see it's more logical to put the loop for the fields within the <script> tag itself rather than trying to get the php to do it dynamically, right?

I'm not quite sure what you mean here. IMHO you really need PHP to loop over the server-side data source to produce the uniquely identifiable output 'prescription' field sets, but you are best also doing a single JQuery loop over all of these once they're actually outputted to the client to then hook up the click handlers. You could use PHP to produce JS, but you'd still be best off creating some single hidden HTML element or JS line of an add-to-array-of-values-to-be-handled script with just the key 'count' value per fieldset, and then build your JS to find & work with each occurance as it finds them (either in the HTML document or your handy JS array) rather than hard-code any ID values deep into it.

As for getting PHP and JQuery to 'work together', you basically don't. One's server-side and does things like generate pages before the client gets anything and again work after they submit requests/forms, the other is client side and can't be relied on for a whole host of things (chiefly security, secondly UI features, persisting data). You should be able to replace PHP with any other CGI/server-side language(Perl, Python, etc) and have the JQuery behave the same, and likewise swap JQuery with alternatives (YUI, MooTools?) and your PHP not be affected.

A good idea is to create the static HTML + CSS of the page you want to have the PHP output, then separately you can work on having your PHP generate this dynamically based upon a template + data, and have your JQuery make the UI easier and do some cheap input validation for the static page version. The most integrated combo would perhaps be to build some PHP XML services to use JQuery's AJAX features to add to/update your pages without full reloads/navigation, but this is still best handled and tested in two parts (dynamic service actually querying & well-forming the XML, and a static XML response service to initially build the JQuery against).
The key point being, keep the presentation layer of the HTML + CSS separate from the backend data code, and not dependant on any fancy JQuery client stuff. Then you can work on either side without impacting the other, and reuse a lot of code/effort (as well as save on bandwidth).

suse_nerd 11-28-2011 09:43 AM


Thanks, can you recommend some good starting points for reading on the XML service?

Yes, my next stage was to have some AJAX-style lightboxes which pass information rather than having separate pages (which is rather old fashioned). Now I've got the logic of the coding working fine, the next stage is to make it look nice client-side and also learn something in the process.

All times are GMT -5. The time now is 05:47 PM.