...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
March 28, 2012

Checkbox confirm message – Remain checked if false

Question by benni_mac_b

I am currently trying to add a JavaScript confirm message when a user attempts to deselect an option.

If a user selects cancel on the confirm screen the check box should remain ticked. The problem I am having is that the check box becomes unchecked even if I return false.

Code example can be found here http://jsfiddle.net/Amjzv/

HTML

<div class="ServiceDesc Alternate">    
    <span class="expandable">
        <input id="ctl01_chk" type="checkbox" name="ctl01$chk" checked="checked">
    </span>                
</div>​

JQuery

$(document).ready(function () {
        //each load to persist state
        $('.expandable').each(function () {
            ToggleCheckboxes($(this),false);
        });
        $('.expandable').click(function () {
            ToggleCheckboxes($(this),true);
        });
    });
    //toggle child checkbox show/hide
    function ToggleCheckboxes(checkboxSpan, showConfirm) {
        if (checkboxSpan.find(':checked').length > 0) {
            checkboxSpan.parent().find('.indent').show();
        }
        else {
            if (showConfirm) {
                var answer = confirm("Are you sure?");
                if (answer) {
                    checkboxSpan.parent().find('.indent').hide();
                }
                else {
                    return false;
                }
            }
            else {checkboxSpan.parent().find('.indent').hide();}
        } 
    }​

Answer by iMoses

You are returning false inside your custom function, but not inside the function assigned to the click event. just fix the following line:

$('.expandable').click(function () {
    return ToggleCheckboxes($(this),true);
});

Answer by Starx

Simplest Way

$("#ctl01_chk").click(function() {
    if(confirm("Are you sure?")) { 
           // continue;
    } else { 
       return false;
    } 
});

Demo

Read more

Delegate for jQuery 1.3.2

Question by estrar

I got this code today that works for jQuery v7. The problem is that it need to work for 1.3.2 as well. How would I translate it?

$(document).ready(function() {
    $("ul#dropdown li ul").hide(); 
    $("ul#dropdown").delegate( 'li', 'click', function () {   
    if (!$(this).parent().is("ul#dropdown") ) {
            return false; 
        }  
    $(this).siblings('.' + "current").removeClass("current").children('ul').slideUp('fast');
    $(this).addClass("current").children('ul').slideDown('fast')
    });
});

Answer by Starx

The only option for delegation in 1.3 is live() method

$("ul#dropdown li").live('click', function () {   
    if (!$(this).parent().is("ul#dropdown") ) {
            return false; 
        }  
    $(this).siblings('.' + "current").removeClass("current").children('ul').slideUp('fast');
    $(this).addClass("current").children('ul').slideDown('fast')
});
Read more

Override colorbox onClose

Question by Эџad Дьdulяңмaи

I am using the following which works great. I am just wondering if it would be possible to override the onClosed after the box is loaded

    $.colorbox({href:"fff.html",
    onClosed:function(){ window.parent.location.reload(true); }
    });

I know that I can use the resize function after the box is loaded to resize the dimensions. Would it be possible to use the close functions similarly to accomplish my goal?

Answer by Starx

You can do it exactly the way you are attempting

$.colorbox({href:"fff.html",
    onClosed:function(){ 
       //This is your method that triggers onClose
       // SO go ahead, override it 

       //You can also call multiple function on it like

       function1(); //call function 1
       function2(); //call function 2
    }
});

Or, you can pass a function name to the onClosed() too like

$.colorbox({href:"fff.html",
    onClosed: overrideFunction
});

function overrideFunction() {
  /your overriding function
}
Read more

Differenece between window.location and location.href

Question by Rizwan Shahid

I am getting confused what is difference between window.location and location.href both are acting in same way

Answer by Mateusz W

Not really.
window.location is object that holds all information about current document location (host, href, port, protocol etc.).

location.href is shorthand for window.location.href (you call location from global object – window, so this is window.location.href), and this is only string with full url to current website.

They acting the same when you assign url to them – this will redirect to page which you assing, but you can see difference between them, when you open console (firebug, of developer tools) and write window.location and location.href.

Answer by Starx

location.href property returns the entire URL of the current page.

Where as

window.location property represents the currect location of the window object, if you change this you will get redirected.

Read more

Jquery form onchange select values changing

Question by Malyo

I’m looking for best solution to this problem. I have a simple shop logical problem. There are 2 select elements, size and color. I want to make them dependent, on data (now it’s example data, but later it’s gonna be from database) – size will decide which color options will be visible for customer (hiding not necessary ones).

First problem is that when i make change event, and i wanna hide the default shown element on document ready, it’s still visible (i’d have to change color to different than open dropdown again and it won’t be visible then).

