...

Hi! I’m Starx

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

Is there an easy way to convert text into HTML in JavaScript?

Question by Dejas

Possible Duplicate:
Escaping HTML strings with jQuery
JavaScript/jQuery HTML Encoding

For example, if I wanted to show the user the string x < 3 in HTML I would need to replace the < character with &lt;. Is there a prebuilt function to do this in JavaScript or perhaps jQuery that converts any text string into the corresponding HTML?

Answer by bhamlin

If you want to use jQuery, you can use the text(string) method.

$(".selector").text("x < 5");

http://api.jquery.com/text/

Answer by Starx

Or, Take it simple and do this

var str1 = "x < 3";
str1.replace(/</g, '&lt;');

Here is a function from another question

function htmlEscape(str) {
    return String(str)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
}

Or, Excellent cheat using jQuery Source

function htmlEncode(value){
  return $('<div/>').text(value).html();
}

function htmlDecode(value){
  return $('<div/>').html(value).text();
}
Read more

Coding standards for documenting javascript function

Question by tamakisquare

Possible Duplicate:
What options are available for documenting your Javascript code?

In Python, to document a function, there is Docstring (example below)

def complex(real=0.0, imag=0.0):
    """Form a complex number.

    Keyword arguments:
    real -- the real part (default 0.0)
    imag -- the imaginary part (default 0.0)

    """
    if imag == 0.0 and real == 0.0: return complex_zero
    ...

Wondering what’s the coding standards I should follow for documenting function in javascript.

Answer by Starx

Read this excellent articles to know about the ways to document in JS.

Also check this question What tools are available for documenting JavaScript?

Read more

Take href of an anchor in a container and apply it to image

Question by Liam

I have a list of DIV’s that all contain a piece of text, an image, and an anchor.

With Javascript/jQuery, is it possible to take the href of the anchor, and wrap the image in anchor tags with that link?

I know this is a strange requet, Ive made a fiddle…

http://jsfiddle.net/fFgwb/


There will be multiple divs so I cant have the same id

Answer by Starx

Here is a way

var src = $("#imgid").attr("src"); //take out the src
$("#imgid").wrap($('<a href="'+src+'" />'); //wrap around it with the anchor

Your usage, can be something like

$("img", $("#divid")).each(function() {
    var src = $(this).attr("src"); //take out the src
    $(this).wrap($('<a href="'+src+'" />')); //wrap around it with the anchor

});

Here is a demo with this implementation on your fiddle.

Read more

jQuery validation – How to not accept a file extension

Question by Maxime Lepers

I would like to find a way to refuse a specific extension in a text field at form submission.

I have a field where you can specify a URL but this URL shouldn’t link to a PDF file.

I figured that there is a jQuery validation methods called accept that does exactly the contrary of what I want to do.

Is there a way to use with a not() function or something similar? It would be way easier than creating a custom validation method.

Answer by Starx

Here is any idea

var ext = $('#fieldid').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','jpg', ...]) == -1) {
    alert('invalid extension!');
}
Read more

exporting and uploading mysql database from dev to production

Question by jpporterVA

I am in the process of implementing an upgrade to my small website that consists mainly of adding 13 tables to my mysql database, loading a few rows into each (type codes and reference data). I was able to do a release previously when I created the database in production and populated it with one table.

I created that one by hand via the php mysql admin tool (shared hosting at godaddy), and I guess I can do the same thing again since my release is still small. But, I’d like to know what some of the best ways to upload the database to production would be. I’d like to be able to take a snapshot of the database tables along w/ the contents of some of the reference tables and ftp them to production and load them. And, I’d like to know what is best to use for more complicated sites (which my site is going to be over time) and accounts for any procedures or triggers (which I don’t have yet).

Since my site is live, i don’t want to figure this out with trial and error while it’s down, so . your suggestions are appreciated in advance.

Answer by Starx

Here is a pictured tutorial of how you can do this using phpMyAdmin.

Read more

Weird issue with a php if statement

Question by FunkyMonk91

I want to use this page to determine if the user has either updated a newsletter or created a new one. It connects to the database no problem and will update, but I can not get it to insert a fresh one as it gives me this error:

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ” at line 1

If I remove the if statement and just force it to insert a new record it will work with no issues.

Any advice would be greatly appreciated, thank you.

<?php
$server = "localhost";
$username = "user";
$password = "****";
$database = "test";

$con = mysql_connect($server, $username, $password);

$title = $_POST["title"];
$body = $_POST["body"];
$transaction = "Record Added";

if (!$con)
{
    die('Could not connect: ' . mysql_error());
}

mysql_select_db($database, $con);

if(isset($_POST["id"]))
{
    $sql = "INSERT INTO newsletter (date, title, body)
    VALUES('1990-12-12', '$title', '$body')";       
}
else
{
    $id = $_POST["id"];
    $transaction = "Record Updated";
    $sql = "UPDATE newsletter SET title='".$title."', body='".$body."' WHERE newsletterId =".$id;   
}

if (!mysql_query($sql,$con))
{
    die('Error: ' . mysql_error());
}

echo $transaction;

mysql_close($con);
?>

Answer by jeroen

Your logic seems flawed, if an ID is posted you try to insert and when no ID is posted you try to update:

