i am quite new to Jquery and Javascript but i ve created a script which communicates with a php controller in symfony2.
My question is, what can i do to reduce the script length –> maybe there is a smarter way to solve the logic which i solved with the switch expression?
Thanks
/**
* This function gets the current clicked buttons value and post it to the given action + returns the correct value
*/
$(document).ready(function() {
$('button.rating-button').click(function(event) {
event.preventDefault();
var $element = $(this).attr('id');
var $rating = $(this).attr('value');
var $messageId = $(this).closest('ul').next('input:hidden').val();
if(typeof $rating !== 'undefined' && $rating != null) {
$.post(Routing.generate('rating_vote', { 'messageId': $messageId, 'ratingCode': $rating }),
function($json) {
$('button#'+$element).parent().find('span').text($json.numberOfRatings);
/* check if oldRating is defined and oldRating is not the same as new rating ( prevent decrease of actual value if this is the first vote entry for the current message and the specific user ) */
if(typeof $json.oldRating !== 'undefined' && $json.oldRating != null && ($json.oldRating != $rating) ) {
switch($json.oldRating) {
case 1:
$oldElement = 'rating-first';
break
case 2:
$oldElement = 'rating-second';
break;
case 3:
$oldElement = 'rating-third';
break;
}
$('button#'+$oldElement).parent().find('span').text(Number($('button#'+$oldElement).parent().find('span').text()) -1);
}
});
}
});
});
you can replace your switch case logic with this rather neat concept.
Some general thoughts: