Jquery Load onclick data driven customisation system - php

This code is to work in combination with a form showing the results of the selections made on the right hand side of the page by loading the URL of the chosen option in a specified DIV that corresponds to the ID of the product.
function product_analysis(productid, address) {
if (this.checked = 'checked') {
$(productid).load(address);
}
else {
$(productid).load('http://www.divethegap.com/update/blank.html');
}
};
Problem is that the query to check if the box is checked or not does not work. If you check or uncheck the box it loads the address of the onclick event.
Any help would be appreciated but please keep in mind that the products are data driven so we cannot have specific IDs but rather IDs built of the Post ID.
Also when the page loads there will need to be some sort of global function which will work out what is 'checked' and load those URLs (products) in their specific DIVs.
Many Thanks,

Beware that you used = instead of == in the if() condition.
Also, have you tried with the :checked selector?
$("#id:checked")
JQuery documentation

function product_analysis(productid, address, box) {
if (box.checked) {
$(#productid).load(address);
}
else {
$(#productid).load('http://www.divethegap.com/update/blank.html');
}
};
and code for the box
onclick="product_analysis('#product_1231', 'http://www.divethegap.com/update/products/2010/11/padi-open-water/', this)"

Related

Display something on admin post page if specific category is selected

I'm trying to get Wordpress' Admin Post Page to display some form of output when a specific category (say, 'Featured') is selected.
Something like this (original page):
When I select the 'Featured' category (selected 'Featured' category), I want something to display, like this:
Meaning the page checks if the specific category is checked, and if it is, Wordpress generates an option menu for the user to fill in.
How do I go about doing this? I'm looking at the Wordpress Codex but so far, no dice.
You'll have to print some jQuery only in that screen, and then it's matter of listening for live changes and making the show/hide actions.
The following is from this WPSE Answer. You have to adjust the elements IDs. Also, jQuery's live method is deprecated, change that as well.
add_action('admin_head', 'wpse_53486_script_enqueuer');
function wpse_53486_script_enqueuer() {
global $current_screen;
if ( 'post' == $current_screen->id )
{
echo <<<HTML
<script type="text/javascript">
jQuery(document).ready( function($) {
if ( $('#in-category-6').is(':checked') ) {
$("form#adv-settings label[for='myplugin_sectionid-hide']").show();
$('#myplugin_sectionid').show();
} else {
$('#myplugin_sectionid').hide();
$("form#adv-settings label[for='myplugin_sectionid-hide']").hide();
}
$('#in-category-6').live('change', function(){
if ( $(this).is(':checked') ) {
$('#myplugin_sectionid').show();
$("form#adv-settings label[for='myplugin_sectionid-hide']").show();
} else {
$('#myplugin_sectionid').hide();
$("form#adv-settings label[for='myplugin_sectionid-hide']").hide();
}
});
});
</script>
HTML;
}
}
Another method to print scripts in targeted admin pages.
If you want that you feature will works after the post is saved (so that it already marked id DB to witch category this post belong to), you should use in_category() function to detect whether this post is in the category that you want, and if so - to show your extra box.
But, as I understand you want that it will work also before the post is saved, so you should use jQuery - detect whether the checkbox with value x (where x is your category id) is checked, and then display your extra box by changing css display property from none to block.
Check out Advanced Custom Fields.
It is a wordpress plugin that allows you to add additional fields to posts, and it can do this by category. I have used it before to set background images on posts for use in a slider.

Is it possible to force the value of a new CRUD form field?

I am using Agile Toolkit. I have a drop-down field in my CRUD.
How can I make the "New" button display different set of values in this drop-down to when the "Edit" button is clicked?
Here is my code:
class page_things extends Page {
function init(){
parent::init();
$p = $this;
$f = $p->add('Form');
$idCat = ($f->get('idCat')?$f->get('idCat'):$this->api->getConfig('idCat','MASP2U03'));
$dpUE = $f->addField('dropdown', 'Category');
$dpUE->setModel('Category');
$dpUE->js('change',$f->js()->submit());
$dpUE->set($idCat);
$f->addSubmit('OK');
$c = $f->add('CRUD');
$c->setModel('things',array('name', 'field1', 'field2', 'field3'))->setMasterField('idCat',$idCat);
if($f->isSubmitted()){
$c->js(true)->show()->execute()->reload()->execute();
}
}
}
Thank you for help !!
use
$crud=$this->add('CRUD',array('allow_add'=>false));
to disable default Add button, then add your own button:
if($crud->grid)$crud->grid->addButton('Add')->js('click')
->frameURL('Add',$this->api->url('./new'));
After this you'll need to create a new page
class page_things_new extends Page {
and inside this page define the form the way you want it to appear no the "add" click. I don't fully understand your question, but with these instruction you can have a different page appear when adding new entries to your crud.
Here's an alternative to Romans that I've tried. It uses $this->api->memorize to store a GET variable chosen in the drop down list in a session variable. Then in the Form, you can set default the chosen value by using recall in the model.
Something like this
in page/things
// load the javascript function (see later)
$this->js()->_load('your_univ');
/*****************************************************************/
/* Code to populate drop down lists - amend where as required*/
$catList=$this->api->db->dsql()->table('category c')
->field('c.id')
->field('c.name')
->where('c.type',$cat_type)
->order('c.id')
->do_getAssoc();
// Check if one is set on URL or default from config and memorize the value
if ($_GET['cat']){
$cat=$_GET['cat'];
} else {
$cat=$this->api-getConfig('idCat');
}
$this->api->memorize('category',$cat);
$f=$p->add('Form',null,null,array('form_empty'))
->setFormClass('horizontal bottom-padded');
$l1=$f->addField('dropdown','category')->setValueList($catList)->set($cat);
// calls a bit of javascript described later to reload with the parameter
$l1->js('change')->univ()->yourfunc($p->api->getDestinationURL(null), $l1);
.. rest of your page code goes here ..
Then in /lib/Model/Category.php
Add the following recall for the field
$this->addField('idCat')->system(true)->visible(false)
->defaultValue($this->api->recall('category'));
Note the system(true) and visible(False) means it wont show up and wont be changeable on the CRUD but you can play around with the options so it shows in the CRUD grid but not in the form.
Finally, the little bit of javascript to make the reload work (Romans might advise a better way to do this). Make sure yourfunc matches in the page and in the js.
in /templates/js/your_univ.js add the following
$.each({
yourfunc: function(url, name){
document.location.href=url+'&cat='+$(name).val();
},
},$.univ._import);
I've got code similar to this working in my own pages. You can probably make it work as a POST as well as the drop down is a form if you dont want the cat to show on the URL.

unknown checkbox problem

Ok, consider this problem. I have a list of email addresses and each email address has a checkbox which marks them as valid or not. OK, so the user can go and check/uncheck each one of the email addresses manually or he can click on a button that selects or deselects all the checkboxes.
However, my problem is, when the user clicks on that button that selects/deselects all the checkboxes, how would the program know in what state all the checkboxes are? I mean:
if (all checkboxes are checked)
{ uncheck all}
else
{ check all }
I cannot just go and take the value of the first row, since:
1. User may have checked/unchecked it manually
2. That ID may no longer be present in the db.
Please help me.
I think you are looking at this the wrong way. I would suggest having a checkbox as your toggle (as sites/apps do). Then the state of the checkbox is dependant whether all other checkboxes are selected.
You could do it with variables / flags but this look intuitive to me. here is an example - code is a bit rushed :)
http://jsbin.com/uyapi4
Just look at the first row, and then apply the opposite state to all checkboxes.
If there is an ID no longer in the database, that is a separate issue that you handle with server-side code, either by ignoring it, or by throwing a validatione error back to the user.
The way this is worded it makes me think this is a usability question as opposed to a programming question. Take a look at gmail and the ui they use for toggling selected emails. There is basically a checkall box at the top of the list which grays in checked if an email is checked. If you click it then it toggles everything to unchecked and switches to unchecked itself. If you click again it selects all. I think this UI works well.
Not sure if its what your are looking for, hope it help.
// Will select all checkbox input not checked, and checked them.
$(".checkbox-class:not(:checked)").attr('checked', true);
No tested.
Not entirely sure whether you're asking a UX question or a technical question. So I'll answer both. :-)
From a UX perspective, FWIW (and this may be off-topic), usually with an "all" button that toggles between "all" and "none", this is the state map I use:
all are checked => uncheck all
none are checked => check all
some are checked => check all
If you do that, this is really easy:
var cbs;
cbs = $(container).find('input[type=checkbox]');
cbs.attr('checked', cbs.not(':checked').length > 0);
Live example
...assuming all of these checkboxes are in some kind of container (e.g., a form or some div within the form, etc.).
If you want to do something else, you can still have jQuery to count the checked ones for you:
var cb, total, checked;
cb = $(container).find('input[type=checkbox]');
total = cb.length;
checked = cb.filter(':checked');
if (checked == total) {
// They're all checked
}
you can use this assuming you have all the checkboxes named email[]
Add this to the head of the page or in the script file you have:
<script type="text/javascript">
function checkAll()
{
checkBoxes = document.getElementsByName('email[]')
for(i=0;i<checkBoxes.length;i++)
if(!checkBoxes[i].checked)
checkBoxes[i].checked = true
}
function uncheckAll()
{
checkBoxes = document.getElementsByName('email[]')
for(i=0;i<checkBoxes.length;i++)
if(checkBoxes[i].checked)
checkBoxes[i].checked = false
}
</script>
and this in the body of the page:
Check All || Uncheck All
or add it as a button but dont forget to use"javascript:checkAll()"and"javascript:uncheckAll()"`
or store the state in a variable and do something like this?:
http://www.jsfiddle.net/EQuvq/12/
It sounds like you want two separate events: Select All and Deselect All. The most straightforward way to handle this is to have two separate buttons (or selections in a drop-down, whatever).
In this case, you'd want something like (in JavaScript using jQuery):
function selectAll() {
$(":checkbox").attr("checked", true);
}
function deselectAll() {
$(":checkbox").removeAttr("checked");
}
It's within the current HTML spec that the "checked" attribute have no value, but. If you're unsure about this, you can always use .attr("checked", true) instead.
If, on the other hand, you're looking for a function that toggles the state of each checkbox, then...
function toggleChecked() {
$(":checked").each(function() {
var checkedState = $(this).attr("checked");
$(this).attr("checked", !checkedState);
});
}
If, finally, you're looking for a function that assigns a checked state to all checkboxes, then...
function setChecked(state) {
$(":checked").attr("checked", state);
}

jQuery: Using autocomplete to add values to two fields instead of one

I want to use the autocomplete plugin for jQuery to populate not one, but two fields when selecting one of the autocomplete values - the name of a band is entered in the #band input field, but the band url (if exists) should also automatically be added to the #url input field when selecting the band name.
Right now I simply have an un-pretty list in an external php file from which the autocompleter takes it's values:
$bands_sql = "SELECT bands.name, bands.url
FROM bands
ORDER BY name";
$bands_result = mysql_query($bands_sql) or print (mysql_error());
while ($bands_row = mysql_fetch_array($bands_result)) {
$band_name = $bands_row['name'];
$band_url = $bands_row['url'];
echo $band_name."\n"; #needs to be replaced with an array that holds name and url
}
My autocomplete function looks very basic atm, but as I'm an absolute beginner when it comes to jQuery (and also clueless when it comes to PHP arrays), I have no idea how to tell it to populate two fields and not one.
$(document).ready(function() {
$("#band").autocomplete('/autocomplete-bands.php');
});
Is that even possible?!
sure check use result hadler so you can then do what you want once a choice has been made
I don't know about the particular plug-in you are using, but I would use the autocomplete widget for jQuery UI instead of a third party plug-in.
Here is an example of what you are looking for:
$("#band").autocomplete('/autocomplete-bands.php').result(function(event, data, formatted) {
if (data)
$('#url').(data['url']);
else {
// no data returned from autocomplete URL
}
});
I don't know much about php, but whatever the format of your data that is returned should be put where the data['url'] is currently in order to populate the #url input.

JQuery help with checkboxes and their values

I am very new to javascript and JQuery but I managed to get my first ajax script almost working 100%. Maybe today will be my lucky day and I can finish this up. :)
Let me give you guys a sample of each file so you know what is what. I believe that my last try at figuring this out was not successful because I was confusing these files. They are all js and have the exact same syntax.
What I have are 2 javascript files. One is called ajax.js and has the folling syntax. it calls ajax.php.
$("#admEmpID").bind("change", function(e){
$.getJSON("ajax.php?e=" + $("#admEmpID").val(),
function(data)
{
$.each(data, function(i,item)
{
if (item.field == "admEmpStatus")
{
// ?? radio buttons
}
............. etc
The next file I have is this script and is called admEmp.js. I think that this one is for my form validation.
$(function() {
$('.error').hide();
$('input.text-input').css({backgroundColor:"#FFFFFF"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#FFDDAA"});
});
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#FFFFFF"});
});
$(".admEmpBtn").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var admEmpID = $("input#admEmpID").val();
var admEmpStatus = $("input[name='admEmpStatus']:checked").val();
$.ajax({
type: "POST",...............etc.
What I would like to do is toggle my checkboxes according to the database results. If the result from the database is = 1 then the checkbox should be checked otherwise it should be unchecked.
These scripts that I have in place now will populate my textboxes from the values in the database so for someone like myself who has no idea what is happening with JQuery and its innerworkings, it is only natural for me to assume that the checkboxes will also be filled with the on/off values. Maybe I am incorrect. The last time I posted on SO looking for help, a guy mentioned that I needed to toggle the results with server side code. Is this correct or will JQuery do it for me?
I also have radio buttons in addition to the checkboxes that I need to show the values for as well. Just as a side note, the checkboxes are not grouped; they each have their own value.
Thanks for any help you guys can provide.
OK. "dz" said that I should put ('#admCustRptDly').attr('checked', true); into my script to see if that will allow me to see the checked attribute but it doesn't. The database has a 0 for that checkbox so I sould be seeing no checkmark. I put that into the ajax.js file. Here is what it looks like now.
else if (item.field == "admCustRptDly" && item.value == "1")
{
// $("checkbox#admCustRptDly").attr("checked", "checked");
$('#admCustRptDly').attr('checked', true);
}
Here is what I did that makes me think that I may be making some progress. I put an alert inside of the condition and I do NOT get an alert. If I go to a customer that does have the db value set to 1, then I do get the alert. That's more than I was getting before. But again, I am still seeing the checkmark even though the data in the db = '0'
Checkboxes behave a little differently than other input fields. When you have <input type="text" name="field1" value="foo" /> for example, the text field is automatically populated with "foo".
However, if you have <input type="checkbox" name="field2" value="1" />, the checkbox doesn't have anything to populate. This is because the checkbox has a special "checked" attribute that determines whether or not it is checked by default. As such, it's very possible your script that populates your textboxes are putting in the correct value for the checkbox, but are not setting the checked attribute.
To do so with jQuery, you can do $('#checkboxid').attr('checked', true);.
If I understand correctly, you have a form that is updated asynchronously via an Ajax call when you change the value in the #admEmpID field (first js file).
The second js file contains code to post changes you made to the form back to the server. I don't think it's for form validation (at least not the part you're showing).
But I'm not sure what the problem is. The first js file gets data from the server when you change some text field (#admEmpId). Is that data not shown correctly? You mention that textboxes are filled with the correct data. Are the checkboxes and radiobuttons not selected when they should be? In that case, you must first make sure you understand what data is returned from the server (contained in the data variable in the first js file). Then you must verify that the script addresses the right elements on your page to be updated.
You may just need another else if clause in your javascript for the case when you want to uncheck a box:
else if (item.field == "admCustRptDly" && item.value == "0")
{
$('#admCustRptDly').attr('checked', false);
}
You could, however, simplify both cases into a single statement like so:
else if (item.field == "admCustRptDly")
{
$('#admCustRptDly').attr('checked', ((item.value == "1") ? true : false));
}

Categories