if(isset($_POST["id"]))
{
    $id = $_POST["id"];
    $transaction = "Record Updated";
    $sql = "UPDATE newsletter SET title='".$title."', body='".$body."' WHERE newsletterId =".$id;        
}
else
{
    $sql = "INSERT INTO newsletter (date, title, body)
    VALUES('1990-12-12', '$title', '$body')";   
}

That is where your error comes from, your $id is empty.

Apart from that you should look into sql injection. Switching to prepared statements is the best way to go.

Answer by Starx

Quotes your query properly

$sql = "UPDATE newsletter SET title='".$title."', body='".$body."' WHERE newsletterId ='$id'";
Read more

Swap class on click

Question by Will B

I’ve been trying to figure out how I’m supposed to change a class of an element when you click it.

At the moment i have two classes (cOpen and cClosed). When you open the page the div is set to ‘cClosed’.

<div id="camera" class="cClosed" onClick="cameraToggle('weekLoaderWrapper', 'cameraContainer');">Kamera</div></a>

The things within onClick is not relevant to my question btw..

I’ve also put this script in the code

$('#camera').click(function() {
    $(this).toggleClass('cOpen');
    $(this).toggleClass('cClosed');
});

What I want it to do is to when you press the “camera”-div the class simply swaps to cClosed instead of cOpen, and vice verse when you click it again. This isn’t working atm.

My problem is how i’m supposed to “toggle” the div so it swaps the class of the “camera”-div.

Answer by Starx

Why are you using two classes? Use one class to identify the open and none to denote closed.

$('#camera').click(function() {
    $(this).toggleClass('cOpen');
});
Read more

DIV Style and DIV Position not getting along

Question by user1186164

<div id=mmactivate style='display: none'>
<form>
<INPUT TYPE="text" NAME="date1xx" VALUE="" SIZE=25>
<IMG SRC=CalandarIcon.png HREF="#" onClick="cal1xx.select(document.forms[0].date1xx,'anchor1xx','MM/dd/yyyy'); return false;" TITLE="cal1xx.select(document.forms[0].date1xx,'anchor1xx','MM/dd/yyyy'); return false;" NAME="anchor1xx" ID="anchor1xx">
<DIV ID="testdiv1" STYLE="position:absolute;background-color:white;layer-background-color:white;"></DIV>
</form>
</div>

This code is used to activate a popup java calandar. For some reason the style=’display: none’ and the position:absolute; arn’t playing along. If I delete one or the other it works, otherwise it does nothing when I click it…

Any ideas on how to make it work?

Answer by Starx

So many mistakes

  1. Java is not JavaScript. [MetalFrog]
  2. Line 1: id=mmactivate should be id="mmactivate"
  3. Line 2: The form consists of no method, actions or enctype. [Mr. Lister]
  4. Line 4: Why is there script in the title field?
  5. Line 4: Why does an image have a href attribute. [Mr. Lister]
  6. Line 4: Inline event handlers are a bad choice to start with.
  7. Line 5: testdiv1 is a child of “mmactivate”, so it has to follow its parent’s display: none;
Read more

How to get SQL-like HAVING and GROUP BY for PHP arrays?

Question by Average Joe

Is there a PHP code snippet or a built in array function that would do kind of like what a sql statement with having and group by does? That is removing the dups and counting the occurrences and giving you back an array that you can use for reporting/debugging purposes.

An example may clarify;

say your array is like this

Array (
['0'] => usa
['1'] => minnesota
['2'] => california
['3'] => san fransisco
['4'] => los angeles
['5'] => san fransisco
['6'] => malibu
['7'] => malibu
['8'] => malibu
['9'] => usa
}

and you want something back like this, or something to this effect..

Array (
['usa'] => 2
['minnesota'] => 1
['california'] => 1
['san fransisco'] => 2
['los angeles'] => 1
['malibu'] => 3
}

Answer by David Z.

http://www.php.net/manual/en/function.array-count-values.php

You can use the following code to do this:

array_count_values ($myArray)

Answer by Starx

Use array_count_values() to get the number of duplicates

$array = array(...);
$duplicate = array_count_values($array);
Read more

set default value other than options value using jquery

Question by Both FM

<select id="itemDepartment">

  <option value="1">Computer Accessories</option>
  <option value="2">Laptop</option>

</select>

the following attribute set the default value in drop down list

selected="selected"

but I want to select the default value other than options value i.e Please Select Department , when I click on the drop down list then Please Select Department text disappear and options value appear ( as default behavior)

Answer by gdoron

<select id="itemDepartment">
    <option class="placeHolder" value=""> Please Select Department </option>  
    <option value="1">Computer Accessories</option>
    <option value="2">Laptop</option>
</select>​​​​​

$('#itemDepartment').focus(function() {
    $(this).find(".placeHolder").hide();
}).blur(function() {
    $(this).find(".placeHolder").show();
});​

Live DEMO

Answer by Starx

Just add a dummy value with the text you want.

<select id="itemDepartment">
  <option value="" selected="selected">[Please Select Department ]</option>
  <option value="1">Computer Accessories</option>
  <option value="2">Laptop</option>    
</select>
Read more
...

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