...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
February 26, 2013

empty() then run the rest of the funtion

Question by ndesign11

I have some json that’s loaded into li.ui-state-default pending user entry.

The user can then enter a new entry. I want it to empty li.ui-state-default everytime a new entry is loaded but it seems to just stay empty.

//data for DOM
var timeout = '';
$('.call-json').keyup(function () {
    clearTimeout(timeout);
    var val = this.value;
    timeout = setTimeout(function () {
        $('.ui-state-default').empty();
        $.getJSON('json/' + val + '.json', function (data) {
            // load data

            var items = [];
            for (key in data[0].attributes) {
                if (key.match('.stat.prop.type')) {
                    items.push(data[0].attributes[key])
                }
            };

            displaySortLabel(items, "type-details");

        function displaySortLabel(items, parentClass) {
                $('<span/>', {
                    'class': 'el-data',
                    html: items.join('')
                }).hide().fadeIn().appendTo('.' + parentClass + ' .sort-label');
            }

Answer by Starx

$('li.ui-state-default').html(''); //empty it like this
Read more

Add click event to iframe

Question by user1170330

I want to add a click event to an iframe. I used this example and got this:

$(document).ready(function () {
   $('#left').bind('click', function(event) { alert('test'); });
});

<iframe src="left.html" id="left">
</iframe>

But unfortunately nothing happens.
When I test it with another element (e.g. a button), it works:

<input type="button" id="left" value="test">

Answer by Starx

The actual problem is that, the click event does not bind to the DOM of the iframe and bind() is deprecated, use .on() to bind the event. Try with the following codes and you will find the borders of the iframe clickable getting that alert.

$('#left').on('click', function(event) { alert('test'); });

Demo of that Issue

So how to get it done?

How you should do is, create a function on iframe page, and call that function from that iframe page.

Read more
February 25, 2013

Animated bars at scroll position

Question by user1375823

I created some animated bars with jquery. I’m only really just learning jQuery & javascript. It was working last night, the bars animated when at a certain scroll position but now it doesn’t work, nothing has been changed. Anyone help me out? Or is there a better way to do it than what I’m doing?

http://jsfiddle.net/FkUYf/1/

$(document).ready(function(){
    $(document).scroll(function() {
        var top = $(document).scrollTop();
        console.log(top);
        if (top > 930) $("#html, #css").animate({width:"100%"}, 2000);
        if (top > 930) $("#javascript").animate({width:"70%"}, 2000);
        if (top > 930) $("#php").animate({width:"50%"}, 2000);
        if (top > 930) $("#mysql").animate({width:"30%"}, 2000);
        if (top > 930) $("#wordpress").animate({width:"60%"}, 2000);
    });
});

Answer by Starx

You dont seem to hit that 930 margin. Its working fine with 330 margin.

http://jsfiddle.net/FkUYf/2/

Read more

Why am I encouraged to download Jquery?

Question by user2087941

I am following various tutorials to learn jquery, and they reference downloading jquery.
But why? do I not just declare it as a script src= etc. in the my html ?
I don’t see what else I would need beyond that and the .js files to go with my html and css.

-ALSO- what is your favourite jquery tutorial resource? books or websites, anything. Thanks

Answer by Starx

For one reason, to run the scripts without needing to be connected on the internet.

Read more

jQuery: Count images

Question by Jones-Rocks

I have a folder with images named example_**_title.jpg.

I want to count these images with jQuery/Javascript and return the number of images.

I tried:

count = 0;
for (var i=0; i<=10; i++){
   var bg_url = 'http://www.example-url.com/example_'+i+'_title.jpg';
   $.get(bg_url)
   .done(function(){ 
      count++;
   })
   .fail(function(){
   });
}
alert(count);

Thanks for the help.

Jones

Answer by Michael Laffargue

Since you don’t want to get the files but just count, you can use type:'HEAD' It should reduce the amount of data :

$.ajax({
    url:'http://www.example-url.com/example_'+i+'_title.jpg',
    type:'HEAD',
    error: function()
    { 
      //file doesn't exist
    },
    success: function()
    {
        count++;
    }
});

Answer by Starx

Your code should work, this is a quote missing on your code. I hope that is just a typo.

count = 0;
for (var i=0; i<=10; i++){
   var bg_url = 'http://www.example-url.com/example_'+i+'_title.jpg';
   $.get(bg_url, function(data){ count++; });
}
alert(count);
Read more

PHP PDO data into Json_Encode + but only first line appears

Question by Adam

                       $sql='SELECT word,language,acceptable FROM profanity;';
                       $pds=$database_miscellaneous->pdo->prepare($sql); 
                       $pds->execute(); 
                       //$row=$pds->fetch();
        foreach($pds as $row) {
            $profanityText = json_encode(array('word' => $row['word'],
                                       'language' => $row['language'],
                                       'acceptable' => $row['acceptable']));
        }

I have the above code. The catch is it works but only the first line from the database goes into the json array. I’ve run the query directly against the DB and it pulls all the data.

I’m guessing my foreach loop has an issue or many the way I’m doing the PDO call.

any ideas?

Answer by Starx

The problem is that the variable holding the json encoded values $profanityText gets overidden every time in the loop.

Use this

    $rows = array()
    foreach($pds as $row) {

        $rows[] = array('word' => $row['word'],
            'language' => $row['language'],
            'acceptable' => $row['acceptable']);
    }
    $profanityText = json_encode($rows);

Or, if you are not manipulating your data in anyway, you can just directly call (as mentioned by deceze)

$profanityTest = json_encode($pds->fetchAll(PDO::FETCH_ASSOC));
Read more

how to show calendar on text box click in html

Question by Vinoth

In html i want to show calendar to select date while clicking a text box.
then we select a date from that calendar then the selected date will be display in that text box.

Answer by Starx

jQuery Mobile has a datepicker too. Source

Just include the following files,

  <script src="jQuery.ui.datepicker.js"></script>
  <script src="jquery.ui.datepicker.mobile.js"></script>
Read more

get all weekdays in php

Question by Keydi

I am thingking if how to get all the date of weekdays between a given date

example: I have a date given 2013-01-01 and 2013-20-01

It must return all date of weekdays like 2013-01-01

how could this be done using php
thankz

Answer by Starx

Look into DatePeriod Class, this is available from PHP 5.3.

Here is an example from the site

$begin = new DateTime( '2012-08-01' );
$end = new DateTime( '2012-08-31' );
$end = $end->modify( '+1 day' );

$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);

foreach($daterange as $date){

       // You can manipulate the date here
    echo $date->format("Ymd") . "<br>";
}
Read more

Sql Error – Incorrect integer value

Question by Babu Ahmed

I’m getting following error when I submit a form:

Can't added a new post. Incorrect integer value: '' for column 'aid' at row 1

Php Code:

$insert = mysql_query("INSERT INTO brt_articles VALUES( '', '$post_title', '$des', 
'$date', '$org_date')");    

    if($insert)
    {
        echo "<font color=green>Successfully added a new article.</font>";
        header("Refresh:3; url=allbrtarticle.php");
    }
    else
    {
        echo "<font color=red>Can't added a new post</font>" . 
              mysql_error();
    }

In my Localhost It’s ok. But in server why it’s giving me a error message ?

Answer by Starx

The aid field does not accept '' value as input.

The safest way is to specify column names as you are sending the query.

INSERT INTO brt_articles (title_field, description_field, date_field, org_date, fieldname) VALUES('$post_title', '$des', '$date', '$org_date');

If aid is a primary key, simply omit that field in your query

INSERT INTO brt_articles VALUES('$post_title', '$des', '$date', '$org_date')
Read more

simple alert box doesn't close after the first click, what to do to make it work?

Question by sasori

i have a simple jquery script that calls a fancybox after a button was clicked,
now the problem is, the fancy box doesn’t close after the first click of the button, only after the 2nd click…

The second problem is, inside the fancy box, there is a form with 3 input fields, the submit button/button doesn’t work in one click, it needs to get clicked twice as well..any ideas on what to do?

jQuery("#hsbcloanbutton").click(function(e){

    e.preventDefault();
    var loanAmount = jQuery('#loanAmount').val();
    var loanTenure = jQuery('#loanTenure').val();
    var InstalmentAmount = jQuery('#InstalmentAmount').val();
    var loanName = jQuery('#loanName').val();
    var loanNric = jQuery('#loanNric').val();
    var loanContact = jQuery('#loanContact').val();
    if(loanAmount.length < 1 || loanTenure.length  < 1 || InstalmentAmount.length < 1)
    {
        alert("Please enter data");
        return false;
    } else if(isNaN(loanAmount) || isNaN(InstalmentAmount)){
        alert("Please put numbers only in Loan Amount and Instalment Amount fields");
        return false;
    } else {
                jQuery("#hsbcloanbutton").fancybox({
                'titlePosition' : 'inside',
                'transitionIn' : 'none',
                'transitionOut' : 'none',
                'hideOnOverlayClick' : false,
                'hideOnContentClick' : false,
                'showCloseButton' : false,
        });


    }
    jQuery("#hsbcloansubmitformbutton").click(function(e){
        e.preventDefault();
        jQuery.ajax({
            'type' : 'POST',
            'url' : "<?php echo Yii::app()->createUrl?>",   
        )};
    });
});

Answer by Starx

It seems you are initializing your fancybox, on the click event: That might be causing this.

Initialize the script on $(document).ready()

$(function() {
        jQuery("#hsbcloanbutton").fancybox({
                'titlePosition' : 'inside',
                'transitionIn' : 'none',
                'transitionOut' : 'none',
                'hideOnOverlayClick' : false,
                'hideOnContentClick' : false,
                'showCloseButton' : false,
        });
});
Read more
...

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