...

Hi! I’m Starx

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

Reset angle of text in skewed div using CSS

Question by benhowdle89

I have made a fiddle:

http://jsfiddle.net/89x4d/

I’m trying to maintain the skewed div but keep the p text straight.

Is this possible?

Thanks

Answer by Alexander Pavlov

You should use 20deg instead of 0deg on P to compensate for the DIV transform (since the result is the composition of transforms.)

Answer by Starx

In order to cancel the effect of the skew, you have to give positive value of transformation.

p {
   -webkit-transform: skew(20deg) !important;
   -moz-transform: skew(20deg) !important;
   -o-transform: skew(20deg) !important;
   transform: skew(20deg) !important;
}

Demo

Read more

Is there something wrong with my json structure?

Question by amiawizard

I’ll have my PHP like so:

array(2) {
  [0]=>
  object(stdClass)#20 (1) {
    ["name"]=>
    string(5) "Indie"
  }
  [1]=>
  object(stdClass)#21 (1) {
    ["name"]=>
    string(12) "Cult-classic"
  }
}

Then json_encode it which results in this:

0: {name:Indie}
name: "Indie"
1: {name:Cult-classic}
name: "Cult-classic"

So why is this getting undefined (it’s actually just traversing every character treating the structure as a string.

for(var i = 0; i < tagged.length; i++) {
    alert(tagged[i].name);
}

Update:

$.post('/host/tags/item_tags/' + movieId,
    function(tagged) {
        alert(tagged);
        for(var i = 0; i < tagged.length; i++) {
            alert(tagged[i]);
        }
});

Answer by Brad

Somehow, I doubt json_encode() is giving you that kind of broken output. This is the appropriate output:

[
    {"name":"Indie"},
    {"name":"Cult-classic"}
]

So to answer your question, yes, there is something wrong with your output. You can validate your JSON at: http://jsonformatter.curiousconcept.com/

Answer by Starx

Tranverse along the json data with .each() instead

function(tagged) {        
    $.each(tagged, function(k,v) {
       alert(v);
    });
}
Read more

join method is not working in jquery

Question by prerna

JSFiddle

$(".commentbox").on("click",".btnSave",function(){


         var id = $(this).attr("id").split("-");
            alert(id);
            id.shift();
            alert(id);
            var newString = id.join('-');
            alert(newString);


   });       
});​

Input is btnSave-88eC4B8D2-8F96-4EB5-B42E-08C540D7F171

Output :88eC4B8D2,8F96-4EB5,B42E,08C540D7F171

Whereas it works fine for btnReply button Why
Please help me out

Answer by naveen

Is this a trick question ? 🙂


The problem is with this line of code

<input type='button' class='btnSave' value='Save' id='btnSave-" + id + "' /> "

Here id passed is actually id="btnSave-88C4B8D2,8F96,4EB5,B42E,08C540D7F171" because id is an array and that array got converted to a comma separated string because you set it as string attribute. Now you call split(-) on that string which gives you “btnSave” and “88C4B8D2,8F96,4EB5,B42E,08C540D7F171”. Now you shift and remove the btnSave leaving the single member “88C4B8D2,8F96,4EB5,B42E,08C540D7F171” and then you call join(“-“) on that single string which doesn’t change a thing at all. So, all you have to do is change the above shown like like this

<input type='button' class='btnSave' value='Save' id='btnSave-" + newString + "' /> "

Fiddle here: http://jsfiddle.net/naveen/XHr6e/

Answer by Starx

One of the weird issues I have encountered, but escaping the - fixes the problem.

var newString = id.join('-');

Usage: Demo

$(".commentbox").on("click",".btnSave",function(){
        var id = $(this).attr("id").split("-");
        id.shift();
        var newString = id.join('-');
        alert(newString);
   });       
});​
Read more

Execution of dynamically loaded JS files

Question by shaunshd

I understand that JS is single threaded and synchronously executed. Therefore when i add a file to my browser head tag that file is executed as soon as its encountered. Then it goes to the next script tag & executes that file. My question is when I add a js file dynamically to an HTML head tag. How does the browser executes that file?
Is it like that the file is executed as soon as the file is loaded wherever the current execution is. Or is it that we can control how that file is executed?