Second is that i’m looking for most flexible solution, since i have doubts about mine. Here’s the code:

       var rozmiar = new Array("S", "M", "L", "XL", "XXL");
   var kolor = new Array("Czerwony", "Niebieski", "Zielony", "Biały", "Czarny");
   var opcje = new Array( rozmiar, kolor);

        $(document).ready(function(){
        $('.form1').change(function(){
                $('.form2 option').show();

                var selectSelector = function(z){
                    selectSelector = $('select.form2 option[value='+kolor[z]+']').hide();
                };

                wybranyRozmiar = $(this).val();
                    if(wybranyRozmiar == rozmiar[0]){
                        selectSelector(0);
                    }
                    if(wybranyRozmiar == rozmiar[1]){
                        selectSelector(1);
                    }
                    if(wybranyRozmiar == rozmiar[2]){
                        selectSelector(2);
                    }
                    if(wybranyRozmiar == rozmiar[3]){
                        selectSelector(3);
                    }
                    if(wybranyRozmiar == rozmiar[4]){
                        selectSelector(4);
                    }
            });
        });

Answer by Starx

I am answering the only part I understand.

Instead of using multiple if statements you can use switch

switch(selectsize) {
   case rozmiar[1]:
       $('select.form2 option[value='+color[2]+']').hide();
       break;
   //case <another>"
       //break;
}
Read more

php class function wrapper

Question by Patrick

this is my class:

class toyota extends car {
    function drive() {
    }
    function break() {
    }
}

class car {
    function pre() {
    }
}

Is there any way I can do so that when I run $car->drive(), $car->break() (or any other function in toyota), it would call $car->pre() first before calling the functions in toyota?

Answer by zerkms

Yep. You could use protected and some __call magic:

class toyota extends car {
    protected function drive() {
        echo "driven";
    }
    protected function dobreak() {
        echo "breakn";
    }
}

class car {
    public function __call($name, $args)
    {
        if (method_exists($this, $name)) {
            $this->pre();
            return call_user_func_array(array($this, $name), $args);
        }


    }

    function pre() {
        echo "pren";
    }
}

$car = new toyota();
$car->drive();
$car->dobreak();

http://ideone.com/SGi1g

Answer by Starx

This will better done with the magic methods called __call()

public function __call($name, $arguments)
{
    $this -> pre();
    return $this -> $name($arguments);
}

What is this method? It overrides the default method call, so that preCall State can be invoked.

Your toyota class

class toyota extends car {    

    public function __call($name, $arguments)
    {
        $this -> pre();
        return call_user_func_array(array($this, $name), $arguments);
    }

    function drive() {
    }
    function break() {
    }
}
Read more

Why doesn't this work? OOP novice

Question by Sorrybyenglish

I am new to OOP, so please do not be harsh.

My task is that this:

 $color = new Color(127,0,0);
 $rect = new Rectangle($color, 100, 50);
 $rect->render();

Should bring to the page the following code:

 "div style="background-color:RGB(127,0,0);width:100px;height:50px"></div>"

Below is my OOP code. The goal was to use an abstract class Component and with an abstract method render(). I am trying to figure out why code doesn’t work:

 class Color {
    protected $red;
    protected $green;
    protected $blue;
    public function __construct($red, $green, $blue) {
    $this->red = $red;
    $this->green = $green;
    $this->blue = $blue;
    }
 }
  abstract class Component {

    protected $color;
    protected $width;
    protected $height;

    public function __construct($color) {

    $this->color = new Color();

    }

    abstract function render();

  }
  class Rectangle extends Component {
    public function __construct($color, $width, $height){
    parent::__construct();
    $this->color = $color;
    $this->width = $width;
    $this->height = $height;
    }
    public function render() {
    echo "<div style='background-color:RGB(" . $this->color . ");width:" . $this->width .     "px;height:" . $this->height . "px'></div>";
    }
   }
  $color = new Color(127,0,0);
  $rect = new Rectangle($color, 100, 50);
  echo $rect->render();

Answer by Starx

You haven’t passed the $color object to the parent class, and the spelling of width is incorrect

public function __construct($color, $width, $height){
    parent::__construct($color); //The parent also needs a $color as it is defined
    $this->color = $color;
    $this->width = $width;
    $this->height = $height;
}
Read more

When is it semantically correct to use the hr element?

Question by John Doe

The HTML5 reference says that

The hr element represents a paragraph-level thematic break, e.g. a scene change in a story, or a transition to another topic within a section of a reference book.

That description is not enough descriptive to me. I use the hr element in my HTML documents as a way to separate content. Is this correct?

Could anyone give a few examples on when to use it (apart from the examples shown) and when to use CSS styling instead?

Answer by ceoux

It’s proper to use it when you have, say, several paragraphs with two distinct themes.

<p>Paragraph about domestic kittens</p>
<p>Paragraph about kittens' favourite foods</p>
<p>Paragraph about kittens' playfulness</p>
<hr>
<p>Paragraph about my day at work</p>

