Move this topic
Calling a function if checkbox is checked instead of onClick
in Using jQuery
•
9 years ago
I need to call this function if a checkbox is checked instead of being triggered by onClick:
- onclick="toggle_colorbox(this);"
How can I insert it into the following function?
- $('.Colorbox').change(function() {
if ($('input:checkbox[name=colors_love[]]:checked')) {
}
});
Function toggle_colorbox(td) changes a boxes opacity and displays a check mark to indicate that a color has been selected, but because I am pre-selecting the values matching a user's account information, I need
to initiate the function if that particular checkbox is checked.
If you'd like to see it in context http://jsfiddle.net/chayanyc/KdcJY/104/
If you'd like to see it in context http://jsfiddle.net/chayanyc/KdcJY/104/
1
Replies(49)
I looked at the jsfiddle; it's not clear if you want to use the one checkbox to control the three elements at the bottom all at once.
I fixed up the fiddle so it's hopefully much clearer now (I'm sorry about that - I'd had tried several things trying to get this to work, and both me and the fiddle had gotten a little confused ;-) ) http://jsfiddle.net/chayanyc/KdcJY/104/
Function toggle_colorbox(td) changes a boxes opacity and displays a check mark to indicate that a color has been selected.
Because I am pre-selecting the values matching a user's account information, I need to initiate the function if the checkbox[name=colors_love]:checked
The php which pre-selects the values matching a user's account information:
Function toggle_colorbox(td) changes a boxes opacity and displays a check mark to indicate that a color has been selected.
Because I am pre-selecting the values matching a user's account information, I need to initiate the function if the checkbox[name=colors_love]:checked
The php which pre-selects the values matching a user's account information:
- <input type="checkbox" name="colors_love[]" value="Bright_Red" class="cbx" <?php if($rows['colors_love[]']=='Bright_Red') echo "checked='checked'"; ?>
Leave a comment on Godsbest's reply
- $(function(){
- $('.cbx').each(function(){
- this.checked = !this.checked;
- })
- .parent().each(function(){
- toggle_colorbox(this);
- });
- });
That's exactly what I need! Unfortunately it only works as expected if
only one value has been selected, but if more than one checkbox has been
selected it stops working. How can I adjust the code for that?
Leave a comment on wizzud's reply
Your original fiddle, with 2 checkboxes checked, and the code above : http://jsfiddle.net/KdcJY/105/
Seems to work okay...
Seems to work okay...
You're right, it works in the fiddle where it's hard-coded but not when doing it dynamically with the php (even though it shows regular checkboxes as checked that way).
I'm assuming that there isn't a way to show that in a fiddle, but I can set up an example on my server.
I'm assuming that there isn't a way to show that in a fiddle, but I can set up an example on my server.
Leave a comment on wizzud's reply
Then your PHP ... needs a bit of work?
All that PHP does is build the HTML. The script provided works with the expected HTML, so it must be the PHP that's building it incorrectly.
If you are using the same PHP that's in your original fiddle then, No, it's not going to work because you don't terminate any of the checkbox elements.
All that PHP does is build the HTML. The script provided works with the expected HTML, so it must be the PHP that's building it incorrectly.
If you are using the same PHP that's in your original fiddle then, No, it's not going to work because you don't terminate any of the checkbox elements.
The PHP works with regular checkboxes, so I'm assuming that it it's ok :-(
I'm not sure what you mean by not terminating any of the checkbox elements. Would you mind explaining that? I did add a '/' at the end (changed ?>> to ?> />), but it didn't help so I'm assuming that's not what you're referring to.
I'm not sure what you mean by not terminating any of the checkbox elements. Would you mind explaining that? I did add a '/' at the end (changed ?>> to ?> />), but it didn't help so I'm assuming that's not what you're referring to.
Leave a comment on wizzud's reply
it's work as WIZZUD mentioned. see this
please check that or let us have more of your code.
- <?php $arr=array(1,1,0); $i=0 ?>
<td bgcolor=#00BFFF class="Colorbox input_field" onclick="toggle_colorbox(this);" title="Deep_Sky_Blue"><div class=Check>✓</div>
<input type="checkbox" name="colors_love[]" value="Deep_Sky_Blue" class="cbx" <?php if ( $arr[$i++]) echo 'checked="checked"';?> >
</td>
<td bgcolor=#30BA30 class="Colorbox input_field" onclick="toggle_colorbox(this);" title="Bright_Green"><div class=Check>✓</div>
<input type="checkbox" name="colors_love[]" value="Bright_Green" class="cbx"
<?php if ( $arr[$i++]) echo 'checked="checked"';?> >
</td>
<td bgcolor=#FF0000 class="Colorbox input_field" onclick="toggle_colorbox(this);" title="Black"><div class=Check>✓</div>
<input type="checkbox" name="colors_love[]" value="Bright_Red" class="cbx" <?php if ( $arr[$i++]) echo 'checked="checked"';?> >
</td>
please check that or let us have more of your code.
msd1811,
Of course I'm happy to share all of my code ;-) I've included a link below to the files, but since I'm assuming that it's easier if I pick out the relevant bits, I'm including the snippet that we're dealing with.
I tried your suggestion of changing this:
Of course I'm happy to share all of my code ;-) I've included a link below to the files, but since I'm assuming that it's easier if I pick out the relevant bits, I'm including the snippet that we're dealing with.
I tried your suggestion of changing this:
- <?php if($rows['colors_love']=='Black') echo "checked='checked'"; ?> />
- <?php if ( $arr[$i++]) echo 'checked="checked"';?> >
- <?php
$result = mysql_query("SELECT * FROM style WHERE style.user_id=$user_id ") or die(mysql_error());
$row = mysql_fetch_array($result );
$search = array('_', ',');
$replace = array(' ', ', ');
$rows = str_replace($search, $replace, $row);
?>
<td bgcolor=#000000 class="Colorbox input_field" onclick="toggle_colorbox(this);" title="Black"><div class=Check>✓</div>
<input type="checkbox" name="colors_love[]" value="Black" class="cbx" <?php if($rows['colors_love']=='Black') echo "checked='checked'"; ?> /></td>
Leave a comment on msd1811's reply
Chaya
What I meant was : your original fiddle (v 104) uses code like this for each input element (lifted from 3rd post above)...
Whether its a > or a /> is irrelevant; the point is - or was - that the fiddle has neither. However, browsers are generally fairly forgiving, and would probably terminate it for you when they saw the closing </td>, so that's not necessarily the problem you have. And anyway, It would seem that you've probably corrected this is in your actual code.
You're right, the PHP is no use in the fiddles.
That still leaves us with the problem that, whereas we have proved that the script does work against the expected HTML, your PHP doesn't seem to be producing that HTML?
So, run your PHP, produce your HTML, inspect it, lift the TABLE containing the checkboxes straight out of the browser's View Source and paste it into fiddle's HTML (v 105), and it should work. If it doesn't then there is something amiss with the HTML produced by the PHP, and we might need to see that PHP (and the HTML it produced).
What I meant was : your original fiddle (v 104) uses code like this for each input element (lifted from 3rd post above)...
- <input type="checkbox" name="colors_love[]" value="Bright_Red" class="cbx"
- <?php if($rows['colors_love[]']=='Bright_Red') echo "checked='checked'"; ?>
- <input type="checkbox" name="colors_love[]" value="Bright_Red" class="cbx"
- <?php if($rows['colors_love[]']=='Bright_Red') echo "checked='checked'"; ?> />
Whether its a > or a /> is irrelevant; the point is - or was - that the fiddle has neither. However, browsers are generally fairly forgiving, and would probably terminate it for you when they saw the closing </td>, so that's not necessarily the problem you have. And anyway, It would seem that you've probably corrected this is in your actual code.
You're right, the PHP is no use in the fiddles.
That still leaves us with the problem that, whereas we have proved that the script does work against the expected HTML, your PHP doesn't seem to be producing that HTML?
So, run your PHP, produce your HTML, inspect it, lift the TABLE containing the checkboxes straight out of the browser's View Source and paste it into fiddle's HTML (v 105), and it should work. If it doesn't then there is something amiss with the HTML produced by the PHP, and we might need to see that PHP (and the HTML it produced).
Wizzud,
I hadn't even realized I'd made that mistake when I was copying and pasting the
code - Good catch :-)