Answer by AHM

When the script is loaded, it will be executed as soon as possible. That is, if some other javascript function is executing, like a clickhandler or whatever, that will be allowed to finish first – but this is a given because, as you say, in browsers JavaScript normally execute in a single thread.

You can’t control that part of the script loading, but you could use this pattern – heavily inspired by JSONP:

inserted script:

(function () {
    var module = {
        init: function () {
            /* ... */
        }
    }

    ready(module);  // hook into "parent script"
}());

script on main page:

function ready(o) {
    // call init in loaded whenever you are ready for it...
    setTimeout(function () { o.init(); }, 1000);
}

The key here is the ready function that is defined on your page, and called from the script you insert dynmaically. Instead of immediately starting to act, the script will only tell the parent page that it is loaded, and the parent page can then call back to the inserted scripts init function whenever it wants execution to start.

Answer by Starx

Considering a way to do this is

var js=document.createElement('script')
js.setAttribute("type","text/javascript")
js.setAttribute("src", filename)
document.getElementsByTagName("head")[0].appendChild(js); 
// ^ However this technique has been pointed to be not so trusworthy (Read the link in the comment by Pomeh)

But answering your question

How does the browser executes that file?

As soon as the script is added to the DOM

Is it like that the file is executed as soon as the file is loaded wherever the current execution is?

Yes

Or is it that we can control how that file is executed?

Its better if you attach an onload event handler, rather than a nasty tricks.

Read more

What is wrong with these PHP scripts in reading JSON?

Question by Newbie

This is the code that I wrote:

$result = $textProc->sentiment($text);
$json_a = json_decode($result, true);
echo $json_a[label];

where $result stores the JSON data.

However, it returns me error:

Warning: json_decode() expects parameter 1 to be string, object given in C:xampp
htdocsaisentiment.php on line 9

Notice: Use of undefined constant label - assumed 'label' in C:xampphtdocs
aisentiment.php on line 11

Solution:
This is the output of var_dump($result):

object(stdClass)#2 (2) { ["value"]=> float(0.63882080795918) ["sent"]=> int(1) } 

Sorry, I should have checked this first.

Answer by Starx

Notice: Use of undefined constant label – assumed ‘label’ in
C:xampphtdocs aisentiment.php on line 11

On echo $json_a[label]; label refers to a constant which is not present.

To refer to an element in a associative array, you have do it as following.

echo $json_a['label'];

Warning: json_decode() expects parameter 1 to be string, object given
in C:xampp htdocsaisentiment.php on line 9

Next, on $result = $textProc->sentiment($text);, The function is not returning a string. Do a var_dump($result) to ensure, it is returning json string format.

Read more

innerHTML wont change if a changebox changes

Question by John Smith

I have a basic list:

<select id = "opt">
  <option value="a">a</option>
  <option value="b">b</option>
  <option value="c">c</option>
</select>

Now I must change the selected items in JS. Its done, and then I need the content of this select items (.innerHTML).
But sadly, the innerHTML say nothing is selected… how to fix this?

EDIT: here is the code:

for (var count = 0; count < document.getElementById('opt').childNodes[0].options.length; count++)
{
 if (document.getElementById('opt').childNodes[0].options[count].value == 7) { document.getElementById('opt').childNodes[0].options[count].selected = true; break; }
}
var obj = document.getElementById('opt');
alert (obj.innerHTML);

and that alert() just displays the original HTML code

Answer by Starx

You can do this as such

var opt = document.getElementById("opt");
var listLength = opt.options.length;
for(var i =0; i< listLength; i++) {
   if(opt.options[i].selected) {
      opt.options[i].textContent = 'the change HTML';
   }
}

Demo

Read more

Is it possible to using or in codeigniter form validation?

Question by motto

I have an input which can be decimal or numeric. I want to use this rule:

$this->form_validation->set_rules('price', 'Price', 'decimal|numeric');

But i think the rules in form_validation helper not working with “or” statement. If the price is something like that “149.99” it’s valid but if the price is “150” it’s not.

Am i missing something or isn’t it possible to use something like that:

 $this->form_validation->set_rules('price', 'Price', 'decimal or numeric');

