javascript combo box - php

I have used this function to call the following page depending on the chosen option.
The First IF will direct me to the Monthly report while the second IF will direct me to the Daily report
<script type="text/javascript">
function ActionDeterminator()
{
var monthly = document.myform.duration.options[0].value;
var daily = document.myform.duration.options[1].value;
if (monthly == 0){
document.myform.action = 'month.php';
}
if (daily == 1) {
document.myform.action = 'day.php';
}
}
</script>
I have also another function which will execute a job depending on the option. The first IF will convert my report to excel doc while the second IF will direct me to view page to print.
<script type="text/javascript">
function ActionDeterminator()
{
if(document.myform.group[0].checked == true) {
document.myform.action = 'excel.php';
}
if(document.myform.group[1].checked == true) {
document.myform.action = 'view.php';
}
return true;
}
</script>
The Problem:
the problem is that it does not direct me to the correct page (whether monthly or daily)... it only directs me to view page or exporting to excel. Could anyone teach me the correct way to do this function?
Also, I want to ask the correct javascript for combo box.

What you'll want to do is get all the form elements into an array, loop, and evaluate for checked equals true
For example:
var elems = document.getElementsByName('group');
for (var i=0; i<elems.length; i++) {
if (elems.item(i).checked == true) {
break;
}
}
switch (i) {
case 0:
//action = 'excel.php';
break
//case etc...
}

Related

hiding php created divs during onload with javascript

I am running the javascript function shoh() below on page load to hide div's. This works fine on html hard coded divs but appears not to be working on divs that are created via php. Am I correct in assuming that the javascript runs first before the php creates the divs and that is why they aren't being hidden? If so, is there any other way to hide these divs after they are created? They need to be shown by default in case javascript is disabled?
code which runs with onload:
<script type="text/javascript">
function closeAllDivs() {
shoh('g1');
shoh('g2');
shoh('g3');
shoh('g4');
}
</script>
<BODY onLoad="closeAllDivs();">
javascript to hide divs:
function shoh(id) {
if (document.getElementById) { // DOM3 = IE5, NS6
if (document.getElementById(id).style.display == "none"){
document.getElementById(id).style.display = 'block';
filter(("img"+id),'imgin');
} else {
filter(("img"+id),'imgout');
document.getElementById(id).style.display = 'none';
}
} else {
if (document.layers) {
if (document.id.display == "none"){
document.id.display = 'block';
filter(("img"+id),'imgin');
} else {
filter(("img"+id),'imgout');
document.id.display = 'none';
}
} else {
if (document.all.id.style.visibility == "none"){
document.all.id.style.display = 'block';
} else {
filter(("img"+id),'imgout');
document.all.id.style.display = 'none';
}
}
}
}
php code which creates divs:
for ($i=0; $i < count($this->items); $i++){
<div style="display: block;" id="g<? echo $i ?>">
... code that displays items
</div>
}
It shouldn't really matter so much whether the php made the divs or whether they're hardcoded - by the time the HTML hits the browser, it's already the same thing. The server processes the PHP - by the time it leaves the server and heads to the browser, there is no PHP anymore.
I'd recommend using window.onload instead of a <body onload="">
window.onload = function() {
closeAllDivs();
};
Thanks to Wolfman Joe for letting me know the problem was likely not with the order of things. This told me the shoh() function was likely failing and therefore interrupting execution... so the code to close the divs was never executed. The solution was to build a check into the shoh() function to first make sure the div existed before attempting to change its property. As it turns out, not all divs $i were being created.
function shoh(id) {
if (document.getElementById) { // DOM3 = IE5, NS6
if (document.getElementById(id)){
if (document.getElementById(id).style.display == "none"){
document.getElementById(id).style.display = 'block';
filter(("img"+id),'imgin');
} else {
filter(("img"+id),'imgout');
document.getElementById(id).style.display = 'none';
}
}
}
}

Javascript in a Included PHP File

I have a php file (a form) that includes javascript to check if all inputs are filled. When I view the php file directly the js works perfectly, but when I include the PHP file in another page the javascript no longer works.
My javascript code:
<script type="text/javascript" src="../js/modernizr.js"></script>
<script type="text/javascript">
window.onload = function(){
document.getElementById("topField").setAttribute("autocomplete","off");
}
window.onload = function() {
// get the form and its input elements
var form = document.forms[0],
inputs = form.elements;
// if no autofocus, put the focus in the first field
if (!Modernizr.input.autofocus) {
inputs[0].focus();
}
// if required not supported, emulate it
if (!Modernizr.input.required) {
form.onsubmit = function() {
var required = [], att, val;
// loop through input elements looking for required
for (var i = 0; i < inputs.length; i++) {
att = inputs[i].getAttribute('required');
// if required, get the value and trim whitespace
if (att != null) {
val = inputs[i].value;
// if the value is empty, add to required array
if (val.replace(/^\s+|\s+$/g, '') == '') {
required.push(inputs[i].name);
}
}
}
// show alert if required array contains any elements
if (required.length > 0) {
alert('The following fields are required: ' +
required.join(', '));
// prevent the form from being submitted
return false;
}
};
}
}
</script>
This is an explanation to anyone who finds this question later. In javascript you can only attach a single function to an event handler. If you want to attach more, you need to chain them. Pretty much all javascript framework/libraries has some sort of method to handle event chaining.
Javascript allows you to treat functions like variables. So you can assign an old onload function to a variable, then call it later within the new onload function.
If you are not using a framework, you can do something like this to handle event chaining.
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
You would call this with the following:
addLoadEvent(function(){
// Some code here
});

I'd like to detect the value chosen from a drop down, and then pass that to the page url and reload

I have some javascript sorting my ul, alphabetically a-z or z-a. It works fine on page one, but if there is more than one page it ignores the list on page 2 etc.
So, instead of using javascript to sort the li's, I want to pass the selection back to the page's query and reload
here's my script, most of which is redundant now.
var select = document.getElementById('organise');
$('#organise').change(function() {
if(select.value === 'A') {
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? 1 : -1;
});
} else {
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? -1 : 1;
});
}
});
So I want to detect the selected dropdown value (either A or Z) and pass that into the url and reload. I'm stuck ;-?
Rich :)
I am not sure this is the best way to approach the problem, and maybe you should elaborate what doesn't work with your pagination. In any case, you can achieve what you need to do by doing something like this (explaination in the code comments):
var queryString = {};
// Get the previous query string with a little help from PHP
// this shouldn't be a problem since you are already using PHP
// for your project.
queryString = <?php json_encode( $_GET ); ?>;
$('#organise').change( function() {
// Set the sort property of the object to the value of the select.
queryString.sort = $(this).val();
// jQuery will help you serialise the JSON object back to
// a perfectly valid query string (you may want to escape
// characters)
newQueryString = $.param( queryString );
// Append the new query string
window.location = newQueryString;
});
This function will properly check if you already have any query string and preserve that; also, if the user changes the select multiple times, it will not add up several query strings.
you can change the url and pass the param with
document.location.href = document.location.href + "?arg=" + document.getElementById("organise").value;
You can use localstorage for this if you don't want to show in url
For example:
function Ascending()
{
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? 1 : -1;
});
}
function Descending()
{
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? -1 : 1;
});
}
if(localStorage.order=='A')
{
return Ascending();
}
else
{
return Descending();
}
var select=document.getElementById('organise');
$('#organise').change(function() {
if(select.value === 'A') {
localStorage.order=='A';
return Ascending();
} else {
localStorage.order=='Z';
return Descending();
}
});
Refer more for localStorage on http://www.w3schools.com/html/html5_webstorage.asp

Use Jquery to update a PHP session variable when a link is clicked

I have several divs that a user can Minimize or Expand using the jquery toggle mothod. However, when the page is refreshed the Divs go back to their default state. Is their a way to have browser remember the last state of the div?
For example, if I expand a div with an ID of "my_div", then click on something else on the page, then come back to the original page, I want "my_div" to remain expanded.
I was thinking it would be possible to use session variables for this, perhaps when the user clicks on the expand/minimize button a AJAX request can be sent and toggle a session variable...IDK..any ideas?
There's no need for an ajax request, just store the information in a cookie or in the localstorage.
Here's a library which should help you out: http://www.jstorage.info/
Some sample code (untested):
// stores the toggled position
$('#my_div').click(function() {
$('#my_div').toggle();
$.jStorage.set('my_div', $('#my_div:visible').length);
});
// on page load restores all elements to old position
$(function() {
var elems = $.jStorage.index();
for (var i = 0, l = elems.length; i < l; i++) {
$.jStorage.get(i) ? $('#' + i).show() : hide();
}
});
If you don't need to support old browsers, you can use html5 web storage.
You can do things like this (example taken from w3schools):
The following example counts the number of times a user has visited a
page, in the current session:
<script type="text/javascript">
if (sessionStorage.pagecount) {
sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
}
else {
sessionStorage.pagecount=1;
}
document.write("Visits "+sessionStorage.pagecount+" time(s) this session.");
</script>
Others have already given valid answers related to cookies and the local storage API, but based on your comment on the question, here's how you would attach a click event handler to a link:
$("#someLinkId").click(function() {
$.post("somewhere.php", function() {
//Done!
});
});
The event handler function will run whenever the element it is attached to is clicked. Inside the event handler, you can run whatever code you like. In this example, a POST request is fired to somewhere.php.
I had something like this and I used cookies based on which user logged in
if you want only the main div don't use the
$('#'+div_id).next().css('display','none');
use
$('#'+div_id).css('display','none');
*Here is the code *
//this is the div
<div id = "<?php echo $user; ?>1" onclick="setCookie(this.id)" ><div>My Content this will hide/show</div></div>
function setCookie(div_id)
{
var value = '';
var x = document.getElementById(div_id);
var x = $('#'+div_id).next().css('display');
if(x == 'none')
{
value = 'block';
}
else
{
value = 'none';
}
console.log(div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/")
//alert(x);
document.cookie = div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/";
}
function getCookie(div_id)
{
console.log( div_id );
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==div_id)
{
return unescape(y);
}
}
}
function set_status()
{
var div_id = '';
for(var i = 1; i <= 9 ; i++)
{
div_id = '<?php echo $user; ?>'+i;
if(getCookie(div_id) == 'none')
{
$('#'+div_id).next().css('display','none');
}
else if(getCookie(div_id) == 'block')
{
$('#'+div_id).next().slideDown();
}
}
}
$(document).ready(function(){
get_status();
});
Look about the JavaScript Cookie Method, you can save the current states of the divs, and restore it if the User comes back on the Site.
There is a nice jQuery Plugin for handling Cookies (http://plugins.jquery.com/project/Cookie)
Hope it helps
Ended up using this. Great Tutorial.
http://www.shopdev.co.uk/blog/cookies-with-jquery-designing-collapsible-layouts/

computing result based on two different ajax request

i have a simple form with two fields whose data are being validated against a database on keyup with jquery. I am also having a button which is currently enabled or disabled based on the number of characters entered in these two fields. THe two jquery functions return an "accept" or "cancel" image for the two fields. I want to enable the button only if both the functions return the accept image or i can even make them return true along with it, which will not be a problem. I just wanna know how to compute a local result based on the returned value from two different ajax requests.
These are two functions that validate teh field against a database.
$("#agentName").keyup(function(){
var agentName = $("#agentName").val();
if(agentName.length > 3)
{
$("#agt-name-result").html(ajax_load).load(loadUrl, "val="+agentName+"&fld=agent_name");
}
else{
$("#agt-name-result").html("<img src=\"images/cancel.png\" />");
}
});
$("#agentSource").keyup(function(){
var agentSource = $("#agentSource").val();
if(agentSource.length > 9)
{
$("#agt-src-result").html(ajax_load).load(loadUrl, "val="+agentSource+"&fld=agent_url");
}
else{
$("#agt-src-result").html("<img src=\"images/cancel.png\" />");
}
});
This is the function that validates the button
$("#agentName,#agentSource").keyup(function(){
var validate;
var agentName = $("#agentName").val();
var agentSource = $("#agentSource").val();
if((agentName === "") || (agentSource === "") || (agentName.length < 3) || (agentSource.length < 10))
{
validate = false;
}
else { validate = true; }
if(validate === true) {
$("#addAgntBtn").removeAttr("disabled");
$("#addAgntBtn").removeClass("dialog-btn-disabled").addClass("dialog-btn");
}
else {
$("#addAgntBtn").attr("disabled", "disabled");
$("#addAgntBtn").removeClass("dialog-btn").addClass("dialog-btn-disabled");
}
});
Any ideas?
I would use a setInterval to poll a $.data() value in which the two ajax calls put their results. You have to pay attention to concurrent accesses, but it should work

Categories