If you’d like to otherwise separate themes among images and content, I believe this is also appropriate.

<img src="/img/kitten.jpg" alt="kitten playing with ball">
<img src="/img/kitten1.jpg" alt="kitten drinking milk">
<hr>
<img src="/img/zebra.jpg" alt="zebras in the wild">

The new use of hr seems to just be for distinguishing topics within HTML. If you find that your content is well-connected, don’t feel that you need to use the tag.

Answer by Starx

According to this article

In HTML 4.01, the <hr> tag represented a horizontal rule.

In HTML5, the <hr> tag defines a thematic break.

However, the <hr> tag may still be displayed as a horizontal rule in
visual browsers, but is now defined in semantic terms, rather than
presentational terms.

All layout attributes (align, noshade, size, and width) in HTML 4.01
was deprecated in HTML 4.01, and is not supported in HTML5. Use CSS to
style the <hr> element instead.

In HTML5, use <hr> when you are diverting your topic from the previously written paragraph.

Read more

What does '" actually mean in PHP Syntax?

Question by Christus Cleetus

I have a piece of code and i keep getting syntax errors for codes like thess :

$query ="SELECT * from `jos_menu` where `id` = ".'".$parent.'";

Now when i reformat it as :

$query ="SELECT * from `jos_menu` where `id` = ".$parent;

That is when i remove : ‘”
it works fine. So i am just wondering, what does (‘”) actually do ???

Answer by Burhan Khalid

The only problem with

$query ="SELECT * from `jos_menu` where `id` = ".'".$parent.'";

Is that you missed a few ':

$query ="SELECT * from `jos_menu` where `id` = ".'"'.$parent.'"';

In PHP, a string can either be:

$var = 'This is a string';

Or

$var = "This is a string";

If you want to put " inside a string that you already started with ", you need tell PHP that you don’t want your second " to end the string but use the character " as part of the string itself. This is what " does. It tells PHP that Don’t give the " character any special meaning; since normally if you started the string with ", the next " would end the string.

means remove any “special” meaning to the next character

This only works if the character after the would have had special meaning. Some examples:

Suppose we want to print Hello "World". I am a string!:

$var = "Hello "World". I am a string!";

In this example we will have errors. Since we started the string with ", the next " will close the string. So what PHP thinks:

  1. " Start of string
  2. Hello part of string variable.
  3. " Hey, since I saw that the string was started with ", this must mean the end of it!
  4. World" <– Error

Stop processing and throw errors.

However, if we write:

$var = "Hello "World". I am a string!";

Now, PHP thinks:

  1. " Start of string
  2. Hello part of string variable
  3. Ah, okay, the next character I should remove any special meaning
  4. " Okay, this is immediately after , so I just use it normally, as a ".
  5. World part of string
  6. Okay, the next character I will remove any special meaning
  7. " This is now a normal "
  8. . I am a string! – part of string variable.
  9. " Ah! Since the string was started with ", this must be the ending.
  10. ; ends statement.

Hopefully this clarifies things for you.

Answer by Starx

It denotes escaped characters. The next character that appear after it, will be taken as its current form.

Your Query is incorrectly escaped

$query ="SELECT * from `jos_menu` where `id` = ".'".$parent.'";
                                               //^ You mismatched the quotes from here

A correctly escaped query should be

$query ="SELECT * from `jos_menu` where `id` = "$parent"";
                                           //  ^ Note here " will printed as it is within the query

For example,
If $parent was 2, then the query would be

 SELECT * from `jos_menu` where `id` = "2"
Read more
March 27, 2012

displaying all records in separate div

Question by user1292042

Ok. I have this code.

$result = mysql_query("SELECT * FROM items");

while($row = mysql_fetch_array($result))
{

    $ss = "<div>";
    $ss. = '<img src="'.$row['name'].'" />';  
    $ss. = $row['title'];
    $ss. = $row['description'];
    $ss. = $row['link'];
    $ss. = "</div>";

}

My HTML is like this

<html>
<head>
<style type="text/css">
body{background:gray;}
div{border:1px solid red;}
</style>
</head>
<body>
<? echo $ss; ?>
</body>
</html>

But I get an error

Parse error: syntax error, unexpected ‘=’ in … on line 83

I just want to display all records with separate div.

Answer by Starx

Problem is on this line

$ss. = '<img src="'.$row['name'].'" />';
// ^ See the . with the space in between, it should be .=

Continue fixing all the line like that.

Solution:

$ss = "";
while($row = mysql_fetch_array($result))
{

    $ss .= "<div>";
    $ss .= '<img src="'.$row['name'].'" />';  
    $ss .= $row['title'];
    $ss .= $row['description'];
    $ss .= $row['link'];
    $ss .= "</div>";

}
Read more
...

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