Answer by Starx

CI, does not allow to mix datatypes when validating. Instead, Create your custom validation rule.

Declare a rule like this

$this->form_validation->set_rules('price', 'Price', 'callback_decimal_numeric');

After create a method on the controller

    public function decimal_numeric($str)
    {
        if ($str <isdecimal&nummeric>) //Use your logic to check here
        {
            $this->form_validation->set_message('decimal_numeric', 'The %s field validation has failed');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }
Read more

Mysql alter statement

Question by Eagletrophy

this is my alter statement trying to connect two tables:

ALTER TABLE my_contacts 
  CHANGE `profession` `profession_id`  INT NOT NULL, 
  ADD CONSTRAINT professions_profession_id_fk 
  FOREIGN KEY (profession_id) REFERENCES professions (profession_id)

and I have the following error:

#1452 - Cannot add or update a child row: a foreign key constraint fails (`contacts`.<result 2 when explaining filename '#sql-1ca_73'>, CONSTRAINT `professions_profession_id_fk` FOREIGN KEY (`profession_id`) REFERENCES `professions` (`profession_id`))

can anyone guide me on what this is? I am actually learning how to write sql myself since I have used tools all this while.

Answer by verhage

Your foreign key constraint is failing.

The foreign key you are trying to create enforces every profession_id in my_contacts to be present in your professions table. Right now, this is not the case. You should lookup all records in my_contacts where the profession_id is not present in professions and fix those first.

Answer by Starx

This is a relationship conflict. An easier to solve this is

  • Remove the relationship between the fields
  • Alter the tables
  • While adding the relationship again, fix the errors you receive.
Read more

unable to create multiple div inside div dynamically

Question by prerna

$.post("../../Handler/Topic.ashx", 
       { commentclob: commentClob, 
         commenttitle: commentTitle,
         topicId: id, 
         Button: buttoname },
       function (data) {
         obj = jQuery.parseJSON(data);
         var $table = $('<table/>').addClass('commentbox');

         $table.append('<tr><td>' + 
                       'Comment Id:' + 
                       obj.CommentId + 
                       '</td></tr>');

        var includeReply = "<input type='button' 
                                   class='btnReply' 
                                   value='Reply' 
                                   id='btnReply-" + obj.CommentId + "' />";


        $("#commentContainer").prepend(
          $('<div/>').attr('id', '#comment-' + obj.CommentId)
                     .append($table)
        );

        //This doesnt work         
        $("#comment-" + obj.CommentId).append(
          $('<div/>').attr('id', '#container-' + obj.CommentId)      
                     .append(includeReply)
        );
});

html

  <div id="commentContainer"></div>

I am successfully able to append div with #comment-id to comment-container but I am unable to append another div inside #comment-id.

I have tried

               var str = $("<div>").attr("id", "#container-" + obj.CommentId)
               $(str).append(includeReply);
               $table.append('<tr><td>' + 'CommentDiv:' + str + '</td></tr>');

But it gives

CommentDiv:[object object]

Answer by Starx

str is an HTML object so it can concatenated like that. You have to extract the markup with .html() and then concatenate it.

   var str = $("<div>").attr("id", "#container-" + obj.CommentId)
   $(str).append(includeReply);
   $table.append('<tr><td>' + 'CommentDiv:' + str.html() + '</td></tr>');
Read more

can an child class access parent class property data?

Question by Eli

I have a child class extending a parent class.

In my parent class have a protected property that stores config data. In the parent class this property has all the configuration files needed.

But in the child class I cannot access that data. How can I bring over the config property data into the child class?

I am using

class Child extends Parent
{
    public function __construct()
    {
        print_r($this->config);
    }
}

but i get an empty response.

Answer by Starx

Unless the resource is Private you can

There are basically to ways to access the parent resource:

  1. parent::{resource identifier}; eg. parent::config;
  2. $this -> {resource identifier}; Unless the resource is overridden

Now, coming to the part, of which might cause this issue.

The parent constructor might need to run, in order to store the configuration. SO,

class Child extends Parent
{
    public function __construct()
    {
        parent::__construct();
        print_r($this->config);
    }
}
Read more
...

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