...

Hi! I’m Starx

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

javascript multiple checkbox validation

Question by skylab

I would like to use this simple script with my form to make sure I have at least 1 box checked but I have a feeling something is wrong, most likely at the getElementsByName tag. I always get the pop up box no matter if I have items checked or not.

<script language="javascript">
function validate() {
    var chks = document.getElementsByName('id[][]');
    var hasChecked = false;
    for (var i = 0; i < chks.length; i++) {
        if (chks[i].checked) {
            hasChecked = true;
            break;
        }
    }
    if (hasChecked == false) {
        alert("Please select at least one.");
        return false;
    }
    return true;
}
</script>

and the form, which may or may not end up with more checkboxes in the end:

<form 
enctype="multipart/form-data" 
method="post" 
action="formsubmission.php"
name="form_type" onSubmit="return validate()">

<input id="attrib-8-10" type="checkbox" value="10" name="id[8][10]">
<label class="Checkbox" for="attrib-8-10">thick</label>
<input id="attrib-8-11" type="checkbox" value="11" name="id[8][11]">
<label class="Checkbox" for="attrib-8-11">medium</label>
<input id="attrib-8-12" type="checkbox" value="12" name="id[8][12]">
<label class="Checkbox" for="attrib-8-12">thin</label>

Answer by Starx

var chks = document.getElementsByName('id[][]');

Does not select any element, as you have specied all the index on the elements .

Here is how you can do it?

var chks= document.getElementsByTagName('input');
for (var x=0; x < chks.length; x++) {
    if (chks[x].type.toUpperCase()=='CHECKBOX' && chks[x].checked == true) {
        hasChecked = true;
        break;
    }
}
Read more
April 2, 2012

jquery works on jsfiddle, but not on my website

Question by user1099029

Here is the link to the jsfiddle: http://jsfiddle.net/d3xMZ/

when I hover, it does exactly what it is suppose to do, which is load the social sharing.
but when I implemented it on my website, nothing happens on hover.
Can anyone help, I have googgled and looked at similar questions on stackoverflow, but no luck

Answer by Starx

First, Include the jquery library on your code.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

Next, Wrap the jquery code inside

$(function() {
  //place the js part here
});
Read more

How do I get the highest number in a column?

Question by Skiroid

My table named pictures has a column named pic and I’m wanting to get the highest number in that column. Each row has a unique number in pic and it goes up by 1 each row. But one or two rows won’t have a number in the column and will have some text instead. Like grapes.

Here’s an example of the table…

  TABLE: pictures
 ___________________
|  caption  |  pic  |
|-------------------|
|   some    |   1   |
|  random   |   2   |
|  thing    |   3   |
|   here    |grapes |
|___________________|

So, how would I get the highest number in the column pic which would be 3?

Column pic is a varchar.

Answer by zerkms

SELECT MAX(CONVERT(pic, UNSIGNED INTEGER)) AS max_pic
FROM pictures
WHERE CONVERT(pic, UNSIGNED INTEGER) IS NOT NULL 

The WHERE pic = pic + 0 condition is a trick that helps checking if it is a number value

Answer by Starx

Use MAX() to get the maximum value available. Like this

SELECT MAX(pic) FROM `pictures` WHERE CONVERT(`pic`, SIGNED INTEGER) IS NOT NULL 
Read more

How to link a textbox value to a database row and then insert it

Question by user1309180

I have a textbox where it stores in a user’s option. The possible options are options 3 all the way to 26, ‘True or False’ and ‘Yes or No’.

<input type="text" name="gridValues" class="gridTxt maxRow" readonly="readonly" />

Now in my database I have a table known as ‘Options’ which contains an ‘OptionId’ and ‘OptionType’ fields. The rows in the table is like this below:

OptionId  OptionType
O1        A-C
O2        A-D
O3        A-E

...

O24       Yes or No

Now what I want to do if it is possible is that I want options 3-26 and options ‘True or False’ and ‘Yes or No’ from the application to link with an ‘OptionId’ from the database.

For example:

If textbox equals 3 then this equals OptionId 'O1'
If textbox equals 4 then this equals OptionId 'O2'
If textbox equals 5 then this equals OptionId 'O3'

...

If textbox equals Yes or No then this equals OptionId 'O24'.

I want this to happen because when I INSERT VALUES, I want to INSERT the ‘OptionId’ in other database tables when I need to.

Is this possible to do and if so does anyone know how to link the textbox value to the ‘OptionId’ and then INSERT it into a database table known as ‘Questions’?

Answer by yo hal

If I understand correctly your problem then you want to an insert in one table based on another table’s value, this can be done with an INSERT SELECT as in

INSERT INTO questions SELECT optionid FROM options WHERE optiontype = $selected_option

Answer by Starx

It is not possible to link the textbox with the mysql row.

You will have to send an ajax request with a function attached on onChange event of the textbox to do this.

I am not going to cover the ajax part, but you can do something like this using jquery.

$("#yourtextbox").change(function() {
    var textval = this.value; //get the value
    $.post(
        "yourpage.php", //the page to update the text box based on the values
         { 
             'variablename': textval, 
             'action' : 'update' 
         }, //send the values
         function(data) {
             //do something on the success
         }
    );
});
Read more

extracting text from html file

Question by zeacuss

I’m trying to get nodes containing text from html file using Javascript and jQuery.
if I have a node like
`

<div>txt0
<span>txt1</span>
txt2
</div>


How can I select elements that meets this criteria??
Meaning, I need to retrieve the
divand thespan` , and it would be even better to know location of the text.

I’m trying to get the text to replace it with images in a later function.
I tried this

`

$('*').each(function(indx, elm){
   var txt = $(elm).text();
   // my code to replace text with images here
});

`

but it does not get the required results.. it does all the parsing in the first element, and changes the html totally.

Answer by Starx

Your markup structure is a bit uneasy. Consider changing to something like this

   <div>
     <span>txt0</span>
     <span>txt1</span>
     <span>txt2</span>
   </div>

Then using jQuery

$("div span").each(function(k,v) {
   $(this).html("<img src=""+v+".jpg" />"); //replace with the image
});
Read more

How to connect the 'MSSQL' database in Codeigniter Framework?

Question by Bhavin Rana

How to connect the ‘MSSQL’ database in Codeigniter Framework ?

i m currectly starting an application which is on codeignitor framework and for db i would like to use the mssql.

applicationconfigdatabase.php file settings here.

$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = '#.#.#.27';
$db['default']['username'] = '@@@@@@';
$db['default']['password'] = '@@@@@@@@@';
$db['default']['database'] = '$$$$$$$$$$$$$';
$db['default']['dbdriver'] = 'mssql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

after changing the ‘libraries’ in to autoload.php in config folder
it shows just a black white page only with no any of errors.
can you please tell me what other changes i have to do to work with the MSSQL Database ?

#autoload.php#

$autoload['libraries'] = array('database');

Many Thanks in Advance !
😀

Answer by Starx

Your Configuration code is fine. Further reading here

IF you believe the errors are not showing up, then go to the index.php and on the top place the following snippet to show the errors.

error_reporting(E_ALL);

Other, then this check if the MSSQL service is running and is accessible. May be create a simple .php and try a connection with plain codes.

A non CI file Something like,

<?php
$server = 'YOURPCSQLEXPRESS';
$link = mssql_connect($server, 'user', 'pass');

if (!$link) {
    die('Something went wrong while connecting to MSSQL');
}
?>
Read more

Use jQuery select() to select contents of a div

Question by Conor Higgins

Is it possible to use or adapt jQuery’s .select() to set a selection range on the entire contents of a div?

I have a div which has a series of labels, inputs, select objects and a couple of other UI elements. I have found code on a separate StackOverflow post with some code hosted on jsFiddle: http://jsfiddle.net/KcX6A/570/

Can this be adapted to select the value of inputs also? Or how would you suggest I go about this?

Thanks,
Conor


Edit: More info

I know how to get the value of inputs using jQuery, that is easy, I also know how to select he values of independent elements using .select().

In my div I have a series of different element types including inputs, labels, selects, etc. I need an overall selection of all elements. The jsFiddle link I added earlier shows how to set the range of a div and select the text of elements like p tags etc. What I need is to set the range of the div’s contents and when I hit ctrl+c or cmd+c it copies the values of the inputs as well as the labels.

So to summarise, using .val and .select won’t work for this I don’t think. I need to combine the above in some way but not sure exactly how this will be accomplished. Any ideas?

Answer by techfoobar

Check this fiddle: http://jsfiddle.net/JAq2e/

Basically the trick is to introduce a hidden text node whose content will be included in the selection when copied.

Answer by Starx

If you want to select the input elements together with every thing.

Here is a jQuery mixed, JS solution

function selectElement(element) {
    if (window.getSelection) {
        var sel = window.getSelection();
        sel.removeAllRanges();
        var range = document.createRange();
        range.selectNodeContents(element);
        sel.addRange(range);
    } else if (document.selection) {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(element);
        textRange.select();
    }
}

selectElement($("div")[0]); //Select the div
$("input").trigger("select");  //select the inputs

Demo

Read more

for each loop exception

Question by oneofthelions

I get an exception in my second print line.

int num[] = {50,20,45,82,25,63};
System.out.print("Given number : ");
for(int d:num){
System.out.print("  " + num[d]);
}

The console output is

Given number : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 50

Why doesn’t d take all the array elements but only 50?

Answer by Starx

In the for(int d:num) loop every item is represented by d not num[d]

So, here is how it should be done.

for(int d:num){
    System.out.print("  " + d);
}

A simple dry run will show you where you went wrong.

For the first loop your statement will come down to num[50] which is not available anywhere, so you get the exception.


However, if your attempt was to use indexing, then a simple trick below will do the trick

int index = 0;
for(int d:num){
    System.out.print("  " + num[index++]);
}

But I honestly believe, this is not the correct solution to the problem.

Read more

How to remove ANSI-Code ("&#13;") from string in PHP

Question by ESCOBAR

I have tried a lot but nothing is working. I want to import a XML-file with PHP. In some strings the customer puts some ANSI-Code Carrier Returns (“&#13;”). I have tried to remove them with:

str_replace('r', '', $xml->description);

I also tried it with "&#13;", "rn", "&\#13;" in the search but nothing works. Do you have any idea how to remove these linebreaks?

Thanks!

Answer by Corbin

Since your XML processor is already handling de-entitying the entities, you’ll be left over with plain ASCII n or r or rn. PHP does not handle r or n inside of single quotes. It only translates them to their respective characters (codes 10 and 13), when the r and n are inside of double quotes.

You just need to use “n” or maybe “rn”.

Answer by Starx

Actually, This runs just fine

$str = "&#13;"; //just an example

echo str_replace("&\#13;", "hello", $str);

Demo

Read more
...

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