php - jQuery voting system -
so making voting system, thumbs & thumbs down voting system. using cakephp , jquery mysql want make sure front end correct , best way it.
i want user able change vote, so utilizing jquery best , efficient way? i'm novice jquery when comes class manipulation.
the id field going unique id of photo users voting on. of course test , not going final product in production. there multiple photos on page , user votes or down each of them.
here code.
<?php echo $javascript->link('jquery/jquery-1.4.2.min',false); ?> <script type="text/javascript"> $(document).ready(function() { $('.vote').click(function () { if ($(this).hasclass("current")) { alert("you have voted option!"); return; } var parentid = $(this).parent("div").attr("id"); if ($(this).hasclass("up")) { //do backend query , checking here alert("voted up!"); $(this).toggleclass("current"); if ($("#" + parentid + "-down").hasclass("current")) { $("#" + parentid + "-down").toggleclass("current"); } } else if($(this).hasclass("down")) { //do backend query , checking here alert("voted down!"); $(this).toggleclass("current"); if ($("#" + parentid + "-up").hasclass("current")) { $("#" + parentid + "-up").toggleclass("current"); } } }); }); </script> <div id="1234"> <a id="1234-up" class="vote up" >+</a> | <a id="1234-down" class="vote down" >-</a> </div>
you way:
<script type="text/javascript"> $(document).ready(function() { $('.vote').click(function () { if ($(this).hasclass("current")) { alert("you have voted option!"); } else { var parentid = $(this).parent("div").attr("id"); var error = false; if ($(this).hasclass("up")) { //do backend query , checking here (set: error) alert("voted up!"); } else if($(this).hasclass("down")) { //do backend query , checking here (set: error) alert("voted down!"); } //removes votes $(this).parent("div").children().removeclass("current"); if(!error) { $(this).addclass("current"); } else { alert("there error"); } } return false; }); }); </script> <div id="1234"> <a class="vote up" href="#">+</a> | <a class="vote down" href="#">-</a> </div>
it removes need html id's , dont need doubled code add current class. i'm not sure quicker, think way allow better code maintenance.
Comments
Post a Comment