...

Hi! I’m Starx

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

Get unique id after the fact?

Question by qitch

I want to be able to change a button image on click which isn’t the issue. Each button is unique to information that is pulled from the database and on click the button should change and send the appropriate info to the database. What I am unsure about is how I can change the specific button. Say there are five things up, so five buttons. Each button has its unique id to go with its information. How can I find out what the id is so that I can manipulate the button?

I use php to grab the info from the database and go through a while loop to get it all displayed. Once it is all displayed it is there for the user to see and then they can click on the button.

edit – It just came to me. I can make my onclick function take a variable and feed the variable into it. Right?

Answer by Starx

A simple trick actually. Call a function on the click and pass its id, to it as a parameter.

<button id="id1" onClick="handleclick(this.id)">Button1</button>
<button id="id2" onClick="handleclick(this.id)">Button2</button>

<script>
function handleclick(id)
{
    alert(id); //here is your id
}
</script>

Demo


Alternative

You can do something like this also

buttons = document.getElementsByTagName("button");
for( var x=0; x < buttons.length; x++ ) {
    buttons[x].onclick = handleclick;
}

Demo 2

Read more

Click event listener on a <tr>

Question by Jonny Sooter

I have this event that listens for a click on a img then it switches the img for another, but this img can get real small and I wanted to make the entire tr click able. Any suggestions?

$('#example tbody td img').live('click', function () {
                var nTr = $(this).parents('tr')[0];
                if ( oTable.fnIsOpen(nTr) )
                {
                    /* This row is already open - close it */
                    this.src = "images/details_open.png";
                    oTable.fnClose( nTr );
                }
                else
                {
                    /* Open this row */
                    this.src = "images/details_close.png";
                    oTable.fnOpen( nTr, fnFormatDetails(oTable, nTr), 'details' );
                }
            } );

Update
I tried using this but now my img won’t change. How would I select the img to use (this) or do I just make a var for it?

$('#example tbody td').on('click', function (e) {
        var myImage = $(this).find("img");
        var nTr = $(this).parents('tr')[0];
        if ( oTable.fnIsOpen(nTr) )
        {
        /* This row is already open - close it */
        myImage.src = "images/details_open.png";
        oTable.fnClose( nTr );
        }
        else
        {
        /* Open this row */
        myImage.src = "images/details_close.png";
        oTable.fnOpen( nTr, fnFormatDetails(oTable, nTr), 'details' );
        }
    } );

Answer by Mohammed ElSayed

first: it’s now better to use delegate() or on() instead of live(), which is now deprecated by the way.

second: just add a handler for the td, and by nature, it will get the same click event that will occur on your img, then you can eaisly select the img and play with it like nomral, consider the following example which is using the better way of on()

Update: I’ve modified the code a little bit to make it better

    $('#example tbody').on('click', 'td', function (e) {
        var myImage = $(this).find("img");
        var nTr = this.closest('tr');
                if ( oTable.fnIsOpen(nTr) )
                {
                    /* This row is already open - close it */
                    myImage.src = "images/details_open.png";
                    oTable.fnClose( nTr );
                }
                else
                {
                    /* Open this row */
                    myImage.src = "images/details_close.png";
                    oTable.fnOpen( nTr, fnFormatDetails(oTable, nTr), 'details' );
                }
}

you should now be ok with this solution, let me know if you need further help.

Answer by Starx

Pretty Simple

Select td instead of img

 $('#example tbody td').on('click', function () {

P.S: Of course the live function has been deprecated so its better to use .on()

Read more

PHP IF with multiple days of the week

Question by mrlayance

Is this possible?

$d=date("D");
...
else if ($d=='(Thu|Fri|Sat)') {

I can get a single day of the week working.

if ($d=='Wed') {

Thanks

Answer by Clamidity

You could use the OR operator:

else if ($d=='Thu' || $d=='Fri' || $d=='Sat') {

Answer by Starx

Why can’t you use or or ||?

else if ($d=='Thu' || $d=='Fri' || $d=='Sat') {

If you dont want to stick to simplicity then use preg_replace()[docs]

preg_match('^(Thu|Fri|Sat)$', $yourtext, $matches, PREG_OFFSET_CAPTURE);
if(count($matches)) {
    /// found
}
Read more

Convert dot syntax like "this.that.other" to multi-dimensional array in PHP

Question by Bryan Potts

Just as the title implies, I am trying to create a parser and trying to find the optimal solution to convert something from dot namespace into a multidimensional array such that

s1.t1.column.1 = size:33%

would be the same as

$source['s1']['t1']['column']['1'] = 'size:33%';

Answer by Starx

Although pasrse_ini_file() can also bring out multidimensional array, I will present a different solution. Zend_Config_Ini()

$conf = new Zend_COnfig_Ini("path/to/file.ini");
echo $conf -> one -> two -> three; // This is how easy it is to do so
//prints one.two.three
Read more
March 9, 2012

Hide the upload submit button if field "file" is empty

Question by Warface

With this simple example

<form action="" method="post" enctype="multipart/form-data">
            Upload images: <input type="file" name="images[]" multiple="multiple"> <input type="submit" name="submitImgs" value="Upload"/>
        </form>

How can I hide the submit button until somthing’s in the file field, I’ve tried to make a php script that look if the $_FILES[‘error’] == 4 or is_file_uploaded, etc and that don’t work. So I want to simply hide the button until something is selected in the file field.

The answer could be in javascript, jQuery… I don’t care 😀

Thanks

Answer by Rob W

The <input type="file"> element has a files property.

Simply check files.length.

jQuery example, which modifies the submit button on the fly:

// Select the <input type="file"> element
$('input[type=file][name="images[]"]').change(function(){
    var hasNoFiles = this.files.length == 0;
    $(this).closest('form') /* Select the form element */
       .find('input[type=submit]') /* Get the submit button */
       .prop('disabled', hasNoFiles); /* Disable the button. */
});

Answer by Starx

Use this. Attach the code on the change event of the file field.

  $(function() {
     $("input:file").change(function() {
       var fileName = $(this).val();
       if(filename != "") { $("#submitButtonId").show(); } //show the button
     });
  });
Read more

Textarea not showing hebrew text from mysql

Question by Prateek

I’m trying to return some particular text from mysql into a textarea. Now this text returning from mysql has

    collation=utf8_unicode_ci 

and the charset is set by adding this line in my php file.

   <meta http-equiv="Content-Type" content="text/html;charset=iso-8859-8-i" />

Cant figure out the problem here. Everything looks alright but why is the textarea not showing hebrew text? Instead it shows “???????” – Question marks.

Thanks.

Answer by Starx

During the data entry, or retrieval, the MySQL must be configured to accept unicode(UTF-8) data. There are number of ways, you can do this

  1. Place this line on the database connection part

    mysql_set_charset('utf8',$link); //$link is your connection identifier
    
  2. Run charset utf8 on CLI

  3. Use SET NAMES 'utf8' as your first query to the database

Moreover, while outputting such data the screen, the html should be configured to understand unicode characters as well. Use

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

At the top of the displaying page.

Read more

How to use a variable in a namespace?

Question by Chris

I’m trying to dig up my long-lost PHP skills and have therefore stumbled on a problem. I have a function that initializes (not sure if it’s a correct word for it) a class in the following fashion:

$foo = new MasterSlave$bar();

$bar is a defined class, obviously. But the entire thing doesn’t work. This only seems to work when I do the following:

$foo = new $bar();

But with my first example, it outputs the following error:

unexpected T_VARIABLE, expecting T_STRING

Which means that I have to manually enter the class name, correct? But, what if I’m a stubborn nerd who doesn’t want to and doesn’t see the efficiency in it? Hence my question; how to pull this off without getting a bloody error?

UPDATE: Got the thing working with wrapping the MasterSlave$bar in a $variable. Not sure if it’s the correct way of doing this, but it works and props go to Visual Idiot

Answer by Peter Kiss

Variables never bound to any namespace they will be always in the global scope.

Answer by Starx

AFAIK, the namespacing does not work the way you are trying to.

This is how you should do it

namespace MasterSlave;
$bar = "theclassname";
class $bar() {
}

Docs

Read more

Why does this break in jQuery 1.7.x?

Question by qwertymk

The following code snipplet shows what my issue is:

var $div = $('<div>');

$('span').live('click', function() { this.innerHTML = 'changed'; });

$div.append(
    $('<span>span</span>').click()
);

$div.appendTo('body');
​

This works as expected in jQuery 1.6.x but not in 1.7.x

Why is it not working in 1.7.x? Is it a bug? Is there any way to get it to work in 1.7.x?

EDIT: .on doesn’t change anything!!

Answer by Pointy

The way that event handling works has changed in the 1.7 release. Before the <span> is added to the DOM, events triggered on it will not bubble up to the <body> as they once did (erroneously, in my opinion; the 1.7 behavior makes much more sense).

The triggering of the event on the <span> probably works, but because the event does not bubble to the <body> the actual handler that deals with your .live() setup cannot be called.

edit — it may be the document element to which events bubble; whatever, the point is the same.

edit again — Here’s a way to make this work so that you can trigger handlers before adding your elements to the DOM:

$('<div></div>').on('click', 'span', function() {
    this.innerHTML = "Changed!";
}).append($('<span>span</span>'))
  .find('span').click().end()
  .appendTo($('body'));

That sets up the “click” handler as a delegated handler on the nascent <div> directly. Then, after appending the new <span> to that element, it’s then possible to trigger a “click” on that <span> and have the handler be called. That happens before the whole thing is appended to the <body>.

Answer by Starx

The working solution for both 1.6 and 1.7

var $div = $('<div>');
$('span').live('click', function() { this.innerHTML = 'changed'; });
$div.append('<span>span</span>');
$div.appendTo('body');
$('span').trigger('click');

Demo


However, omit the risk of using a deprecated function with replacing live with on

$('span').on('click', function() { this.innerHTML = 'changed'; });
Read more

Instantiate an variable with a methods return object

Question by Eirc man

I have been searching for hours but I can’t seem to understand why this does not work. Here is the code

My goal is to have a different method to load the XML document, and another one to print and manage that document.

class ...

//Fetch and print xml document
    function fetchFromXMLDocument($XMLDocName) {
        $xmlDoc = new DOMDocument();
        $xmlDoc->load($XMLDocName);
        return $xmlDoc;

    }

Here I want do add the value of the fetchFromXMLDocument() to my $he variable.
but it does not seem to be working?

function printXml($XMLDocName) {
   //this seems not to be right??       
    $he = fetchFromXMLDocument($XMLDocName);

    //after that this is what I want to do..
    // $items = $he->getElementsByTagName("item");
         ...
    }

Does anybody have an idea on why that might be?

Answer by Starx

The problem is that function fetchFromXMLDocument(); is inside a class.

If the method you are accessing it from printXML, is within the same class then you should access it using $this operator.

function printXml($XMLDocName) {    
     $he = $this -> fetchFromXMLDocument($XMLDocName);
     ...
}

However, If the method you are accessing it from printXML, is outside. Then first you have to create and object of the class and access it.

function printXml($XMLDocName) {    
     $obj = new yourxmlclassname();
     $he = $obj -> fetchFromXMLDocument($XMLDocName);
     ...
}
Read more

Using a string path to set nested array data

Question by Anthony

I have an unusual use-case I’m trying to code for. The goal is this: I want the customer to be able to provide a string, such as:

"cars.honda.civic = On"

Using this string, my code will set a value as follows:

$data['cars']['honda']['civic'] = 'On';

It’s easy enough to tokenize the customer input as such:

$token = explode("=",$input);
$value = trim($token[1]);
$path = trim($token[0]);
$exploded_path = explode(".",$path);

But now, how do I use $exploded path to set the array without doing something nasty like an eval?

Answer by alexisdm

Use the reference operator to get the successive existing arrays:

$temp = &$data;
foreach($exploded as $key) {
    $temp = &$temp[$key];
}
$temp = $value;
unset($temp);

Answer by Starx

Can’t you just do this

$exp = explode(".",$path);
$array[$exp[0]][$exp[1]][$exp[2]] = $value
Read more
...

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