LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 11-25-2011, 04:04 PM   #1
suse_nerd
Member
 
Registered: May 2008
Distribution: SuSe
Posts: 50

Rep: Reputation: 15
Jquery and checkboxes


Hello

I'm trying to manipulate some jquery into doing my bidding:
http://pastebin.com/nFhteNRp


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...
Code:
	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) { 
						document.getElementById('add').submit();}
				}
								}				}

Last edited by suse_nerd; 11-25-2011 at 04:07 PM.
 
Old 11-26-2011, 05:00 AM   #2
Proud
Senior Member
 
Registered: Dec 2002
Location: England
Distribution: Used to use Mandrake/Mandriva
Posts: 2,794

Rep: Reputation: 116Reputation: 116
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:
Code:
    $('#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 />.

Last edited by Proud; 11-26-2011 at 05:06 AM.
 
Old 11-26-2011, 07:45 AM   #3
j-ray
Senior Member
 
Registered: Jan 2002
Location: germany
Distribution: ubuntu, mint, suse
Posts: 1,591

Rep: Reputation: 145Reputation: 145
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.
 
Old 11-26-2011, 02:13 PM   #4
suse_nerd
Member
 
Registered: May 2008
Distribution: SuSe
Posts: 50

Original Poster
Rep: Reputation: 15
@j-ray:
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.

@proud:
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
 
Old 11-26-2011, 02:47 PM   #5
suse_nerd
Member
 
Registered: May 2008
Distribution: SuSe
Posts: 50

Original Poster
Rep: Reputation: 15
Okay, I've updated the pastebin, with hopefully most of your suggestions?
 
Old 11-26-2011, 03:06 PM   #6
j-ray
Senior Member
 
Registered: Jan 2002
Location: germany
Distribution: ubuntu, mint, suse
Posts: 1,591

Rep: Reputation: 145Reputation: 145
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
 
Old 11-26-2011, 06:23 PM   #7
Proud
Senior Member
 
Registered: Dec 2002
Location: England
Distribution: Used to use Mandrake/Mandriva
Posts: 2,794

Rep: Reputation: 116Reputation: 116
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
Code:
<font face='Arial, Helvetica, sans-serif'><input name='ID$count' type='checkbox' id='ID$count' value='$count'></font>
with
Code:
<input id='ID$count' name='ID$count' class='prescription' type='checkbox' value='$count' />
Use something like the following JS for your handler.
Code:
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:
Code:
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
Code:
	  var inputs_fieldset_id = $( e.target ).parents( 'fieldset' ).attr( 'id' );
within your .click( function( e ){ })

Last edited by Proud; 11-26-2011 at 06:28 PM.
 
Old 11-27-2011, 06:05 AM   #8
suse_nerd
Member
 
Registered: May 2008
Distribution: SuSe
Posts: 50

Original Poster
Rep: Reputation: 15
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.
 
Old 11-27-2011, 11:08 AM   #9
Proud
Senior Member
 
Registered: Dec 2002
Location: England
Distribution: Used to use Mandrake/Mandriva
Posts: 2,794

Rep: Reputation: 116Reputation: 116
Quote:
Originally Posted by suse_nerd View Post
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).

Last edited by Proud; 11-27-2011 at 11:16 AM.
 
Old 11-28-2011, 09:43 AM   #10
suse_nerd
Member
 
Registered: May 2008
Distribution: SuSe
Posts: 50

Original Poster
Rep: Reputation: 15
@Proud

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.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
jquery to dynamically create cookies using the jquery cookie plugin lmcilwain Programming 5 07-27-2011 09:11 PM
checkboxes in php [on/off] ALInux Programming 1 11-09-2005 06:40 AM
Unsubscribe From [ ] (checkboxes) t3gah LQ Suggestions & Feedback 5 06-02-2005 12:12 PM
Checkboxes in the Subscribed Threads listing Bebo LQ Suggestions & Feedback 2 07-21-2004 09:30 AM
MySQL/PHP - checkboxes etc linuxfond Programming 2 05-07-2004 04:12 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 11:41 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration