...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
June 2, 2010

How to conditionally execute a jquery validation?

Question by Chendur Pandian

I am validating form using jquery validation plugin……

 rules: {
    Name: "required",
    MobileNo: {
           required: true,
           minlength: 10, remote: '<%=Url.Action("getClientMobNo", "Clients") %>'
               },
    Address: "required"
            },
    messages: {
        Name: "please provide a client name",
        MobileNo: {
        required: "Please provide a mobile phone no",
        rangelength: jQuery.format("Enter at least {0} characters"),
        remote: jQuery.format("This MobileNo is already in use")
      },
      Address: "please provide client address"
   },

This works pretty well on add form validation but i use the same form for edit here they can use the same mobile no,but my plugin validates that mobileno saying there is already a mobileno… But how to execute remote attribute based on a condition,

   MobileNo: {
           required: true,
           minlength: 10,
          if($("#HfId").val() == ""){ 
            remote: '<%=Url.Action("getClientMobNo", "Clients") %>'
             }
          },

Is this a valid jquery conditional validation statement…. How to skip remote attribute based on a condition….

Answer by Starx

Well, I would do something like this

for example my php page is member.php

to add, send a URL like this member.php?action=add

<? 
$action = $_GET['action'];
?>
<script>
        $("#frmmember").validate({
      rules: { 
        name: { 
                <? if($action=='add') { ?>
                      required: true, 
               <? } ?>
                      rangelength: [4, 50] },
        email: { required: true, rangelength: [5, 50], email: true },
        phone: { required: true, number:true, rangelength: [7, 10] }
        },
      onkeyup: false
    });
</script>

In this case, the validation rule required=true is only going to apply if there is “add” in the url variable "action"

Read more

How to get TinyMCE and Jquery validate to work together?

Question by chobo2

I am using jquery validate and the jquery version of tinymce.

I found this piece of code that makes tinymce to validate itself every time something changes in it.

Hi

I am using the jquery validate with my jquery tinymce so I have this in my code

    // update validation status on change
    onchange_callback: function (editor)
    {
        tinyMCE.triggerSave();
        $("#" + editor.id).valid();
    },

This works however there is one problem. If a user copies something from word it brings all that junk styling with it what is usually over 50,000 characters. This is way over my amount of characters a user is allowed to type in.

So my jquery validation method goes off telling me that they went over the limit. In the mean time though tinymce has cleaned up that mess and it could be possible now the user has not gone over the limit.

Yet the message is still there.

So is there a better function call I can put this in? Maybe tell tinymce to delay the valid when a paste is happening, or maybe a different callback?

Anyone got any ideas?

Answer by Starx

Oh yeah, I also faced this problem.

So, I fixed it by calling the validation on the click event of a button instead.

$("#buttontosave").click(function() {
         tinyMCE.triggerSave();
         var status;
         status = $("#myform").valid(); //Validate again
         if(status==true) { 
             //Carry on
         }
         else { }
});

This works try it.

For additional resources try

http://blog.rebeccamurphey.com/2009/01/12/jquery-validation-and-tinymce/

http://tinymce.moxiecode.com/punbb/viewtopic.php?id=21588

http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/Q_23941005.html

Read more

how to set focus on top of the page

Question by vakas

How do I set focus to the top of a page?

Answer by Starx

It would be helpful if you write a little so that we can understand your problem.

A very easy way is linking to class or id on a page.

For example this page “page.html”

<body>
        <div id="top"> ..................Content................</div>
        <div id="otherdiv">........................</div>
</body>

then if you need to focus on top, send a link like “page.html#top” the page will automatically focus on top

or if you want to stick to javascript then do this

document.location.href = '#top'; //to send it to the top

But I would say use simple html anchor to go to top like

<a href="#top">Back to Top</a>

Read more
May 31, 2010

How to hide jQuery Sub-Menus(ddsmoothmenu)?

Question by Tim Schmelter

I’m new to jQuery and i must admit that i’ve understood nothing yet, the syntax appears to me as an unknown language although i thought that i had my experiences with javascript.
Nevertheless i managed it to implement this menu in my asp.net masterpage’s header.
Even got it to work that the content-page is loaded with ajax with help from here.
But finally i’m failing with the menu to disappear when the new page was loaded asynchronously. I dont know how to hide this accursed jQuery Menu.

Following the part of the js-file where the events are registered for hiding/disappearing. I dont know how to get the part that is responsible for it and even i dont know how to implement that part in my Anchor-onclick function where i dont have a reference to the jQuery Object.

buildmenu:function($, setting){
 var smoothmenu=ddsmoothmenu
 var $mainmenu=$("#"+setting.mainmenuid+">ul") //reference main menu UL
 $mainmenu.parent().get(0).className=setting.classname || "ddsmoothmenu"
 var $headers=$mainmenu.find("ul").parent()
 $headers.hover(
  function(e){
   $(this).children('a:eq(0)').addClass('selected')
  },
  function(e){
   $(this).children('a:eq(0)').removeClass('selected')
  }
 )
 $headers.each(function(i){ //loop through each LI header
  var $curobj=$(this).css({zIndex: 100-i}) //reference current LI header
  var $subul=$(this).find('ul:eq(0)').css({display:'block'})
  $subul.data('timers', {})
  this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
  this.istopheader=$curobj.parents("ul").length==1? true : false //is top level header?
  $subul.css({top:this.istopheader && setting.orientation!='v'? this._dimensions.h+"px" : 0})
  $curobj.children("a:eq(0)").css(this.istopheader? {paddingRight: smoothmenu.arrowimages.down[2]} : {}).append( //add arrow images
   '<img src="'+ (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[1] : smoothmenu.arrowimages.right[1])
   +'" class="' + (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[0] : smoothmenu.arrowimages.right[0])
   + '" style="border:0;" />'
  )
  if (smoothmenu.shadow.enable){
   this._shadowoffset={x:(this.istopheader?$subul.offset().left+smoothmenu.shadow.offsetx : this._dimensions.w), y:(this.istopheader? $subul.offset().top+smoothmenu.shadow.offsety : $curobj.position().top)} //store this shadow's offsets
   if (this.istopheader)
    $parentshadow=$(document.body)
   else{
    var $parentLi=$curobj.parents("li:eq(0)")
    $parentshadow=$parentLi.get(0).$shadow
   }
   this.$shadow=$('<div class="ddshadow'+(this.istopheader? ' toplevelshadow' : '')+'"></div>').prependTo($parentshadow).css({left:this._shadowoffset.x+'px', top:this._shadowoffset.y+'px'})  //insert shadow DIV and set it to parent node for the next shadow div
  }
  $curobj.hover(
   function(e){
    var $targetul=$subul //reference UL to reveal
    var header=$curobj.get(0) //reference header LI as DOM object
    clearTimeout($targetul.data('timers').hidetimer)
    $targetul.data('timers').showtimer=setTimeout(function(){
     header._offsets={left:$curobj.offset().left, top:$curobj.offset().top}
     var menuleft=header.istopheader && setting.orientation!='v'? 0 : header._dimensions.w
     menuleft=(header._offsets.left+menuleft+header._dimensions.subulw>$(window).width())? (header.istopheader && setting.orientation!='v'? -header._dimensions.subulw+header._dimensions.w : -header._dimensions.w) : menuleft //calculate this sub menu's offsets from its parent
     if ($targetul.queue().length<=1){ //if 1 or less queued animations
      $targetul.css({left:menuleft+"px", width:header._dimensions.subulw+'px'}).animate({height:'show',opacity:'show'}, ddsmoothmenu.transition.overtime)
      if (smoothmenu.shadow.enable){
       var shadowleft=header.istopheader? $targetul.offset().left+ddsmoothmenu.shadow.offsetx : menuleft
       var shadowtop=header.istopheader?$targetul.offset().top+smoothmenu.shadow.offsety : header._shadowoffset.y
       if (!header.istopheader && ddsmoothmenu.detectwebkit){ //in WebKit browsers, restore shadow's opacity to full
        header.$shadow.css({opacity:1})
       }
       header.$shadow.css({overflow:'', width:header._dimensions.subulw+'px', left:shadowleft+'px', top:shadowtop+'px'}).animate({height:header._dimensions.subulh+'px'}, ddsmoothmenu.transition.overtime)
      }
     }
    }, ddsmoothmenu.showhidedelay.showdelay)
   },
   function(e){
    var $targetul=$subul
    var header=$curobj.get(0)
    clearTimeout($targetul.data('timers').showtimer)
    $targetul.data('timers').hidetimer=setTimeout(function(){
     $targetul.animate({height:'hide', opacity:'hide'}, ddsmoothmenu.transition.outtime)
     if (smoothmenu.shadow.enable){
      if (ddsmoothmenu.detectwebkit){ //in WebKit browsers, set first child shadow's opacity to 0, as "overflow:hidden" doesn't work in them
       header.$shadow.children('div:eq(0)').css({opacity:0})
      }
      header.$shadow.css({overflow:'hidden'}).animate({height:0}, ddsmoothmenu.transition.outtime)
     }
    }, ddsmoothmenu.showhidedelay.hidedelay)
   }
  ) //end hover
 }) //end $headers.each()
 $mainmenu.find("ul").css({display:'none', visibility:'visible'})
}

one link of my menu what i want to hide when the content is redirected to another page(i need “closeMenu-function”):

<li><a href="DeliveryControl.aspx" onclick="AjaxContent.getContent(this.href);closeMenu();return false;">Delivery Control</a></li>

In short: I want to fade out the submenus the same way they do automatically onblur, so that only the headermenu stays visible but i dont know how.

Thanks, Tim

EDIT: thanks to Starx’ private-lesson in jQuery for beginners i solved it:
I forgot the # in $(“#smoothmenu1”). After that it was not difficult to find and call the hover-function from the menu’s headers to let them fade out smoothly:

$("#smoothmenu1").find("ul").hover(); 

Regards,
Tim

Answer by Starx

Ok, I didn’t read your whole post. But if you are using a jQuery Menu, that menu should having a container element like <div> or <ul> and they will either have a class or id

In case it is a id then do

$(document).ready(function() {
      $("#myelementid").hide();
});

In case it has a class then do

$(document).ready(function() {
      $(".myelementclass").hide();
});

Hope this helps

UPDATE

$("#mainmenu").children().hide(); // to hide all child elements

or

$(".submenu").hide(); //to hide every submenu
Read more

Dynamically loading external HTML in a div using Java Script

Question by user354051

I have prepared some demo examples for the topic.
There is page name “changelog.html” here:

http://pantheon-studios.in/test/jquery/changelog.html

This is working fine if loaded directly.

I am trying to load this page dynamically into:

http://pantheon-studios.in/test/jquery/index.html

Here changelog.html doesn’t behaving as expected.

I think the init script on changelog.html is not getting executed or something else is happening when loading it dynamically.

Like wise I do have couple of other pages using various jQuery and other java scripts plugins. Some of those needs initialization like animatedcollapse.js in the above example, and couple of them doesn’t need initialization, you can directly call the script and go.

I also gave a try using:

jQuery.getScript("anim.js")

after dynamically loading “changelog.html” but doesn’t work.

The “anim.js” contains

animatedcollapse.addDiv('cat', 'fade=0,speed=400,group=pets,hide=1');
animatedcollapse.addDiv('dog', 'fade=0,speed=400,group=pets,hide=1');
animatedcollapse.addDiv('rabbit', 'fade=0,speed=400,group=pets,hide=1');
animatedcollapse.init();

I would really appreciate is some one point me out the right direction. I am completely new to web programming so please have some patience with me.

Thanks

Answer by Starx

I solved your problem

your index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">

<head>    
    <!-- Java Scripts -->
    <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#clickme").click(function() { 
                $("#content").load("changelog.html");
            });
        });
    </script>
</head>

<body>
    <a href="javascript:void(0)" id="clickme">Load HTML</a>            
    <div>
        <div id="content"></div>
    </div>

</body>
</html>

Your changelog.html

    <script type="text/javascript" src="js/animatedcollapse.js"></script>
    <script type="text/javascript">

        animatedcollapse.addDiv('cat', 'fade=0,speed=400,group=pets,hide=1');
        animatedcollapse.addDiv('dog', 'fade=0,speed=400,group=pets,hide=1');
        animatedcollapse.addDiv('rabbit', 'fade=0,speed=400,group=pets,hide=1');



    animatedcollapse.ontoggle=function($, divobj, state){ //fires each time a DIV is expanded/contracted
        //$: Access to jQuery
        //divobj: DOM reference to DIV being expanded/ collapsed. Use "divobj.id" to get its ID
        //state: "block" or "none", depending on state
    };        
    animatedcollapse.init();    

    </script>    
    <!-- CSS Stylesheet -->
    <style type="text/css">
    .topicdetail{
    text-align:justify;
    width:650px;
    padding-left:10px;
    padding-right:10px;
    /*background: #BDF381;*/
    font-size: 13px;
    }
    </style>
    <div id="container">      
        <ul>
      <li>Compilation command in preferences is more simplified.<a href="javascript:animatedcollapse.toggle('cat')">?</a>
            <div id="cat" class='topicdetail'>

                <br/>
                <p>
                The cat (Felis catus), also known as the domestic cat or house cat to distinguish it from other felines,
                is a small carnivorous species of crepuscular mammal that is often valued by humans for its companionship
                and its ability to hunt vermin. It has been associated with humans for at least 9,500 years.
                A skilled predator, the cat is known to hunt over 1,000 species for food. It can be trained to obey simple 

commands. 
                </p>
                <br/>
            </div>
          </li>

          <li>Compilation command in preferences is more simplified.<a href="javascript:animatedcollapse.toggle('dog')">?</a>

          <div id="dog" class='topicdetail'>
                <br/>
                <p>
                The cat (Felis catus), also known as the domestic cat or house cat to distinguish it from other felines,
                is a small carnivorous species of crepuscular mammal that is often valued by humans for its companionship
                and its ability to hunt vermin. It has been associated with humans for at least 9,500 years.
                A skilled predator, the cat is known to hunt over 1,000 species for food. It can be trained to obey simple 

commands. 
                </p>
                <br/>
            </div>
          </li>

          <li>Compilation command in preferences is more simplified.<a href="javascript:animatedcollapse.toggle('rabbit')">?

</a>

          <div id="rabbit" class='topicdetail'>
                <br/>
                <p>
                The cat (Felis catus), also known as the domestic cat or house cat to distinguish it from other felines,
                is a small carnivorous species of crepuscular mammal that is often valued by humans for its companionship
                and its ability to hunt vermin. It has been associated with humans for at least 9,500 years.
                A skilled predator, the cat is known to hunt over 1,000 species for food. It can be trained to obey simple 

commands. 
                </p>
                <br/>
            </div>
          </li>
        </ul>    
    </div>

Just copy and paste the html

Read more

finding a way to track website users

Question by sdr

I want to know that is there any way to know after which page an user is leaving the website.

So that I can track that page and work to improve the content of that page.

I am using PHP as backend code.

Answer by Starx

If you want to see which is the last page a user is visiting, you can do something like this

I am assuming that you have a mysql connection already provided.
Create a page like “session.php” and place this function

function trackpage($pagename) {
    if(!isset($_SESSION)) { 
       // if the user is visiting the website for the first time
       session_start();
       $query = "INSERT INTO `newusers` VALUES(NULL, '$pagename');";
       //In case table 'newuser' have two fields 'id' and 'page' to keep a track of page
       $result = mysql_query($query) or die(mysql_error());
       $_SESSION['userid'] = mysql_insert_id();
    }
    else {
       //if he is just visiting another page
       $query = "UPDATE `newusers` SET page='$pagename' WHERE id='".$_SESSION['userid']."';";
       $result = mysql_query($query) or die(mysql_error());   
    }
}

Npw you need to include this on every page. on the top write this

<?
include "session.php";
trackpage("index.php");
?>

Now you know on what page are people leaving the website

Read more
May 28, 2010

How do i hide html until its processed with javascript?

Question by acidzombie24

I am using some JS code to transform my menu into a drilldown menu.

The problem is before it runs the JS you see a BIG UGLY mess of links. On their site its solved by putting the js at the top. Using recommendations by yahoo/YSlow i am keeping the JS files at the bottom.

I tried hiding the menu with display:none then using jquery to .show(), .css(‘display’, ”), .css(‘display’, ‘block’) and they all lead up to a messsed up looking menu (i get the title but not the title background color or any links of the menu)

How do i properly hide a div/menu and show it after being rendered?

Answer by acidzombie24

I found the solution. I should let the links be hidden with css then .show() BEFORE the ddMenu code executes instead of after. The ddMenu seems to check the parents width and sinces its hidden i guess its 0. The time between .show() and ddMenu is fast enough not to show the ugly links (on my machine/browser). The the majority of the time (page loading, http req for the JS files, JS compiling/exec etc) the links are hidden so it looks pretty good.

$(function () {
    $('.menuT1').show(); //do it before not after in this case.
    $('.menuT1 > ul').ddMenu({

Answer by Starx

Well, If you are familiar with jquery then I would do something like this

$("#mybuttom").click(function() {
           $("#mydiv").hide(); //hide the div at the start of process
           $.post( "mypostpage.php", 
                   { testvar: testdata },
                   function(data) {
                         //callback function after successful post
                         $('#mydiv').show(); //show it again
                   }
           );
});
Read more

CSS nested div height 100%

Question by Aaron Moodie

I’ve currently got the #border div at 100% of the page height, but am trying to get the #container div to stretch to 100% inside #border. At the moment #container only stretches to fit the content inside it.

* {
    margin: 0;
}

html, body {
    height:100%;
    font-family: Georgia, Times, "Times New Roman", serif;
    font-size:13px;
    line-height:19px;
    color:#333333;
    background: #f5f1ec;
    text-align: left;
}

#border {
    background: #f5f1ec;
    border:solid 1px #FFFFFF; 
    width: 880px;
    margin: 40px auto 0;
    padding:10px;
    height: auto !important;
    min-height: 100%;
    height: 100%;
}

#container {
    background: #FFFFFF;
    padding: 10px 50px 0;
    height: 100%;
}

Answer by Starx

Solved:

#container {
    background: #FFFFFF;
    padding: 10px 50px 0;
    height: 100%;
    width:780px;
    position:absolute;
}
Read more
May 27, 2010

How to show hidden div when javascript is disabled?

Question by Jitendra Vyas

I’m hiding a div using display:none and this div only shows when we click on + icon. but if JavaScript is disabled then I want to show that div by default on. How to do this?

I can’t post whole code for now.

jQuery(document).ready(function() {
  jQuery('a#toggle').click(function() {
       jQuery('#map').slideToggle(400);
       return false;

});

CSS

#map {display:none}

Answer by deceze

Only hide it if Javascript is enabled:

<head>
    <script type="text/javascript" charset="utf-8">
        document.write('<style type="text/css" media="screen">#map { display: none; }</style>');
    </script>
</head>

Answer by Starx

I think

<noscript>Your browser does not support JavaScript!</noscript>

This would be a better idea that other

Put the division you want to show if the javascript is not enable inside <noscript> tags

Read more
May 26, 2010

Best way to install multiple versions of Apache, PHP and MySQL on a single FreeBSD host

Question by Mikael Roos

I want a test- and development-environment for web using Apache, PHP and MySQL. I need to be able to test a single web-application with multiple versions of PHP (5.2, 5.3, etc) and multiple versions of MySQL (5.0, 5.1, 5.5, etc). It shall be hosted on a FreeBSD server.

My idea is to compile each version into a directory structure and running them on separate portnumbers. For example:

opt/apache2.2-php5.2-mysql-5.0 
(httpd on port 8801, mysql on port 8802)
(directory contains each software, compiled and linked towards eachother)

opt/apache2.2-php5.3-mysql-5.1 
(httpd on port 8803, mysql on port 8804)
(and so on)

Any thoughts or suggestions of the best way to setup this type of environment?

UPDATE:
Question moved to serverfault:
http://serverfault.com/questions/145504/best-way-to-install-multiple-versions-of-apache-php-and-mysql-on-a-single-freebs

Answer by Starx

Read more
...

Please fill the form - I will response as fast as I can!