...

Hi! I’m Starx

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

In CSS, When I scroll the scroll bar, the background-color of <li> disappeared

Question by UniMouS

HTML code like this:

<div>
    <ol>
        <li class='a'>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</li>
        <li class='b'>bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb</li>
    </ol>
</div>

CSS code like this:

div {
    width: 400px;
    overflow-x: scroll
}

.a {
    background-color: red;
}

.b {
    background-color: blue;
}

When I scroll the scroll bar, I see that the background color is only applied to the original unscrolled region. How can I solve this problem.

My Code is Here


EDIT

Another example showing my problem clearly.

I have a second problem now: the second line disappeared…why

Answer by James Johnson

For the list items you need to set the display property to inline-block and set the min-width property to 100%. Here’s your jsFiddle, and see below:

div {
    width: 400px;
    overflow-x: scroll;   
}

li {
    min-width: 100%;
    white-space: nowrap;
    display: table-row; /* or inline-block */   
}

.a, .c, .e, .g {
    background-color: red;
}

.b, .d, .f {
    background-color: blue;
}​

EDIT

To make all of the li elements the width of the longest li, use display: table-row.

See this jsFiddle for a demonstration.

li {
    min-width: 100%;
    white-space: nowrap;
    display: table-row;    
}

Answer by Starx

You can overcome this problem by defining your lists as inline

li { display: inline; }

Demo

Read more

replace innerhtml along with events

Question by user1032531

I would like to replace the innerhtml of thisOne with that of either clone1 or clone2.

I have figured out how to replace the entire thisOne element with that of the clone, but would rather not do it that way as I store data in the li element.

I also have figured out how to put a separate div tag around the clones innerhtml, clone(true) that redundant tag element, and append the redundant tag and its innerhtml into thisOne, but these seems like a waste of a tag.

I also find that html() doesn’t bring over the events, and would rather not re-declare them each time I swap the html.

Any suggestions? Thank you

<ul>
<li id="thisOne" data-attr="whatever"></li>
</ul>

<ul style="display: none">
<li id="clone1">
<a href="#" class="doSomething1">Click</a>
<button class="doSomething3">Click</button>
</li>
<li id="clone2">
<a href="#" class="doSomething2">Click</a>
<button class="doSomething4">Click</button>
</li>
</ul>

....

$("clone1 a").click(function(){alert("hi");});

The following new code added doesn’t appear to work.

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Dialogs</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js" language="javascript"></script>
<script type="text/javascript">
$(document).ready(function(){    
    $("#cloneIt").click(function(){$('#newLocation').html($('#clone').html());});
    $("#clone a").on("click", function(){alert("click");});
    $("#clone select").on("change", function(){alert("change");});

});
</script>

</head>
<body>
<input type="button" value="Clone it" id="cloneIt" />

<div id="newLocation"></div>

<div id="clone" style="display: none">
<a href="#">Click Me</a>
<select><option>Hello</option><option>Goodby</option></select>
</div>

</body>
</html>

Answer by ocanal

you can iterate children, than append cloned each one to thisOne

   $("#clone1, #clone2").each(function() {
        $(this).children().each(function() {
                $("#thisOne").append($(this).clone(true));
        });
    });

Answer by Starx

You have to delegate the event so that it waits future occurrences of the selector as well.

It very easy like this

$("#clone1 a").on("click", function(){alert("hi");});
Read more

PHP, MYSQL – Query fails but no error meessage appears

Question by S.e. Estes

Back again, thanks for all the help last time. I’m running this query:

 $query = "SELECT * FROM event where evLoc = ".$loc." AND evChar = ".$char;
 var_dump($query);
 $result = mysql_query($query, $con) or die('Error 1:'.mysql_error());
 if ($result) {
    $row = mysql_fetch_array($result) or die('Error 2:'.mysql_error());
    var_dump(mysql_num_rows($result));
    exit();

I get a message Error 2: but no mysql_error printed out. The var_dump($query) printed out a query that ran without errors in phpMyAdmin. The var_dump(mysql_num_rows($result)) did not print. Ideas?

Answer by Michael Berkowski

This is a case of being too cautious and applying error checking where it doesn’t belong.

Don’t call die() in partnership with a fetch call. The fetch intentionally returns FALSE when there are no rows available, so you don’t have an error, just no rows.

// No rows were returned, wich is FALSE
$row = mysql_fetch_array($result) or die('Error 2:'.mysql_error());

Instead, don’t call die() here:

$row = mysql_fetch_array($result);
if ($row) {
  // you got something
}

Or this way:

if ($row = mysql_fetch_array($result)) {
  // you got something.
}

If multiple rows are expected to be returned, fetch in a while loop.

while ($row = mysql_fetch_array($result)) {
  // loops until you're out of rows
  // or not at all if you have no rows
}

Answer by Starx

Apply Single Quotes in the fields of your query

 $query = "SELECT * FROM event where evLoc = '".$loc."' AND evChar = '".$char."'";

You can write these in short form too. Like

$query = "SELECT * FROM event where evLoc = '$loc' AND evChar = '$char'";

Next, you might want to change your fetch portion.

while($row = mysql_fetch_assoc($result)) { 
 ....
}

When you use this, you will avoid the error you would receive when no rows are returned.

Read more
April 11, 2012

Is there any research/data that shows DIV (with CSS) is faster than TABLE?

Question by deathlock

I’ve seen that similar questions have been asked before, such as: For tabular data, what renders faster, CSS or <TABLE>? or Why not use tables for layout in HTML?

However, besides being a rather old questions (2-4 years ago), I am wondering if there is actually a research/a data which proves with number that (with CSS) renders faster than for displaying tabular data.

I’m not trying to be offensive/disregarding the notion that DIV + CSS is faster (or table is more appropriate), I’m only wanting to know for practical purposes.

I also am not intending this to be a discussion/debate. A link to numbers is what I was expecting.

.

Like previous questions, I’m also aware that to display tabular data it is better to use table. But I just want to know which one is actually, statistically, faster.

Pardon my English, not a native speaker. Sorry if there is any offense taken.

Answer by Starx

Update:

The Discussion about Tables Or Divs have been long fought and left unsettled. As mentioned in your question yourself, the table is more logical when used to show tabular data.

Apart from this as we are moving on to HTML5, the elements are more logical then just styling components. Lets divs divide a portion and Let table display data.


Answering the Misleading Title

CSS is a stylesheet and Table is Element. The comparison between these two are obsolete.###

Read this article. This approaches different then articles normally do.

Read more

Have days display with commas except for the last one

Question by Nina

I have the following if statements that gather up all the days that were selected before it becomes displayed.

$daysUsed = "";

if($this->dayweeksunsession==1){
    $daysUsed .= "Su ";
}

if($this->dayweekmonsession==1){
    $daysUsed .=  "M ";
}

if($this->dayweektuessession==1){
    $daysUsed .=  "T ";
}

if($this->dayweekwedsession==1){
    $daysUsed .=  "W ";
}

if($this->dayweekthurssession==1){
    $daysUsed .=  "Th ";
}

if($this->dayweekfrisession==1){
    $daysUsed .=  "F ";
}

if($this->dayweeksatsession==1){
    $daysUsed .=  "Sa ";
}

if($daysUsed !=="") {
    echo "</span><br/>Days of the Week: <span class='BoxReviewOutput'>";
    echo $daysUsed;
}

My question here is how can I make this so that commas will be displayed for each day of the week that was chosen in the session except for the last one.

For example: Sunday and Tuesday were chosen. So it would be displayed “Su, T”

Thanks in advance!

Answer by Josh

In your ifs add a commma:

$daysUsed = "Whatever, ";

Then before you output the final string:

$daysUsed = substr($daysUsed, 0, -2);

EDIT: -1 needs to be -2, to account for the spacing between days.

Answer by Starx

Use implode()

$days = array("Su", "M", ....., "Sa");
echo implode(",", $days);
Read more

mysql database insert is changing all IDs to 4294967295

Question by three3

Something really weird is going on with my database. I am using PHP to insert data into my database and I have been doing this for the past 2 years without any problems. When a customer makes a payment on my website, I store all of the data from that transaction in my database. Each transaction has a unique “transaction_id”. When I insert the payment information into the database, all of the information is correctly inserted except for the “transaction_id”. ALL transactions are given the “transaction_id” of “4294967295”. So I did some testing. Here is what I did:

1) I echoed out the “transaction_id” to my screen to see what is would say. The results were that the “transaction_id” that was being echoed out was CORRECT. It was not the repeating “4294967295”. However, when I look in my database, it shows “4294967295”.

