...

Hi! I’m Starx

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

Jquery on selecting id issue

Question by user1050619

Can you let me know what is the problem with my code. I have given the code for all the sections belowie; the HTML/CSS & JQuery

When I click my go veg button the class fish should hide.

CSS file

div{
 display:inline;
 float:left;
 height:245px;
 text-align:left;
 border: solid #000 3px;
}

html file

<html>
 <head>
    <link rel="stylesheet"  type="text/css" href="file://c:/jquery/chapter-2/begin/styles/my_style.css"   />
    <script src="file://c:/jquery/chapter-2/begin/scripts/jquery.js"    type="text/javascript"></script>
    <script src="file://c:/jquery/chapter-2/begin/scripts/my_scripts.js" type="text/javascript"></script>
 </head>

<body>
<div class="topper">
    <h2>Our Menu</h2>
      <div class="buttons"><button type="submit" value="vegon">Go Vegetarian</button></div>
      <div class="buttons"><button type="submit" value="restoreme">Restore Menu</button></div>
</div>
<div class="middle">
<li>Thai-style Halibut
 <ul class="menu_list">
  <li                 >coconut milk</li>
  <li class="fish"    >pan-fried halibut</li>
  <li                 >lemongrass broth</li>
  <li                 >vegetables</li>
  <li                 >Thai spices </li>
 </ul>
</li>
<li>Braised Delight
 <ul class="menu_list">
  <li class="meat"    >lamb shoulder</li>
  <li                 >cippolini onions</li>
  <li                 >carrots</li>
  <li                 >baby turnip</li>
  <li                 >braising jus</li>
 </ul>
</li>
<li>House Grilled Panini
 <ul class="menu_list">
  <li class="meat"    >prosciutto</li>
  <li                 >provolone</li>
  <li                 >avocado</li>
  <li                 >cherry tomatoes</li>
  <li                 >sourdough roll</li>
  <li                 >shoestring fries </li>
 </ul>
</li>
<li>House Slider
 <ul class="menu_list">
  <li                 >eggplant</li>
  <li                 >zucchini</li>
  <li class="hamburger">hamburger</li>
  <li                 >balsamic vinegar</li>
  <li                 >onion</li>
  <li                 >carrots</li>
  <li                 >multigrain roll</li>
  <li                 >goat cheese</li>
 </ul>
</li>   <li>Frittata
 <ul class="menu_list">
  <li class="meat"    >eggs</li>
  <li                 >Asiago cheese</li>
  <li                 >potatoes </li>
 </ul>
</li>
<li>Coconut Soup
 <ul class="menu_list">
  <li                 >coconut milk</li>
  <li class="meat"    >chicken</li>
  <li                 >vegetable broth</li>
 </ul>
</li>
<li>Soup Du Jour
 <ul class="menu_list">
  <li class="meat"    >grilled steak</li>
  <li                 >mushrooms</li>
  <li                 >vegetables</li>
  <li                 >vegetable broth </li>
 </ul>
</li>
<li>Hot and Sour Soup
 <ul class="menu_list">
  <li                 >roasted pork</li>
  <li                 >carrots</li>
  <li                 >Chinese mushrooms</li>
  <li                 >chili</li>
  <li                 >vegetable broth </li>
 </ul>
</li>
<li>Avocado Rolls
  <ul class="menu_list">
  <li                 >avocado</li>
  <li                 >whole chiles</li>
  <li                 >sweet red peppers</li>
  <li                 >ginger sauce</li>
 </ul>
</li>
</div>
</body>
</html>

js file

$(document).ready(function() {
    $(".buttons").click(function(){
    $("li.fish").hide();
});
});

Answer by Abdul

nothing wrong every thing is fine.
just replace following line from head

<script src="file://c:/jquery/chapter-2/begin/scripts/jquery.js"    type="text/javascript"></script>

with this line

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

Answer by Starx

The code seems to work, but in any case pinpoint the selection to the buttons not the containers.

$(".buttons button").click(function(){
    $("li.fish").hide();
});

Judging by your code, where you are loading scripts like

<script src="file://c:/jquery/chapter-2/begin/scripts/jquery.js"    type="text/javascript"></script>

Make is the path is correct and is loaded. Further, It will be better if you relative path rather than absolutes.

<script src="scripts/jquery.js" type="text/javascript"></script>