![]()
Image 2 - Doesn't display check marks when more than 1 value has been selected
![]()

That was a great suggestion to
lift the html from the browser's View Source :-) I think it helped narrow down
the problem :-) The HTML only shows checked='checked' when one value in an
array has been selected, and when more than one value is selected it doesn't
get added to the HTML. It also made me realize that I have the same
problem with standard checkboxes (my apologies - I was sure I'd tested
that already), so you're definitely right that the problem lies with my php. Any suggestions?
I added a few fields to help test things - Account Information has two questions which use standard checkboxes, one is of them is set up as an array (the code is a bit clunky though since these fields are normally displayed in Select and MultiSelect elements). I also included a field where the php displays the database values in text format so you can see the values which are being echoe'd by the php vs. what is being checked.
I've 2 screenshots with these below :-) I wasn't able to set up a working example without providing access to the database password information, but I've uploaded the attached the files so that you can see the full code (in order to simplify things I only included 3 customer questions with the relevant code). http://click2fit.com/test_files/member_infoA.php is the primary file and the files used to submit information to the database are
http://click2fit.com/test_files/profile-taste-exec1.php and http://click2fit.com/test_files/profile-createaccount-execA.php
I am so grateful for your help, along with other's like msd1811, to figure this out :-D
- Chaya
Image 1 - Displays check marks when 1 value has been selected
I added a few fields to help test things - Account Information has two questions which use standard checkboxes, one is of them is set up as an array (the code is a bit clunky though since these fields are normally displayed in Select and MultiSelect elements). I also included a field where the php displays the database values in text format so you can see the values which are being echoe'd by the php vs. what is being checked.
I've 2 screenshots with these below :-) I wasn't able to set up a working example without providing access to the database password information, but I've uploaded the attached the files so that you can see the full code (in order to simplify things I only included 3 customer questions with the relevant code). http://click2fit.com/test_files/member_infoA.php is the primary file and the files used to submit information to the database are
http://click2fit.com/test_files/profile-taste-exec1.php and http://click2fit.com/test_files/profile-createaccount-execA.php
I am so grateful for your help, along with other's like msd1811, to figure this out :-D
- Chaya
Image 1 - Displays check marks when 1 value has been selected
Image 2 - Doesn't display check marks when more than 1 value has been selected
Leave a comment on wizzud's reply
Can you put the files up as .txt files please?
Here they are :-)
Attachments
Leave a comment on wizzud's reply
First impressions :
Colours (love or hate) are stored as a comma-separated string.
When you retrieve that string you replace underbars with space and commas with comma-space. But it is still a string, so $rows['colors_love'] might look like "Black", or like "Silver, White, Gold".
Each of your tests for setting 'checked' is testing $rows['colors_love'] against a single colour, eg
For the "Black" string that's fine.
The problem comes when you are testing the "Silver, White, Gold" string, because that will never be equal to any of "Silver", "White" or "Gold"!
As with most things, there are several ways to do this. One way is to explode on the comma-space that you've created...
Then your test becomes...
... and similar for all the other colours.
Colours (love or hate) are stored as a comma-separated string.
When you retrieve that string you replace underbars with space and commas with comma-space. But it is still a string, so $rows['colors_love'] might look like "Black", or like "Silver, White, Gold".
Each of your tests for setting 'checked' is testing $rows['colors_love'] against a single colour, eg
- if( $rows['colors_love'] == 'Black') // then set checked
For the "Black" string that's fine.
The problem comes when you are testing the "Silver, White, Gold" string, because that will never be equal to any of "Silver", "White" or "Gold"!
As with most things, there are several ways to do this. One way is to explode on the comma-space that you've created...
- $explodedColorsLove = explode(', ', $rows['colors_love']);
Then your test becomes...
- if(in_array("Black", $explodedColorsLove)) // then set checked
... and similar for all the other colours.
Thanks for explaining all that :-) It can get really confusing to try to piece together all the different components I need to deal with :-)
That did it :-D It now displays checkmarks for everything that's been selected :-D There's one tiny hiccup in the code - it seems to require that there be at least one item selected because it unselects as it should until you want to remove the final item and then doesn't remove that item. Any suggestions?
Also, I was wondering if there's a way to use (this) instead of having to specify the value for each if(in_array(...))
The code is currently
That did it :-D It now displays checkmarks for everything that's been selected :-D There's one tiny hiccup in the code - it seems to require that there be at least one item selected because it unselects as it should until you want to remove the final item and then doesn't remove that item. Any suggestions?
Also, I was wondering if there's a way to use (this) instead of having to specify the value for each if(in_array(...))
The code is currently
- <?php
- $result = mysql_query("SELECT * FROM style WHERE style.user_id=$user_id ") or die(mysql_error());
- $row = mysql_fetch_array($result );
- $search = array('_', ',');
- $replace = array(' ', ', ');
- $rows = str_replace($search, $replace, $row);
- $explodedColorsLove = explode(', ', $rows['colors_love']);
- ?>
- <td bgcolor=#000000 class="Colorbox input_field" onclick="toggle_colorbox(this);">
- <div class=Check>✓</div>
- <input type="checkbox" name="colors_love[]" value="Black" class="cbx"
- <?php if(in_array("Black", $explodedColorsLove)) echo "checked='checked'"; ?> /></td>
Leave a comment on wizzud's reply
No. Javascript's
this
and PHP's
$this
are not used in the same way.
What I would do, however, is ...
...then replace all those TD colour cells with a single loop (note that I'm also adding a ColorboxSelected class to the td if the checkbox is checked, which removes the need for my javascript!)...
Edit : the closing curly bracket highlighted in red should not be there!
..and add this css rule (immediately after your current .Check rule) so that simply toggling the ColorboxSelected class will show/hide the tick...
...and replace both your toggle_colorbox() function and my suggested javascript with...
What I would do, however, is ...
- <?php
- // associative array of color name (underbars for spaces) and their hash code...
- $Colors = array(
- 'Black' => '#000000',
- 'Charcoal' => '#666666',
- 'Light_Gray' => '#999999',
- 'Silver' => '#cdc5c2',
- // and so on, thru to ...
- 'Tiffany_Blue' => '#4ee2ec'
- );
- $result = mysql_query("SELECT * FROM style WHERE style.user_id=$user_id")
- or die(mysql_error());
- $row = mysql_fetch_array($result );
- // convert the 'colors_love' field to an array without doing any string replacements...
- $colors_love = explode(',', $rows['colors_love']);
- $search = array('_', ',');
- $replace = array(' ', ', ');
- $rows = str_replace($search, $replace, $row);
- ?>
...then replace all those TD colour cells with a single loop (note that I'm also adding a ColorboxSelected class to the td if the checkbox is checked, which removes the need for my javascript!)...
- <?php
- foreach($Colors as $cname=>$ccode){
- $checked = in_array($cname, $colors_love);
- ?>
- <td bgcolor="<?php echo $ccode; ?>"
- title="<?php echo str_replace('_', ' ', $cname); ?>"
- class="Colorbox input_field<?php echo $checked ? ' ColorboxSelected' : ''; ?>">
- <div class="Check">✓</div>
- <input type="checkbox" class="cbx"
- name="colors_love[]" value="<?php echo $cname; ?>"
- <?php echo $checked ? 'checked="checked"' : ''; } ?> />
- </td>
- <?php
- }
- ?>
Edit : the closing curly bracket highlighted in red should not be there!
..and add this css rule (immediately after your current .Check rule) so that simply toggling the ColorboxSelected class will show/hide the tick...
- .ColorboxSelected .Check { visibility: visible; }
...and replace both your toggle_colorbox() function and my suggested javascript with...
- $(function(){
- var selectColorbox = function(){
- // scope (this) is .Colorbox (expected to be a td)
- var select = !$(this).hasClass('ColorboxSelected');
- $(this).toggleClass('ColorboxSelected', select)
- // check or uncheck the checkbox...
- .find('.cbx').prop('checked', select);
- return false; // no need to let the click go any further up
- };
- // this assumes that your color boxes are all within tr.account_rows elements...
- $('tr.account_rows').on('click', '.Colorbox', selectColorbox);
- });
OMG! That's amazing! And it not only integrates easily into the other sections where I do the same thing with images, but the code is simple enough that I can actually understand it :-D
It's not working quite right as is though :-( It seems to only be running the foreach loop for the check marks but not the actual colors (it's only creating one big color box with the 1rst color and displaying all the check marks inside that). I have a feeling it might not be checking the values which have been selected because there are several values echoing from the database (including black, the 1rst color) but there aren't any check marks visible onLoad
btw - I think there was an extra curly bracket at the end of the loop which replaces the TD color cells because I was getting an error message "syntax error, unexpected '}' " for that row, so I removed the final <?php } ?>.
I'm including below how I incorporated it into the code. I'm also attaching a .txt file with the full code, and I added the relevant css to it in case that might be helpful.
It's not working quite right as is though :-( It seems to only be running the foreach loop for the check marks but not the actual colors (it's only creating one big color box with the 1rst color and displaying all the check marks inside that). I have a feeling it might not be checking the values which have been selected because there are several values echoing from the database (including black, the 1rst color) but there aren't any check marks visible onLoad
btw - I think there was an extra curly bracket at the end of the loop which replaces the TD color cells because I was getting an error message "syntax error, unexpected '}' " for that row, so I removed the final <?php } ?>.
I'm including below how I incorporated it into the code. I'm also attaching a .txt file with the full code, and I added the relevant css to it in case that might be helpful.
- <script>
- $(function () {
- var selectColorbox = function () {
- // scope (this) is .Colorbox (expected to be a td)
- var select = !$(this).hasClass('ColorboxSelected');
- $(this).toggleClass('ColorboxSelected', select)
- // check or uncheck the checkbox...
- .find('.cbx').prop('checked', select);
- return false; // no need to let the click go any further up
- };
- // this assumes that your color boxes are all within tr.account_rows elements...
- $('tr.account_rows').on('click', '.Colorbox', selectColorbox);
- });
- </script>
- <?php
- $Colors = array(
- 'Black' =>'#000000',
- 'Charcoal' =>'#666666',
- 'Light_Gray' =>'#999999',
- // and so on, thru to ...
- 'Tiffany_Blue' =>'#4EE2EC'
- );
- $result = mysql_query("SELECT * FROM style WHERE style.user_id=$user_id")
- or die(mysql_error());
- $row = mysql_fetch_array($result );
- // convert the 'colors_love' field to an array without doing any string replacements...
- $colors_love = explode(',', $rows['colors_love']);
- $search = array('_', ',');
- $replace = array(' ', ', ');
- $rows = str_replace($search, $replace, $row);
- ?>
Wizzud, The visibility toggles between Rows 1 & 2 in the table; Row 1 displays only the values that are in the database for that customer (currently in text format, but will be replaced with color boxes as soon as this works ;-) ), and Row 2 shows all available choices and preselects the values in the database.
- <table cellPadding=0 cellSpacing=0 width=100% >
- <tr class="account_rows textbox_toggle" valign="top"><td class="account_fields" style="width:7%"><label>Like:</label></td><td class="customer_data_field textbox_toggle"><?php echo $rows['colors_love']; ?></td></tr>
- <tr class="account_rows" valign="top"><td class="account_fields" style="width:7%"><label>Like:</label></td>
- <?php
- foreach($Colors as $cname=>$ccode){
- $checked = in_array($cname, $colors_love);
- ?>
- <td bgcolor="<?php echo $ccode; ?>"
- title="<?php echo str_replace('_', ' ', $cname); ?>"
- class="Colorbox input_field<?php echo $checked ? ' ColorboxSelected' : ''; ?>">
- <div class="Check">✓</div>
- <input type="checkbox" class="cbx"
- name="colors_love[]" value="<?php echo $cname; ?>"
- <?php echo $checked ? 'checked="checked"' : ''; } ?> />
- </td>
- </tr>
- </table>
Attachments
Leave a comment on wizzud's reply
Sorry about that. Yes there was a typo, but not where you thought.
I have edited my previous post and indicated the faulty closing-curly-bracket (highlighted in red) and it's that one that needs to be removed. The code you took out should be put back in (after the closing </td>).
I have edited my previous post and indicated the faulty closing-curly-bracket (highlighted in red) and it's that one that needs to be removed. The code you took out should be put back in (after the closing </td>).
I should have thought to try that ;-) It's creating the color boxes perfectly now :-)
But unfortunately I was right and it isn't showing any check marks onLoad. I checked the HTML in my browsers View Source, and none of them had class="ColorboxSelected" or checked="checked"
But unfortunately I was right and it isn't showing any check marks onLoad. I checked the HTML in my browsers View Source, and none of them had class="ColorboxSelected" or checked="checked"
Leave a comment on wizzud's reply
Next point, regarding the additional css rule. You may not have noticed that I said that the new rule needed to be added
The .Check rule sets the default (which is visibility:hidden;) and we then want to modify that such that for cases when .Check is within a .ColorboxSelected we set visibility:visible;.
? (I've highlighted the important word)(immediately after your current .Check rule)
The .Check rule sets the default (which is visibility:hidden;) and we then want to modify that such that for cases when .Check is within a .ColorboxSelected we set visibility:visible;.
You're right - I definitely missed that :-)
I switched the order to this, but the check marks still aren't visible :-( (I tried other combinations as well). I also tried adding "display:block" on the off-chance that .cbx was causing the problem.
.cbx { visibility:hidden;display:none;}
.Colorbox input {height: 25px; width: 100%; font-size:200%;}
.Colorbox { position:relative; top:0; font: Verdana,Arial,sans-serif;border:1px solid #ececec;height: 25px; width: 1.9em; z-index:1;cursor:pointer; opacity: 1; filter: alpha(opacity = 100); }
.Check {position:relative; left:2.5px; color:white; font-family: Arial Narrow; font-size:1.5em; display:block; visibility:hidden; }
.ColorboxSelected .Check { visibility: visible; }
.ColorboxSelected { opacity: 0.5;filter: alpha(opacity = 50);}
I switched the order to this, but the check marks still aren't visible :-( (I tried other combinations as well). I also tried adding "display:block" on the off-chance that .cbx was causing the problem.
.cbx { visibility:hidden;display:none;}
.Colorbox input {height: 25px; width: 100%; font-size:200%;}
.Colorbox { position:relative; top:0; font: Verdana,Arial,sans-serif;border:1px solid #ececec;height: 25px; width: 1.9em; z-index:1;cursor:pointer; opacity: 1; filter: alpha(opacity = 100); }
.Check {position:relative; left:2.5px; color:white; font-family: Arial Narrow; font-size:1.5em; display:block; visibility:hidden; }
.ColorboxSelected .Check { visibility: visible; }
.ColorboxSelected { opacity: 0.5;filter: alpha(opacity = 50);}
Leave a comment on wizzud's reply
Immediately after the line...
- $colors_love = explode(',', $rows['colors_love']);
- echo "\nwizzud\n";var_dump($row['colors_love'], $colors_love);echo "\nwizzud\n";
Leave a comment on wizzud's reply
Whoa. Never mind, I've spotted it.
- $colors_love = explode(',', $rows['colors_love']);
- $colors_love = explode(',', $row['colors_love']);
That did it :-D And it makes perfect sense now why it wasn't working before :-) (I'd actually thought about when I fist saw the code but forgot about it when I was figuring out the curly bracket issue)
Two questions -
When I'm doing it in a loop like this, how can I compensate for the light colored colorboxes which need a black checkmark instead of a white one (i.e. when the background-color is white)? I'm assuming that I should create an array of light colors but I'm not quite sure how to add the appropriate If statement to this.
Also, I'm not quite sure how to modify the code for when I want to display just the colors they've selected. Would you mind showing me how to do that?
When I'm doing it in a loop like this, how can I compensate for the light colored colorboxes which need a black checkmark instead of a white one (i.e. when the background-color is white)? I'm assuming that I should create an array of light colors but I'm not quite sure how to add the appropriate If statement to this.
Also, I'm not quite sure how to modify the code for when I want to display just the colors they've selected. Would you mind showing me how to do that?
Leave a comment on wizzud's reply
Q 1.
and
- $Colors = array(
- 'Black' => '#000000',
- 'Charcoal' => '#666666',
- 'Light_Gray' => '#999999',
- 'Silver' => '#CDC5C2-black',
- 'White' => '#FFFFFF-black',
- 'Gold' => '#ffd700-black',
- 'Midnight_Blue' => '#151B8D',
- 'Royal_Blue' => '#0000FF',
- 'Dodger_Blue' => '#0099FF',
- 'Deep_Sky_Blue' => '#00BFFF',
- 'Light_Blue' => '#A3DAFF-black',
- 'Dark_Green' => '#254117',
- 'Deep_Green' => '#0f5f0f',
- 'Forest_Green' => '#008000',
- 'Bright_Green' => '#30BA30',
- 'Light_Green' => '#99ff99-black',
- 'Brown' => '#472400',
- 'Olive' => '#827839',
- 'Khaki' => '#ADA96E',
- 'Beige' => '#ECE5B6-black',
- 'Cream' => '#FFF8DC-black',
- 'Ivory' => '#FFFFF0-black',
- 'Royal_Purple' => '#4B0082',
- 'Deep_Plum' => '#800080',
- 'Violet' => '#9172EC',
- 'Soft_Purple' => '#bbaaff-black',
- 'Deep_Red' => '#8B0000',
- 'Brick_Red' => '#C11B17',
- 'Bright_Red' => '#FF0000',
- 'Deep_Pink' => '#FF1493',
- 'Bright_Pink' => '#fd86a9',
- 'Light_Pink' => '#FFBDDE-black',
- 'Deep_Reddish_Orange' => '#FF4500',
- 'Orange' => '#ff8c00',
- 'Coral' => '#FF7F50',
- 'Bright_Yellow' => '#FFFC17-black',
- 'Soft_Yellow' => '#ffff80-black',
- 'Light_Sea_Green' => '#20B2AA',
- 'Aquamarine' => '#66CDAA',
- 'Turquoise' => '#43C6DB',
- 'Tiffany_Blue' => '#4EE2EC'
- );
and
- <?php
- foreach($Colors as $cname=>$ccode){
- $ccode = explode('-', $ccode);
- $colour = count($ccode) > 1 ? ' style="color:' . $ccode[1] . '"' : '';
- $ccode = $ccode[0];
- $checked = in_array($cname, $colors_love);
- ?>
- <td bgcolor="<?php echo $ccode; ?>"
- title="<?php echo str_replace('_', ' ', $cname); ?>"
- class="Colorbox input_field<?php echo $checked ? ' ColorboxSelected' : ''; ?>">
- <div class="Check"<?php echo $colour; ?>>✓</div>
- <input type="checkbox" class="cbx"
- name="colors_love[]" value="<?php echo $cname; ?>"
- <?php echo $checked ? 'checked="checked"' : ''; ?> />
- </td>
- <?php
- }
- ?>
Leave a comment on wizzud's reply
Q 2.
In the current loop, a cell is output for each iteration of the loop, ie. one cell per element of the $Colors array.
If the output of a cell (in a similar loop) is to be made conditional upon $cname being in $colors_love then just put an if($checked){...} condition around the output of the <td>...</td> element.
In the current loop, a cell is output for each iteration of the loop, ie. one cell per element of the $Colors array.
If the output of a cell (in a similar loop) is to be made conditional upon $cname being in $colors_love then just put an if($checked){...} condition around the output of the <td>...</td> element.
You're awesome!!!
The code you wrote is so straightforward that I've had no problem figuring out how to do simpler modifications (displaying the value, replacing the background color with images, and changing the layout) :-) Even more unusual is that I've been having fun doing it :- D I'm going to go play with the code you just sent me ;-)
The code you wrote is so straightforward that I've had no problem figuring out how to do simpler modifications (displaying the value, replacing the background color with images, and changing the layout) :-) Even more unusual is that I've been having fun doing it :- D I'm going to go play with the code you just sent me ;-)
I'm having trouble updating the database with the user's input in two situations where I need to combine the code with itself or some other code.
When I combine this script together with the code I use to limit the number of items per row, it stops allowing items to be check or unchecked. I need do to this for questions which require images (since there are 30+ items in each array), so hopefully this is something really simple ;-)
When I combine this script together with the code I use to limit the number of items per row, it stops allowing items to be check or unchecked. I need do to this for questions which require images (since there are 30+ items in each array), so hopefully this is something really simple ;-)
- <?php
- //initialize a counter
- $count = 0;
- foreach($Colors as $cname=>$ccode){
- $checked =
in_array($cname, $colors_love);
- //if it's divisible by 6 then we echo a new row
- if(($count % 6) == 0) {
- echo("</tr><tr>\n");
- $count++;
- }else {
- $count++;
- }
- ?>
The 2nd problem is less important, but when I have 2 rows (visibility is toggled) and one row only displays checked items and the 2nd displays all items in the array then it allows adding selections to the database but doesn't remove items when they're unselected. I've temporarily gotten around this by removing the script to check and uncheck items from the 1rst row, but it would be great to fix this for future use.
Leave a comment on wizzud's reply
You only want to stop/start a row if you have completed the row that was started before the loop, so the test should be...
- if( $count > 0 && $count % 6 == 0){
- echo("</tr><tr>\n");
- }
- $count++;
Switching the code and adding the class did it :-D Out of
curiosity, why does if( $count > 0 && $count % 6 == 0) work,
and if(($count % 6) && $count != 0) which I'd also
tried, but forgot to mention, not work?
Also, there's one final thing to get this working perfectly - It adds all the
selected fields, but it doesn't allow unselecting all (if one selection is left
selected it's fine but if I unselect all then it won't unselect anything). Any
idea what could be causing that?
Leave a comment on wizzud's reply
I've updated fiddle with (a representation of) my understanding of the current code (the script & the html as produced by the PHP) : http://jsfiddle.net/KdcJY/108/
What's missing? And where exactly is the problem?
What's missing? And where exactly is the problem?
My code is identical to your except for a few differences in the css (The order of my css is .Check, .ColorboxSelected, .ColorboxSelected .Check, and I removed the position from both .Colorbox and .Check, and added to .Check vertical-align:middle; text-align:center;)
In rereading my question I realized that I wasn't specific enough about the problem (My apologies ;-) ) It unselects as it should in the javascript, but when the changes are submitted to the database it only unselects items if there is still one items selected, and if I unselect all then it doesn't remove any selections from the database.
In rereading my question I realized that I wasn't specific enough about the problem (My apologies ;-) ) It unselects as it should in the javascript, but when the changes are submitted to the database it only unselects items if there is still one items selected, and if I unselect all then it doesn't remove any selections from the database.
Leave a comment on wizzud's reply
You're using checkboxes.
As I'm sure you're aware, checkboxes only get submitted with the form's fields if they are checked.
If no checkboxes are checked, no checkbox fields get submitted.
No fields means that a MySQL update (or insert) command constructed based on examining the submitted fields for specific names could be compromised unless specific account is taken of fields that are checkboxes in the html form.
Your update (and insert) processing tests for the presence of colors_love, etc as a field name, and performs an action (serialize) if found; if not found (ie. all those checkboxes were unchecked) it does .... nothing.
As I'm sure you're aware, checkboxes only get submitted with the form's fields if they are checked.
If no checkboxes are checked, no checkbox fields get submitted.
No fields means that a MySQL update (or insert) command constructed based on examining the submitted fields for specific names could be compromised unless specific account is taken of fields that are checkboxes in the html form.
Your update (and insert) processing tests for the presence of colors_love, etc as a field name, and performs an action (serialize) if found; if not found (ie. all those checkboxes were unchecked) it does .... nothing.
I hadn't thought of that :-( But that makes perfect sense...
Any suggestions as to how I can get around this issue? Would creating a hidden element solve the problem?
Any suggestions as to how I can get around this issue? Would creating a hidden element solve the problem?
Leave a comment on wizzud's reply
The way I see, it's not a client-side problem, it's a server-side problem (ie. in PHP).
I would change the way I built the fields/values lists, and use an associative array with preset elements for those fields I knew I might - or more importantly, might not - be getting from client. Then build the statement(s) from the array after processing the submitted data.
I would change the way I built the fields/values lists, and use an associative array with preset elements for those fields I knew I might - or more importantly, might not - be getting from client. Then build the statement(s) from the array after processing the submitted data.
Wizzud - I edited this a bit (I'd gotten a little confused between this and another php related question that you're also helping me with ;-) )
I'm not quite sure what you mean by this, but if I'm correct in the way I'm understanding what you wrote, there are 2 parts: the array itself and presetting some of the elements. Am I right so far?
If understood what you were saying about the array itself, then I think I'm almost there with the 1rst part because all of the fields which can accept multiple inputs are set up as arrays and are serialized in the php (the elements which only accept one input don't need to be specified with the INSERT/UPDATE method I'm using, but I think they probably aren't as much of an issue). Is that ok as is, or is there something else I need to do to this?
How would I include a preset element in the associative array (all of these fields are optional on the part of the user so I may not be getting anything from the client)?
Here's the snippet of php I'm using to INSERT and/or UPDATE colors_love:
I'm not quite sure what you mean by this, but if I'm correct in the way I'm understanding what you wrote, there are 2 parts: the array itself and presetting some of the elements. Am I right so far?
If understood what you were saying about the array itself, then I think I'm almost there with the 1rst part because all of the fields which can accept multiple inputs are set up as arrays and are serialized in the php (the elements which only accept one input don't need to be specified with the INSERT/UPDATE method I'm using, but I think they probably aren't as much of an issue). Is that ok as is, or is there something else I need to do to this?
How would I include a preset element in the associative array (all of these fields are optional on the part of the user so I may not be getting anything from the client)?
Here's the snippet of php I'm using to INSERT and/or UPDATE colors_love:
- <?php
- require_once('auth.php');
- require_once('config.php');
- $user_id = $_SESSION['SESS_USER_ID'];
- // INSERT
- $fieldlist=$vallist='';
- foreach ($_POST as $key => $value) {
- if ($key=='colors_love'){
- serialize($value);
- $value= implode(',',$value);
- }
- $fieldlist.=$key.',';
- $vallist.='\''.($value).'\',';
- }
- $fieldlist=substr($fieldlist, 0, -1);
- $vallist=substr($vallist, 0, -1);
- $fieldlist.=', user_id';
- $vallist.=','.$user_id;
- // UPDATE
- $setlist='';
- foreach ($_POST as $key=>$value){
- if ($key=='colors_love'){
- serialize($value);
- $value= implode(',',$value);
- }
- $setlist.=$key .'=\''.$value.'\',';
- }
- $setlist=substr($setlist, 0, -1);
- $result = mysql_query('UPDATE style SET '.$setlist.' WHERE user_id='.$user_id);
- if (mysql_affected_rows()==0) {
- $result = mysql_query('INSERT INTO style ('.$fieldlist.') VALUES ('.$vallist.')');
- }
- header("location: member_account_iframe.php");
- exit();
- ?>
And then on member_account_iframe.php I have the code which you're familiar with:
- <?php
- $Colors = array(...);
- $result = mysql_query("SELECT * FROM style WHERE style.user_id=$user_id")
- or die(mysql_error());
- $row = mysql_fetch_array($result );
- // convert Checkbox Arrays elements to an array without doing any string replacements...
- $colors_love = explode(',', $row['colors_love']);
- $search = array('_', ',');
- $replace = array(' ', ', ');
- $rows = str_replace($search, $replace, $row);
- ?>
Leave a comment on wizzud's reply
I would use an array instead of string concatenation, but forget about that; just put this immediately before the INSERT's foreach loop...
- if(!isset($_POST['colors_love'])){
- // this assumes that your retrieval copes with an empty string!
- $_POST['colors_love'] = array();
- }
That worked :-D
I created separate statements for each array, but figured I should check if that's the proper syntax. Also, is there a way to insert "Null" instead of an empty string? (some of my fields will have if = Null statements)
I was told to serialize the array in order to insert all the values of the array into the same row (otherwise each value was being inserted into it's own row), and to use implode so that it wouldn't then add the associated formatting (quotes and []) to the database. I'm curious if you think there's a better approach that I should be taking?
I created separate statements for each array, but figured I should check if that's the proper syntax. Also, is there a way to insert "Null" instead of an empty string? (some of my fields will have if = Null statements)
I was told to serialize the array in order to insert all the values of the array into the same row (otherwise each value was being inserted into it's own row), and to use implode so that it wouldn't then add the associated formatting (quotes and []) to the database. I'm curious if you think there's a better approach that I should be taking?
I thought that worked but then realized that it's just deleting everything regardless of what's being selected :-(
btw - The reason I'm serializing the array is that's what I was told to do in order to insert all the values of the array into the same row (otherwise each value was being inserted into it's own row), and to use implode so that it wouldn't then add the associated formatting (quotes and []) to the database. I'm curious if you think there's a better approach that I should be taking?
btw - The reason I'm serializing the array is that's what I was told to do in order to insert all the values of the array into the same row (otherwise each value was being inserted into it's own row), and to use implode so that it wouldn't then add the associated formatting (quotes and []) to the database. I'm curious if you think there's a better approach that I should be taking?
Leave a comment on wizzud's reply
your INSERT & UPDATE code/loops now look like ... ?
re serialize():
you have ...
Better approach? No, either serialize/unserialize or implode/explode (for save/retrieve). My only recommendation would be that you rtfm so that you know what either combination is actually doing.
re serialize():
you have ...
- serialize($value);
Better approach? No, either serialize/unserialize or implode/explode (for save/retrieve). My only recommendation would be that you rtfm so that you know what either combination is actually doing.
Since we're using explode to convert the checkbox Arrays when we retrieve them from the database, I changed the foreach statements in both INSERT and UPDATE to implode. It seems to be working fine, but since I only tested it with a few variables it would be great to know if that's what you meant ;-)
The good news is that ISSET is now working perfectly for the first array (colors_love) :-D My syntax must be incorrect for using it with additional arrays because it does all sorts of wonky things with the subsequent arrays (i.e. deletes all the items in 1rst array instead of deleting the unselected items in the 2nd array, and not allowing items to be added to an array if it's empty).
Also, since some of my fields will have if = Null statements, I changed array() to array('Null') but figured I should run that by you to make sure that won't cause problems.
- if ($key=='colors_love'){
- $value= implode(',',$value);
- }
- if ($key=='colors_hate'){
- $value= implode(',',$value);
- }
The good news is that ISSET is now working perfectly for the first array (colors_love) :-D My syntax must be incorrect for using it with additional arrays because it does all sorts of wonky things with the subsequent arrays (i.e. deletes all the items in 1rst array instead of deleting the unselected items in the 2nd array, and not allowing items to be added to an array if it's empty).
- if(!isset($_POST['colors_love'])){
- $_POST['colors_love'] = array();
- }
- if(!isset($_POST['colors_hate'])){
- $_POST['colors_love'] = array();
- }
Also, since some of my fields will have if = Null statements, I changed array() to array('Null') but figured I should run that by you to make sure that won't cause problems.
Leave a comment on wizzud's reply
If you copy-pasted that 2nd set of code ... check it!!
I would be very surprised if any submissions from an HTML form contained NULLs, particularly from those arrays, but if you want to store a NULL instead of an empty set ...
I would be very surprised if any submissions from an HTML form contained NULLs, particularly from those arrays, but if you want to store a NULL instead of an empty set ...
Duh! I feel like an idiot! I think I've been staring at my computer for too long ;-)
Should I assume that the other changes I made are ok (removing serialize and adding 'Null')?
Should I assume that the other changes I made are ok (removing serialize and adding 'Null')?
Leave a comment on wizzud's reply
Removing serialize() is fine, as long as you understand why you're removing it.
wrt the NULL, I don't see why you would want to change an empty array - which is supposed to represent an empty set of HTML checkboxes - into one that contains a element!
wrt the NULL, I don't see why you would want to change an empty array - which is supposed to represent an empty set of HTML checkboxes - into one that contains a element!
I believe I do :-) Am I correct in assuming that it's unnecessary to use both serialize and implode at the same time, or are there some instances of Insert/Update/On Duplicate where it might be appropriate?
wrt the NULL question - There are apx. 8 arrays like this which I'm now creating dynamically (thanks to you :-D), and you're absolutely right that these particular arrays wouldn't otherwise have a value of NULL :-) However I was also going to apply the changes (removing serialize and adding ISSET) to other arrays which are connected to multi-select elements (most of which aren't generated dynamically and therefore would otherwise be set to NULL if nothing were selected).
The reason I was asking about this is that some of the information displayed needs to change if particular questions haven't been answered. In fact, I'm actually trying to figure out how to get a show() to do that right now ;-)
wrt the NULL question - There are apx. 8 arrays like this which I'm now creating dynamically (thanks to you :-D), and you're absolutely right that these particular arrays wouldn't otherwise have a value of NULL :-) However I was also going to apply the changes (removing serialize and adding ISSET) to other arrays which are connected to multi-select elements (most of which aren't generated dynamically and therefore would otherwise be set to NULL if nothing were selected).
The reason I was asking about this is that some of the information displayed needs to change if particular questions haven't been answered. In fact, I'm actually trying to figure out how to get a show() to do that right now ;-)
Leave a comment on wizzud's reply
I would suggest that you be very, very careful trying to use "Null", because you're going to end up with that "Null" string in the database column, when what you really want is NULL. In general, allowing nulls in database columns that directly relate to html form fields (ie. they feed into, and store values from) is not a good idea, and causes problems such as the one you're about to face if you go ahead.
No, there are no appropriate instances for using both serialize() and implode(), because they both reduce an array to a string so there would be no point.
No, there are no appropriate instances for using both serialize() and implode(), because they both reduce an array to a string so there would be no point.
I didn't even know that there were 2 different types of Null so I'm
really glad that I asked
I'm assuming that means that I should check if a value is empty and/or Null, but I'm curious if you'd recommend going about this a different way.

I'm assuming that means that I should check if a value is empty and/or Null, but I'm curious if you'd recommend going about this a different way.
Leave a comment on wizzud's reply
Change topic type
Link this topic
Provide the permalink of a topic that is related to this topic
Reply to Chaya Cooper's question
{"z7543116":[14737000003683241,14737000003683334,14737000003683520,14737000003683632,14737000003683652,14737000003685134,14737000003685116,14737000003685164,14737000003685222,14737000003685432,14737000003685459,14737000003685461,14737000003685467,14737000003685469,14737000003685491,14737000003694309,14737000003709003,14737000003717281,14737000003717443,14737000003717541,14737000003720327,14737000003720333,14737000003720375,14737000003720377,14737000003720389,14737000003720397],"z8483411":[14737000003682371],"z2951125":[14737000003682451,14737000003683628,14737000003683634,14737000003681851,14737000003687011,14737000003687015,14737000003687151,14737000003687341,14737000003687343,14737000003687345,14737000003687347,14737000003687351,14737000003687361,14737000003694345,14737000003713986,14737000003718275,14737000003718291,14737000003718339,14737000003719523,14737000003719617,14737000003719621,14737000003719669],"z23096457":[14737000003683798]}
Statistics
- 49 Replies
- 147687 Views
- 2 Followers