2) This time I decided to echo out the query to my web browser. The query was CORRECT. In the query, the CORRECT “transaction_id” was in the query. However, when I look in my database, it shows “4294967295”.

I have 3 different pages where customers can make payments. ALL 3 pages started doing this on April 6th, 2012. None of those pages were modified at all. I have not modified those pages in over 2 years. Any help is greatly appreciated!

$query = "INSERT INTO payments (customer_id, transaction_id, invoice_number, authorization_code, subscription, subscription_id, avs_result, cvv_result, amount, full_tuition, payment_date, ip_address) VALUES ({$_SESSION['customer_id']}, {$_SESSION['transaction_id']}, {$_SESSION['invoice_number']}, '{$_SESSION['authorization_code']}', '{$_SESSION['subscription']}', {$_SESSION['subscription_id']}, '{$_SESSION['avs_result']}', '{$_SESSION['cvv_result']}', {$_SESSION['amount']}, {$_SESSION['full_tuition']}, '{$_SESSION['payment_date']}', '{$_SESSION['ip_address']}')" ;
$result = mysqli_query($dbc, $query) OR die ('<p>There was an error with the INSERT payments query.: ' . mysqli_error($dbc) . '<br />Query:' . $query . '</p>') ;

echo '<p>Transaction ' .  $_SESSION['transaction_id'] . ' has been <font color="green">APPROVED</font> by the system.</p>' ;

echo '<br /><br />' ;

echo '<p>Below is a summary:</p>' ;
echo '<p>Transaction ID: ' .  $_SESSION['transaction_id'] . '<br />
Payment Method: XXXX<br />
Amount: $' . $amount . '<br />
Customer Name: ' . $_SESSION['first_name'] . ' ' . $_SESSION['last_name'] . '<br />
</p>' ;

echo "<p>Note: Please do NOT click the browser's Back button to enter a new transaction.</p>" ;


echo $query ;

Answer by user282172

Your number is larger than the field in the DB can handle…

4294967295 is the largers number 32 bits can hold, your transaction ID is now larger than the numerical field your DB can hold.

Answer by Starx

Change the data type of the transaction_id to BIGINT

Read more

PHP & HTML Form with javascript onsubmit not executed

Question by Baba

I have a HTML form asking for user input. A javascript function is meant to validate the form and should be triggered (using onsubmit) BEFORE executing the PHP code. (The js file is referenced in the header <script type="text/javascript" src="js/javascript.js"></script>)

HOWEVER the javascript is never executed and instead the PHP code executes and (correctly) includes the new file.

How can i make the javascript execute as required?

HTML file:

<form name="details" action="" method="post" 
     onSubmit="return ValidateForm(details);">
...
<input type="submit" name="post-this-form" value="Next"/>
</form>

PHP file:

if (isset($_POST['post-this-form']) and 
     $_POST['post-this-form'] == 'Next')
{
...
some php 
...
include 'shipping-details.html.php';
exit();
}

EDIT

here is the javascript as requested. It has been tested and worked without any PHP involved. By passing details (the name of the form) i’m making all the form fields accessible.

function ValidateForm(details)
        {
        var firstName=document.forms.details.firstName.value;
        var lastName=document.forms.details.lastName.value;
        var streetAddress=document.forms.details.streetAddress.value;
        var town=document.forms.details.town.value;
        var city=document.forms.details.city.value;
        var zip=document.forms.details.zip.value;
        var country=document.forms.details.country.value;       
        var creditCard=document.forms.details.creditcard.value;                 

                ...

        //Checks firstName
        if ((firstName=="")||(!firstName.match(alphabetExpression)))
            {
            alert ("Invalid first name, please re-enter");
            return false;
            }
                 ...

        //Checks creditCard
        if ((creditCard=="")||(!creditCard.match(numericExpression))||(creditCardLength!=16))
            {
            alert ("Invalid credit card entry, please re-enter");
            return false;
            }       
        }// end function

EDIT 2

i added alert ("Hi"); to the start of the javascript and the alert never shows up which leads me to think that the function isn’t executed at all.

EDIT 3

My initial suspicion that this problem could be due to PHP was wrong. As Jason mentioned in his comments the problem was in the javascript itself. It is a bit strange thought because the same javascript code worked “on its own” without PHP and on my local machine. So many factors to consider…thanks All for taking the time to have a look at my problem!

Answer by Jason Fuller

Comment converted to answer

“I bet there is a javascript error. Open error console. ctrl+shift+j in firefox.”

Glad that helped.

Answer by Starx

Here are few things you must know the about the functions you are trying to build

function ValidateForm() {
     this; // this contains the form name no need for any variable declaration

     return true; // or false This is very important to continue the execution
                  // false stops the submittion
}

When you fix both of these issues, it should work as you want.

Read more

What is the optimal string format for converting to an array?

Question by amiawizard

I’m producing a string with GROUP_CONCAT in MySQL.

There are 2 columns I need to select for each row being id and name, how should I format the string in the query so I can produce an array that couples the ids and names in PHP at optimal speed?

For example (my attempt):
GROUP_CONCAT producing

{"id":1,"name":"python"},{"id":2,"name":"ruby"}

Then convert this to an array in PHP.

Answer by Starx

I dont know why you are attempting this. But this query should work

SELECT * FROM `yourtable` GROUP_CONCAT(
    CONCAT('{"id":"',id,'","name":"',name,'"}') 
    separator ',')
Read more

jquery: vertically expand div when using contained draggable

Question by monsto

I’ve got paragraphs of plain text with specific words hilited. the hilited words are meant to be draggable. when dragging is started, i want the div that hilites the word (#hilite) to expand top and bottom extents (vertically only), in a higher z-order, and allow the word (#word) to be dragged up and down in that space (container: parent). The plans is at some point have it dropped on a droppable within the area.

at this point, my problem is that i expand #hilite with padding… which increases the size of the div without increasing usable space. Would using Resizable be better? or Animate? I’ve seen a number of recommendations for using Resizable, but i thought it was for user resizing not programmatic.

for the droppables, i figure that once the space is created i’ll swap out .css(‘display’, ‘[none|block]’) to show them inside the #hilite div and make them valid targets.

http://jsfiddle.net/monsto/GCsnM/ for what i have atm.

(oh btw, i hate the people came up with jsfiddle. it’s simply too genius.)

Answer by Starx

Your container is a span, which is by default an inline element, it cannot show block properites. You have to tell it behave as block

#hilite { display: inline-block; }

Demo

And the options you gave vertically is false, give Y. Read Here

Read more

Counting rows from second table

Question by Goldie

I have two tables in mysql database

groups

id|name
_______
1 |red
2 |blue
3 |green
4 |white

and users

id|name  |group
_______________
1 |joe   |1
2 |max   |1
3 |anna  |2
4 |lisa  |2

So… joe and max are in the “red” group, anna and lisa are in the “blue” group.

How can I make simple listing of groups which would contain the number of
persons in that group
For example

red - 2
blue - 2
green - 0
white - 0

Answer by Mosty Mostacho

Give this a try:

select g.name, count(u.id) from groups g
left join users u on g.id = u.group
group by g.id, g.name

Answer by Starx

This should work

SELECT g.*, COUNT(DISTINCT u.id) FROM `groups` g
INNER JOIN `users` u on g.id = u.group
GROUP BY u.id
Read more
...

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