...

Hi! I’m Starx

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

How to receive an event when selected option is the already selected option of a dropdown?

Jarrod Roberson’s Question:

Objective:

I want to dyanmically load a select with values from an AJAX call, and allow the user to select the first item in the list once it is loaded and after it gets focus, right now, the first item is the selected item and when you click the dropdown and click the first item nothing happens. I can’t add any placeholder items that are not valid selections.

Question:

How do you fire the .change event in jQuery when the currently selected option is reselected / not changed?

Given the following :

<select id="myoptions">
  <option id="one" >Option 1</option>
  <option id="two">Option 2</option>
</select>

Assuming that option one is selected, and I click on the dropdown and select one again, what event fires?

$('#myoptions').change(function() {
    alert('You selected something!');
}

The above code works if I select something different, but if I select the currently selected option nothing happens. I tried using .click and nothing happens then either.

In other words :

If I click on the dropdown and “select” the currently selected option, how do I get an event to fire?

NOTE:

All these suggestions about trigger are not solutions, I need something that fires when I click on Option 1 with the mouse when Option 1 is already the selected option.

None of the answers is a working solution for the use case of the very first time the dropdown is selected, and someone selects the default selected option. Nothing happens.

focusout is not a solution, it doesn’t happen until someone clicks somewhere else, which is too late in the game.

Use .trigger() function to fire custom events on elements.

$("#yourelementid").trigger('change'):

This way you can trigger the change event on element with id yourelementid

Now since you want this to happen when you click on the dropdown and select the previous element. Adding a click event should do it.

$("#yourelementid").on('click', function() {
    $(this).trigger('change');
});
Read more
May 9, 2013

In PHP, how do I call master class functions to different pages?

Gopinath’s Questions:

I have master class for the whole project. I need to call master class functions to different pages and methods as described below:

Master.php

class master{

    function login_parser(){

    }
}

Index.php

include('master.php')

function test(){
    $obj = new master();
}

function test2(){
    obj = new master();
}

I need to call object for every method. Is there any way to call an object in single time?

Yes, Instead of creating object everytime. Create on outside the functions on global scope.

include('master.php')
$obj = new master();

function test(){
    global $obj; //Now carry on
}

function test2(){
    global $obj;
}
Read more

What is the best way to prepend a conjunction to the end of an imploded array in PHP?

Danronmoon’s Questions:

Let’s say I have an array.

$shopping_list = array('eggs', 'butter', 'milk', 'cereal');

What is the easiest and/or most clever way to display this as a comma-delimited list and prepend a word (conjunction, preposition, etc.) to the last value? Desired results include:

'eggs, butter, milk, and cereal'
'eggs, butter, milk, or cereal'
'eggs, butter, milk, with cereal'
'eggs, butter, milk, in cereal'
// etc.

The array will be of variable length, may be associative, and preferably it shouldn’t be modified. It needn’t be imploded either; I figure this is just the standard way of doing things like this. Array dereferencing is fine too, but something PHP 5.3-compatible would be great.

I’m thinking something along the lines of

$extra_word = 'and';

implode(', ', array_slice($shopping_list, 0, count($shopping_list) - 1)) 
    . ', ' . $extra_word . ' '
    . implode(',', array_slice($shopping_list, count($shopping_list) - 1));

But that’s a doozy. Loops are cleaner and slightly less inept:

$i = 0;
$output = '';

foreach ($shopping_list as $item) {
   $i += 1;
   if ($i > 1) {
       $output .= ', ';
       if ($i === count($shopping_list)) {
           $output .= $extra_word . ' ';
       }
   }

   $output .= $item;
}

Both of these ways seem roundabout. Is there a better way out there that comes to mind?

This is cleaner too.

$pop = array_pop($shopping_list);
echo implode(", ", $shopping_list)." and $pop.";
Read more

Exclamation mark doesn't work in trigger() when using event namespace in jQuery 1.9

User2301368’s Questions:

Here is the code:

$("div").on("click",function(){
       console.log("click");
});
$("div").on("click.plugin", function(){
       console.log("click.plugin");
});
$("button").click(function() {
      $("div").trigger("click!");    
});

and the HTML:

<div>test.</div>
<button >Trigger event according to namespace</button>

When I run the code under jQuery 1.8.3, it works. When I click button, it logs click in the console.

But when I change to jQuery 1.9.1, nothing happens when I press the button. It seems like the exclamation mark doesn’t work anymore in 1.9.1.

I can’t find this change in the 1.9 upgrade guide. Does anybody know why?

Use .$ instead of !

$("button").click(function() {
      $("div").trigger("click.$");    
});

Demo [Credits: Tim B James]

Read more

how to get click event of text box with in an li using jquery

Anoop’s Questions:

I have a list of text box within <li>'s. How can I get the click event of the text box?

They are placed inside a <div> nested as shown below.
the lis’s section is dynamically created with jquery .. but the click event is not triggerd as like . i have tried the jquery answers posted in dynamic

<div>
   <ul>
        <li><input type="text"></li>
        <li><input type="text"></li>
    </ul>
</div>

Thanks

$('li').on('click','input[type="text"]', function(){
//code goes here//
});

There you go.

jQuery selectors are similar to CSS Selectors. You can use the same pattern and apply event handler to the elements. But, It would be very easy if you identify your code using class and id. Like

<div id="mydiv">
<!-- Adding ID to the div like this will help you to target your event handler
     To a set of required elements only -->

   <ul>
        <li><input type="text"></li>
        <li><input type="text"></li>
    </ul>
</div>

Then you can catch the click event on the text box very simple as

$("#mydiv input[type='text']").on('click', function() {
// ^ Isn't this as same as CSS?

    console.log("I am clicked");
});

With your markup even though you apply event handler it will be general and will apply to all the text boxes inside a div throughout the page.

If you dont want to change your markup and want to apply the function to all the input boxes. A general version of this code would be:

$("div :text").on('click', function() {
    console.log('I am clicked');
});
Read more

If mouse up then call the function

User2156494’s Questions:

I have the following code that calls a function. However, I would like the function to be called only on the event of a Mouse Up.

positionMenu : function(){
        if (positionMenuInvalidated) return;
        positionMenuInvalidated = true;
        setTimeout(_positionMenuNow,1); }

The _positionMenuNow which is called in setTimeout should happen only in the event of a mouse up. How can this condition be satisfied ?

I don’t think its a good idea to check whether the mouse is up or not while executing the timeout. Instead its better if you trigger the timeout after the mouseup has been triggered.

$('body').on('mouseup', function() {
   setTimeOut("_positionMenu()", 1000);
Read more

how to know whether check box is checked or not

Veena’s Questions:

$('[name="SelectHighlights"]:checked').each(function () {
        var row = $(this).closest('tr');


        var high = {
            AccountId: row.find('td:nth-child(3)').text(),
            Highcomments: row.find('td:nth-child(4)> input').val()
        };
        HighlightsArea.push(high);

    });

this is my code for retreiving the rows with checkbox checked

how to retreive the rows where check box is not checked

Please help me
Thanks in advance

Use :not() selector

$('[name="SelectHighlights"]:not(:checked)').each(function () {
    var row = $(this).closest('tr');


    var high = {
        AccountId: row.find('td:nth-child(3)').text(),
        Highcomments: row.find('td:nth-child(4)> input').val()
    };
    HighlightsArea.push(high);
 });
Read more
May 7, 2013

PHP – Avoid reloading page after form submit

User2108393’s Questions:

I’m new to php and web-programming… I’m working on a school project modifying databases through a corporate site.

I’m using some forms to allow the user to look for information that will be used to fill up other forms on the same page. In this case, a car rental, I look for available cars, show them on a table and then the user picks a car and its info would fill up some other inputs on the same page.

I’m able to do the search and show the result, but then when the user picks the car and clicks submit the whole page is uploaded again. Please, any suggestions?

J.

Redirect to a different page/route, other than the one page was submitted to.

An example for different page redirection.

header("location: differentpage.php");
exit;

Once you are in differentpage.php you cannot reload the POST request. TO get the data you can use SESSION or GET parameter as per requirements.

Read more

Just little bit confusion with &amp;&amp; , != and || in php

Deerox’s Questions:

I am just wondering how i can get success as echo without changing my if (.....) condition. do i need to add more condition or any function or an array? just a lil confused write now thanks. Just want to know if it will work this way or i have to write big codes for this condition 🙂

$petbuyer1 = 1;
$petbuyer2 = 2;
$petbuyer3 = 3;
$user_id = 1;
$petfom = "fomyes";
$fomon = "fomyes";

if (($petfom == $fomon) && ($user_id == $petbuyer1 || $user_id == $petbuyer2 || $user_id == $petbuyer3)) {
    echo "failed";
}else{
    echo "success";
}

Also tried :

if (($petfom == $fomon) && ($user_id != $petbuyer1 || $user_id != $petbuyer2 || $user_id != $petbuyer3)) {
    echo "failed";
}else{
    echo "success";
}

Seems like a typo error with $fomom. May be it should be $fomon.

Read more

Recommended max PHP session length

Vital’s Questions:

In terms of security (or other issues), what are the general recommendations / rules of thumb re PHP session length. A client with an Ecommerce website requested a 3day session length.

There are no general rule of thumb for this, depends on application build. For example:

  1. For bank website: 15/30 Seconds might be appropriate
  2. For a simple CMS application: 15 minutes long session is good enough.
Read more
...

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