The snippet above signifies, there is a folder with jQuery script, on the same base path as the active file.

Read more

Parse error: syntax error, unexpected T_VARIABLE in /home/rixo/public_html/login/process.php on line 41

Question by Jack-T

I am new to php. I keep having this error – Parse error: syntax error, unexpected T_VARIABLE in /home/rixo/public_html/login/process.php on line 41

Here is the full code – http://pastebin.com/8Yqmk0MX

If you could look through it for me and see what is the problem it would be a great help.

-Thank you in advance

Answer by Starx

Its due to unclosed quote on this line

$checkuser = mysql_query('SELECT username FROM user WHERE username='$user');

Fix it

$checkuser = mysql_query("SELECT username FROM user WHERE username='$user'");

Update:

Found another query error on line 61 of the paste. There is mismatching quotes

$write = “INSERT INTO user (username, password, email) VALUES ('$user', '$pwd', '$mail’)';

Fix them

$write = "INSERT INTO user (username, password, email) VALUES ('$user', '$pwd', '$mail')";
Read more
April 26, 2012

Function fails when called by other function

Question by Mark Hollas

fairly new to jQuery so bear with me.

I am having trouble getting the results of one function over to another an executing it.

Then the point is to pass the text as a var to the function populateMessage() and it writes the text to a text box.

I can get the text and it does get passed to the populateMessage function but the function never fully executes and the text box is not populated. If I wrap the populateMessage function in document.ready and have it write something like .text(‘test’); it will work.

How can I make this work?

Thanks for the help

$(document).ready(function () {
    getClickedInvite();
});

//gets clicked item template and sends it to message box

function getClickedInvite() {
    $('.card').click(function () {
        var selectedMessage = $(this).text();
        alert(selectedMessage);
        populateMessage(selectedMessage);
    });
}

function populateMessage(selectedMessage) { 
    alert(selectedMessage + ' has been sent to the message box ')
    var inviteMessageBoxId = $('#inviteMessageBox').find('textarea').attr('id');
    alert(inviteMessageBoxId);
    $('#' + inviteMessageBoxId).text(selectedMessage);
}

Answer by Starx

There is no need to extend the function like that. And if you read the manual, it says

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

SO .find() always does not return a single element.

$('#inviteMessageBox').find('textarea')[0].text(selectedMessage);

Or, if getting id is really that necessary then

var id = $('#inviteMessageBox').find('textarea')[0].attr('id');
$("#"+id").text(selectedMessage);
Read more

need help to figure out what is the error, it's jQuery code

Question by user1743638

i’m trying to make something like light box for a message with jQuery and CSS
but it doesn’t work!!!
here is jQuery code

$(document).ready(function(e) {

    function myFunction(){
        $("#overLay").hide();
        $("#x").hide();
        $("#message").hide();
    }

    $("#overLay").click( myFunction() );
    $("#x").click( myFunction() );

});

Answer by muffel

function myFunction(){
    $("#overLay").hide();
    $("#x").hide();
    $("#message").hide();
}
$(function(){ //run after page is loaded
   $("#overLay").click(myFunction);
   $("#x").click(myFunction);
});

Answer by Starx

As for the syntactical part, The way you are calling the functions are wrong, call them without the parenthesis

$("#overLay").click( myFunction );
$("#x").click( myFunction );
Read more

Add class to link

Question by Danis

I need help with links. I have this kind of links

 <a class="campusIcon km-icon" onclick ="window.location.href='indexHome.html'" data-rel="external">Campus</a>

 <a class="searchIcon km-icon"  onclick ="window.location.href='indexListView.html'"  data-rel="external">Search</a>

 <a class="mapIcon km-icon"  onclick ="window.location.href='indexKBlock.html'"  data-rel="external">Map</a>

 <a class="favIcon km-icon" onclick ="window.location.href='indexChart.html'" data-rel="external">Fav</a>

I need add class km-state-active to this links. if I add class oncklick event, then I get my class added but location.href does not work. So what’s a problem, and how to solve it?

Answer by Starx

You shouldn’t use inline script. its a bad practice. Update you markup to look similar to this.

<a class="campusIcon km-icon" href ="indexHome.html" data-rel="external">Campus</a>

And use jQuery to add the class on click

$("a").on('click', function() {
    $(this).addClass("km-state-active");
});
Read more

eval addition with -1 doesn't work

Question by David 天宇 Wong

I’m having trouble with this js code:

$('.downvoted').live('click',function(){
var ele = $(this);
var truc = ele.prev('.score_position');

$.post('ajax/vote.php', { vote :ele.attr('title') }, function(data) {
    if(data == 'done'){
        ele.removeClass('downvoted').addClass('downvote').html('<img src="images/down.png" />');
        truc.html(eval(truc.html()+1));
    }
});
return false;
});                 

so I have this same function 3 other times for downvoting, un-upvoting and upvoting. It works well except with one exception, if truc.html() is -1 then it goes to -11 instead of 0.

Any idea why it doesn’t work? (you guys can try it here: http://91.121.154.130/?sort=last&# with id:azerty pw:azerty)

Answer by Elliot Bonneville

Don’t use eval() for this sort of work! Use parseInt, Number(...), or any of the other numerous ways of converting a value to a number in Javascript.

truc.html(parseInt(truc.html(), 10) + 1);

Note the second parameter in the parseInt function. This means you want the value passed into be parsed as a base-10 number. If you pass in a number starting with 0 into the parseInt function without specifying the radix you’ll get an unexpected and unwanted result.

Or

truc.html(Number(truc.html())+1);

Or even this:

truc.html(truc.html()*1 + 1);

This works because multiplying a string number by one results converts the variable to a number. Be careful– if the variable you multiply isn’t a valid number you’ll get NaN!

The reason you can’t simply do truc.html(truc.html()+1); is because .html() returns a string value. If you add a number to a string in Javascript, the number is simply concatenated to the string, and no math is performed. (e.g. “-1” + “1” equals “-11”).

Answer by Starx

You need to make sure the value is an integer and Use of .text() is better on this case.

parseInt(truc.text(), 10)+1
Read more

Can not prevent form submit when I add one line

Question by tosin

I am stacked. My code can not prevent defaut action of submit. This was working fine until I add this.doSomething();.

Why this happens? Do I have to use preventDefault?

working code: http://jsfiddle.net/WwW5R/

HTML:

<div id="container">
    <form action="" method="post" id="input">
            <input type="submit">
    </form>
</div>

JavaScript:

$(function() {
    var ReserveUI = function($el) {
        this.$form = {
            input: $el.find('#input')
        };
        this._eventify();
    };

    ReserveUI.prototype.doSomething = function() {
        return false;
    }

    ReserveUI.prototype._eventify = function() {
        this.$form.input.submit(function() {
            this.doSomething(); //if comment out this line, it works
            return false;
        });
    };
    var UI = new ReserveUI($("#container"));
});

thanks for reading:)

Answer by Alnitak

In your submit callback function, this no longer refers to your object, but to the element itself.

It’s therefore causing an exception because the element has no doSomething property, and your return false is skipped.

Instead, write this:

ReserveUI.prototype._eventify = function() {
    var self = this;
    this.$form.input.submit(function(e) {
        e.preventDefault(); // cancels event even if subsequent lines fail
        self.doSomething();
    });
};

See http://jsfiddle.net/xgGGx/1/ for a working example showing that it’s just the scope issue causing the bug.

This is what script debugging tools are for – the reported error should have made the fault reasonably obvious…

Answer by Starx

This is a scope mismatch.

this.$form.input.submit(function() { //here "this" is ReserveUI
    this.doSomething(); //here "this" is input button
    return false;
});

And since there is no doSomething() on input button, the script breaks thus no longer executing the portion to return false.

Here is a way you can get around this

ReserveUI.prototype._eventify = function() {
    var $this = this; //create a reference to the object
    this.$form.input.submit(function() {
        $this.doSomething(); //Now call the object method
        return false;
    });
};

Demo

Read more

Finding whether time is in a defined range

Question by spsingh

Possible Duplicate:
How to check if a date is in a given range?
How to check if date(entered by user) is in given range (Date format :-day month ie.:-1 june )

I am trying to find whether a date is in defined range. I’m using the following code:

    $apple='25 March';
    $udate= date('d F',strtotime($apple));

    echo $udate;
    $startDate='21 March';
    $realStartDate= date('d F',strtotime($startDate)) ;
    echo $realStartDate;
    $endDate='19 April';
    $realEndDate= date('d F',strtotime($endDate)) ;
    if ($udate >= $realStartDate && $udate <= $realEndDate ) {
        echo 'within tange';
    }
    else{
        echo 'Not in range';
    }
    ?>

Where am I going wrong?

Answer by Starx

Like this

if(strtotime($givendate) > strtotime('3/21/xxxx') && strtotime($givendata) < strtotime('4/19/xxxx')) {
   // Its within range
}
Read more

OOP: Which class should own a method?

Question by Frungi

I’m having trouble understanding how classes relate to their methods. Is a method something that the object does, or something that’s done to it? Or is this a different concept entirely?

Specifically, in a library’s software system, should the borrow() method belong to the class representing the library patron, or the class representing the item that the patron is borrowing? My intuition is that it should read like patron.borrow(copy), like English sentence structure, subject.verb(object); but my instructor says that’s Wrong, and I don’t understand why he would have borrow() belong to the Copy class (and he doesn’t really explain things too well). I’m not looking for justification, but can someone just explain the proper relationship?

Edit: This question was closed as “off topic”. I don’t understand. Are software design questions not appropriate for this site?

Answer by Konstantin Oznobihin

Some generic words first.

Software construction is not something which should be governed by English language rules or “beauty” or whatever, it’s engineering discipline. Think of whether your design solves the problem, whether it will be maintainable, whether it will be testable, whether it will be possible to parallelize development and so on. If you want something more formalized take a look at the “On the Criteria To Be Used in Decomposing Systems into Modules” by D. L. Parnas.

As for your library example. Imagine you have a Copy outside of library, shoult it have borrow method then? How the borrowing is registered? Are you ok with either Copy or Patron classes responsible for data storage? It looks more appropriate to put borrow into a Library class. Responsibilities will be clearly divided, you wouldn’t need to know much about borrowing to implement Copy and Patron and you wouldn’t need much details about them to implement Library.

Answer by Starx

Is a method something that the object does, or something that’s done to it? Or is this a different concept entirely?

Let me clear something about class and objects first. Class are generally used to a denote particular category. Like

  1. Cars not Ferrari, or Porsche
  2. Fruits not Banana, or Apple

So, it’s Ferrari that is driven, and a banana that is eaten. Not their class

Its always an object that has properties and has behavior.

Even going to your case specifically.

borrow() method is an action/behavior done by a object of a person on an object of book whose records is kept by another object of the library system itself.

A good way to represent this in OO way for me would be like

libray.borrow(new book('book title'), new person('starx'));

Just for fun, What do you think about this

person starx = new person('starx');
book title1 = new book('title1');
library libraryname = new library('libraryname');
libraryname.addBook(title1);

if(starx.request(title1, libraryname)) {
     starx.take(library.lend(title1, starx));
}
Read more

fadeout and fadeIn callback function in jquery

Question by amit

i have three div with value first, second and third i want to fadeout them first and them fadein with delay function now i want that when my last div fadein then my all three div fade out. but my code in not working well

<script type="text/javascript">

$(function(){

    $('.fileianN').fadeOut().delay(1000).fadeIn(1000);
        $('.fileianLY').fadeOut().delay(2000).fadeIn(1000);
            $('.fiuleHg').fadeOut().delay(3000).fadeIn(1000);

    })


</script>





<div class="duanNt">
<div class="fileianN">first</div>
<div class="fileianLY">second</div>
<div class="fiuleHg">third</div>


</div>

Answer by roXon

jsBin demo

$.when(

    $('.duanNt').children().each(function(idx,el) {
        $(el).delay(idx*600).fadeTo(700,1);
    })

).done(function() {
    $('.duanNt').fadeTo(300,0);
});

http://api.jquery.com/jQuery.when/
http://api.jquery.com/deferred.done/

P.S if you don’t want to hide the .duanNt it self but only it’s children than use: $('.duanNt > div').fadeTo(300,0);

Answer by Starx

There is already a callback function. Which You can use like

$("element").fadeOut(1000, function() {
   //..callback
});

Your usage might be similar to this

$('.fileianN').fadeOut().delay(1000).fadeIn(1000, function() {   
     $('.fileianLY').fadeOut().delay(2000).fadeIn(1000, function() {
            $('.fiuleHg').fadeOut().delay(3000).fadeIn(1000);
     });
});
Read more
...

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