Ratings using HTML radio buttons and javascript - php

I am trying to change the default behavior of a Magento Reviews extension such that it will allow a no-vote but only if there is a review attached. I have done enough research to know where to change the code, and I have added a "Cancel Rating" function, but it isn't working exactly as expected, and I can't seem to figure out how to check if a rating is present.
Here is the HTML part where the radios are defined.
<div class="right" id="ratings-right">
<?php $countRatings = count($this->getRatings()); ?>
<?php foreach ($this->getRatings() as $_rating): ?>
<?php if ( $countRatings > 1 ): ?>
<div class="rating-code" id="ratings-code[<?php echo $_rating->getRatingCode(); ?>]"</div>
<?php endif; ?>
<ul>
<?php $sizeOptions = sizeof($_rating->getOptions()); $index=0; ?>
<li class="value">
<div class="rating-cancel"></div>
<input type="radio" value="0" name="cancel[<?php echo $_rating->getId() ?>]" id="<?php echo $this->escapeHtml($_rating->getRatingCode()) ?>C<?php echo $_rating->getId() ?>" class="radio" /></li>
<?php foreach ($_rating->getOptions() as $_option): $index++;?>
<li class="value">
<div class="separate-rating-star"></div>
<input type="radio" <?php if ( $sizeOptions == $index ) :?><?php endif; ?>name="ratings[<?php echo $_rating->getId() ?>]" id="<?php echo $this->escapeHtml($_rating->getRatingCode()) ?>_<?php echo $_option->getValue() ?>" value="<?php echo $_option->getId() ?>" class="radio" />
</li>
<?php endforeach; ?>
</ul>
<?php endforeach; ?>
<input type="hidden" name="validate_rating" class="validate-rating" value="" />
</div>
And here is the JavaScript portion where validation and resetting occur
Validation.addAllThese(
[
['validate-rating', '<?php echo $this->__('Please select a rating above OR write your Review below') ?>', function(v) {
var ratingContainer = document.getElementById('ratings-right');
var ratings = ratingContainer.getElementsByClassName('rating-code');
var values;
var star;
var error = 1;
window.console&&console.log("START");
for (r=0;r < ratings.length; r++ ) {
values = ratings.getElementsByClassName('value');
stars = values.getElementsByTagName('radio');
for (s=0; s < stars.length; s++ ) {
console.log("Checking star %d.", s);
if (stars[s].checked == true) {
error = 0;
window.console&&console.log("Radio %d is checked.\n", s);
}
}
var review = $('review_field').length;
window.console&&console.log("Review size %d.", review);
if ( review > 5 ) {
error = 0;
window.console&&console.log("Review size (%d) greater than 5.", review);
}
if( error != 0 ) {
window.console&&console.log("Failed.\n");
return false;
} else {
window.console&&console.log("Passed.\n");
error = 1;
}
}
return true;
}]
]
);
$(".overall-raiting ul li").click(
function(){
var tthis = this;
var done = 0;
var $li = $(tthis).parent().children('li');
$li.removeClass('active');
$li.each(function(){
if( done < 1 ) $(this).addClass('active');
if ( tthis == this ) done++;
if( done != 1 ) $(this).prop('checked', false);
})
if ( done > 0 ) return false;
$(this).find('input.radio').attr('checked',true);
}
);
I can't get the console to consistently report values despite reading questions here about using the delete window['console']; method in firefox with firebug and Chrome. But it appears that my .onclick function is changing all radios to unchecked, including the one that should be checked. And as near as I can tell I am not selecting the radios in the validation portion, I've tried using the .val() and .value properties, but this code is my most recent attempt.
All I want is the radio that is clicked to stay checked with all others unchecked and to validate by determining if any is checked (including the cancel) OR if the textarea 'review_field' contains anything.
My final answer is provided below. It is more elegant than my first solution, but I hope this helps someone in the future.

According to what you want to do
all others unchecked and to validate by determining if any is checked (including the cancel) OR if the textarea 'review_field' contains anything
this function might help:
function isValidForm() {
var numRadios = $('#ratings-right input:radio:checked').length,
reviewContents = $('#review_field').val(),
isValid = numRadios == 1 || reviewContents != '';
return isValid;
}

First, my Javascript logging problem was resolved by an answer to this question: JavaScript console log in Magento
jQuery(document).ready(function(){
window.console = jQuery('<iframe>').hide().appendTo('body')[0].contentWindow.console;
});
This obviously only works if you are using jQuery.
The remainder of my question was resolved by implementation of a variation of bbird's code:
var rated = 0;
var ratingValue = $('#ratings-right input:radio:checked');
var reviewArea = $('#review_field');
var reviewContents = "";
for (i=0; i<reviewArea.length; i++) {
reviewContents += reviewArea[i].value;
}
for (i=0; i<ratingValue.length; i++) {
if (ratingValue[i].value.length == 1 )
rated = 1;
}
console.log("%s", rated);
console.log("%s", reviewContents);
var isValid = rated > 0 || reviewContents != '';
console.log("%s", isValid);
return isValid;
As for the radio buttons themselves, in Magento's database, I added a zero star value with an optionId of 99999. This rating is displayed first among the rating options and in the controller for this, I check for a value less than 9999. This ensures that a zero star rating won't be calculated into the aggregate.
This also allowed all radio buttons to be the same class and name so there is no longer any need to programmatically uncheck anything. Radio buttons' default behavior is that only one radio among a group with the same name is allowed to be checked.
here's the implementation of the radio buttons now:
<div <?php if ($_option->getValue() == "0" ) echo "class=\"rating-cancel\""; else echo "class=\"separate-rating-star\"" ?>></div>
<input type="radio" <?php if ( $sizeOptions == $index ) :?><?php endif; ?>name="ratings[<?php echo $_rating->getId() ?>]" id="<?php echo $this->escapeHtml($_rating->getRatingCode()) ?>_<?php echo $_option->getValue() ?>" value="<?php echo $_option->getId() ?>" class="radio" />
This way the first option, which has a value of 0, can by stylized with css to be a cancel button of some sort, and the rest will be stars.

Related

importing from mysql column to checkbox php

i am trying to import from mysql column as an exploded values (category id) from table called "products", and print it in a checkbox input, and check if the value (category id) equal to the (category id) in the table called "cats", to set checkbox to "checked", this is my code:
<?php
for($i2=0;$i2<$rowsZ22;$i2++){
//exploding
$catszz2 = explode(",", $bussSubcat);
//foreach start
foreach($catszz2 as $catzz2) {
if($catzz2==$row22[$i2]["id"]){
$ischecked2="checked";
}else{
$ischecked2="";
}
}
//foreach end
?>
<li><input type="checkbox" onclick="getElementById('cats<?=$row22[$i2]["parent"]?>').checked= true;" <?=$ischecked2?> value="<?=$row22[$i2]["id"]?>" name="subcats[]" id="" /> <?=$row22[$i2]["title"]?></li>
<?php
}
?>
the code is checking the last input only (last category)
any help ?
You're running a foreach before you actually output the checkbox...
So, the $isChecked variable is actually changing in your foreach, but only the last value of the loop will be printed.
You need to move your
<li></li>inside the loop of the $isChecked
I'm not sure if this is what you want, but here goes:
<?php
for ($i2 = 0; $i2 < $rowsZ22; $i2++) {
$catszz2 = explode(",", $bussSubcat);
foreach ($catszz2 as $catzz2) {
if ($catzz2 == $row22[$i2]["id"]) {
$ischecked2 = "checked";
} else {
$ischecked2 = "";
}
?>
<li>
<input type="checkbox"
onclick="getElementById('cats<?= $row22[$i2]["parent"] ?>').checked= true;" <?= $ischecked2 ?>
value="<?= $row22[$i2]["id"] ?>" name="subcats[]" id=""/> <?= $row22[$i2]["title"] ?>
</li>
<?php
}
}
?>

I want to use PHP variable in jQuery in loop

I want to use PHP variable in jQuery.
I am having a 50 students data in table which having textbox and radio button.
By default textbox is hidden but when I clicked on radio button textbox show in table.
$("input[type='radio']").on('change', function() {
if ($(this).val() == "2")
var id = '<?php echo json_encode($absent); ?>';
//$("input[type='text']").show();
else
$("input[type='text']").hide();
});
PHP code:
<input name="nxtmark<?php echo $row[0]; ?>" type="text" id="nxtmark<?php echo $row['id']; ?>" onblur="onleave(this.name);" maxlength="2" placeholder="Enter Mark" hidden="" />
<div class="noerrordiv" id="dnxtmark<?php echo $row[0]; ?>">Mark must not be blank</div>
</td>
<td>
<div align="justify">
<input type="radio" id="rdopresent" name="rdopresent<?php echo $row['id']; ?>" checked="checked" value="1" />Present
<input type="radio" id="rdoabsent" name="rdopresent<?php echo $row['id']; ?>" value="2" />Absent<br />
</div>
</td>
</tr>
You can show / hide text box without using PHP variable. See below code -
$("input[type='radio']").on('change',function() {
//find input text from the previous 'td' for which name starts with 'nxtmark'
var $textBox = $(this).closest('td').prev('td').find('input[name^=nxtmark]');
//show hide text box as per radio button value
if($(this).val() == "2")
$textBox.show();
else
$textBox.hide();
});
If your Problem is just to use PHP variable in jquery then following examples will help you.
if you have to user a php array in jquery then use json_encode in PHP not in SCRIPT.
<?php
$a = array(1,2,3,4);
$a = json_encode($a);
$b = "hello";
?>
<script>
$(document).ready(function(){
alert("<?php echo $a; ?>");
alert("<?php echo $b; ?>");
});
</script>

jquery with variable php

I have this code php
............................
..............................
.................
<input type="radio" name="option[<?php echo $option['product_option_id']; ?>]" stock="
<?php if ($option_value['subtract']) { ?>
<?php if ($option_value['quantity'] >= 3) { ?>
<?php echo $text_in_stock; ?>
<?php } ?>
<?php if ($option_value['quantity'] < 3 && $option_value['quantity'] > 0) { ?>
<?php echo $option_value['quantity']; ?> <?php echo $text_pcs_only; ?>
<?php } ?>
<?php if ($option_value['quantity'] <= 0) { ?>
<?php echo $text_out_of_stock; ?>
<?php } ?>
<?php } ?>
" value="<?php echo $option_value['product_option_value_id']; ?>" id="option-value-<?php echo $option_value['product_option_value_id']; ?>" onchange="recalculateprice();" />
<div class="pippo">
.................
.......
</div>
then I have this script
<script type="text/javascript">
function recalculateprice() {
var stock = $('#style_stock').attr('stock');
$('input[type=radio]:checked').each(function() {
$('.pippo').hide();
if ($(this).attr('stock') != '<?php echo $text_out_of_stock; ?>') {
$('.pippo').show()
stock = $(this).attr('stock');
}
});
I need hide div pippo when check an option with stock = . But the attr stock in option radio has some if ....
What I have insert in this row ?
if ($(this).attr('stock') != '<?php echo $text_out_of_stock; ?>') {
i can't tell you exactly what is the problem
but here are few important notes:-
first in PHP
try to calculate the stock value outside the input tag stock attribute & echo the final value and remove the extra spaces.
try to use "else if" instead of stacking "if" commands and making ambiguity in the value
(its also easier)
second in Javascript
the code you have written will always show the ".pippo" div in case if there at least on radio button with attribute stock != out_of_stock so you need to make sure that you are testing the only changed radio.
the value of the $(this).attr('stock') in the case you use the line directly will be undefined as u didn't define it .
finally the calling for onChange attribute will make some problems in page loading and may give you error of undefined function
so instead i prefer as long as you are using jQuery attach the events through jQuery
here is a full sample of may what you can use
HTML
<div class="pippo">
.................
.......
</div>
<input type="radio" stock="...." name="opt">
<input type="radio" checked="checked" stock="10" name="opt">
<div id="style_stock" stock="10">stock = 10</div>
JAVASCRIPT
function recalculateprice(x) {
if ($(x).attr('stock') != '....') {
$('.pippo').show();
//put the code you want
}else{
$('.pippo').hide();
//put the code you want
}
}
$("input[type=radio]").change(function(){
recalculateprice(this);
});

JavaScript element style change with dynamic id

I am trying to put a line through a list item when the check box next to it is checked. I have managed to do it but I can't check if the the box is checked.
JS File
if(document.getElementById(theID).checked){
document.getElementById(theID).setAttribute("style", "text-decoration:line-through");
}
HTML/PHP
echo'<ol>';
foreach($to_do_XML->task as $item)
{
$theID = $item['id'];
echo '<li id="'.$theID.'">'.$item.'</li>' ;?><form ><input onclick="return cross('<?=$theID?>');" type="checkbox" name="done<?php $li_id_num_done ?>"/></form>
<?php
}
echo '</ol>';
i should also add that the list item is being added within a foreach loop looping trough xml elements
The above code does nothing any help would be appreciated
If $theID is a string, you need quotes around it:
<input onclick="return cross('<?php echo $theID; ?>');" type="checkbox" name="done<?php $li_id_num_done ?>"/>
Also remove this from your function:
got_elements_id
It will cause a reference error.
This would be better I believe:
echo '<li id="'.$theID.'">'.$item.'</li>' ;?>
<form >
<input onclick="return cross('<? echo $theID; ?>');" type="checkbox" name="done<?php $li_id_num_done ?>"/>
</form>
And
function cross( id ){
var element = document.getElementById( id );
if( element.checked){
element.style.textDecoration = "line-through";
}
}
Or even:
function cross( id ){
var element = document.getElementById( id );
element.style.textDecoration = element.checked ? "line-through" : "";
}
Which also enables unchecking and removing the linethrough.

how to validate a form submit in php

I have a form like this:
<form method="post" action="">
<?php
$h = mysql_query("select distinct sous_sous_categorie, sous_sous_categorie_url
from articles where sous_categorie_url='".$_GET["s_cat"]."' ");
while($hRow=mysql_fetch_assoc($h)){
?>
<span class="submit">
<input type="checkbox" name="<?php echo $hRow["sous_sous_categorie_url"]; ?>"
value="<?php echo $hRow["sous_sous_categorie_url"]; ?>" />
<?php echo $hRow["sous_sous_categorie"]; ?>
</span>
<?php } ?>
<input type="submit" name="submit_sous_sous_categorie_search"
value="search" class="submit" />
</form>
as you can see the form is in a loop, the form consists of checkboxes that user will check and accoding to this a search query will be made, the thing is that checkboxes have the name attribute but this attribute is variable (because it is fetch from the db) so my question is how can I make this:
if(checkboxes are empty){
echo "you must at least select one checkbox"
}
This is just an example but I dont see how to do a simple thing such as
if(!$_POST["checkbox"]}{
echo "you must at least select one checkbox";
}
Again, because the name of the checkboxes are variable.
You can make your checkboxes into an array by changing the name to:
name="checkboxes[<?php echo $hRow["sous_sous_categorie_url"]; ?>]"
Then you can use code like this to make sure at least one is checked:
$passed = false;
if( isset( $_POST['checkboxes'] ) && is_array( $_POST['checkboxes'] ) )
{
foreach( $_POST['checkboxes'] as $k => $v )
{
if( $v )
{
$passed = true;
break;
}
}
}
if( ! $passed )
{
echo "You must select at least one checkbox";
exit();
}
Also, you should be careful with your query there, you need to escape that to prevent SQL injection.
You can pass arrays from your FORM to the PHP script:
<!-- The brackets [] let PHP know you're passing in an array -->
<input type="checkbox" name="categories[]" value="<?php echo $hRow["sous_sous_categorie_url"]; ?>" />
Then in the script:
// $_POST['categories'] is an array when categories are checked.
if (empty($_POST['categories'])) {
echo 'Please select a category.';
} else {
foreach ($_POST['categories'] as $url) {
// do something with $url
}
}

Categories