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.
Related
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.
I have a couple of checkboxes and I want to execute a function for each of the elements marked as checked. How can I do this?
In my particular case, I think this might be a little bit easier, because the checkboxes are constructed like this:
$get_json_values=json_decode($json_string,true);
foreach ($get_json_values as $key=>$getlikes) {
if($getlikes['type']=='like') {
?>
<div>
<input type="checkbox" name="<?php echo $getlikes['name'] ?>" value="<?php echo $getlikes['id'] ?>" checked>
<a href="https://www.facebook.com/<?php echo $getlikes['id']; ?>" target="_top">
<?php echo $getlikes['name'] ?> </a>
</div>
<?php
}}
?>
So I think it should look like this:
function doIfChecked()
{
foreach ($get_json_values as $key=>$getlikes) {
if($getlikes['type']=='like'&&<sequence that checks if checkbox is checked>)
{//do stuff}
}
}
Can anyone please help?
Thanks to Julian H. Lam, I found a good answer, but my problem is that for each of the elements , I need to do a request to the server (like a page on facebook), but I can't put any php inside javascript.
So, how could I do that since php is not allowed inside js?
Using javascript:
var checkboxes = document.querySelectorAll('input[type="checkbox"]'),
numCheckboxes = checkboxes.length,
x;
for(x=0;x<numCheckboxes;x++) {
if (checkboxes[x].checked === true) {
// add code here to be done for each checked element
// you can refer to the checked element by calling "checkboxes[x]"
}
}
In the current example I have a form set up that takes a unique id. There is also a link that takes a unique id. The javascript function will fade in that form when the link is selected. Is it possible to call a javascript function based on the PHP variables used to id the form and the link? And so that it will fade in the correct when that corresponds to the unique id of the form?
PHP
while($row = mysql_fetch_array($query)){ $form_id = $row[id]; ?><a href="#"
id="askedClick"><?php echo $row[post_text].'<br>'?></a>
<form action="<?php $curent_file ?>"
method="POST" id="<?php echo $row[id] ?>">Do you know the anwer?
<input type="submit" value="Yes" name="<?php echo $form_id.'yes'?>"
/>
<input type="submit" value="No" name="<?php echo $form_id.'no'?>" />
</form>
<?php } ?>
JAVASCRIPT
$(document).ready(function () {
$("phpvariable").hide();
$("#phpvariable").click(function () {
$("#phpvariable").fadeIn(1200)
});
});
You could use ids, but it will be much easier to just give your link a class of say "showForm" and use HTML traversal to hide the form that follows it
$('.showForm').click(function(){
$(this).nextAll('form').first().fadeIn();
});
You can use the echo php statement. Example below:
echo '
$(document).ready(function () {
$("#' . $phpvariable . '").hide();
$("#' . $phpvariable . '").click(function () {
$("#' . $phpvariable . '").fadeIn(1200);
});
});';
I found a much easier method of doing this, thought I should I go back and put this in for reference
//Javascript
$(".testLink").click(function() {
var linkId = $(this).attr('id');
$("#testDiv"+linkId).fadeIn(400)
});
//PHP
for ($i = 0;$i < /*whatever*/; $i++){
?>
Click Here
<div style="display:none;" id="<?php echo 'testDiv'.$i ?>" >
Unique Data
</div>
<?php
}
In this method, a unique id is created between the link clicked, and the element to be manipulated in the javascript. This way each link can be of the same class, but each will have a unique id associated with its corresponding element, i.e div, form, span etc.
let's say I have a list of checkboxes that the user selects.
<input type="checkbox" name="utility[]" id="utility[]" value="Water" />Water<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />
etc...
The user selected Water and it is added to the database. Now the user wants to update the list:
<input type="checkbox" name="utility[]" id="utility[]" value="Water" checked="checked"/>Water<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />
etc...
How can I check that the utility has already been checked in PHP?
What I've done in the past, to save having hundreds of lines of bloat is this...
First compile all the html in a variable, without any "checked" instances.
$boxes = '';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Water" />Water<br />';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />';
Now I loop over your array of fields to check. I've provided a sample array here too.
$already_checked = array('Water', 'Electricity');
foreach( $already_checked as $ac ) {
$find = 'value="' . $ac . '"';
$replace = $find . ' checked="checked"';
$boxes = str_replace($find, $replace, $boxes);
}
echo $boxes;
You could do something like this:
<input type="checkbox" name="utility[]" value="Water"
<?= in_array('Water', $utilities) ? 'checked="checked"' : '' ?>"
/>
(The $utilities variable above is a stand-in for something like $_REQUEST['utilities'], depending on how your code is structured.)
Like that?
<input type="checkbox" name="utility[]" id="utility[]" value="Water"
<?php
if(isAlreadyChecked("Water"))
echo "checked=\"checked\""
?>
/>Water<br />
<?php
function isAlreadyChecked(value)
{
//Check if it is already checked and return a boolean
}
?>
I tried every variant of the in_array conditional out there and could NEVER get this to work (checking off the checkboxes whose values had been previously selected and thus inserted into the database). I tried complex queries with table joins and no luck with that either. I finally gave up and generated a display:hidden div that opened the array (which for some odd reason I had to IMPLODE rather than explode) and listed its items as comma-separated text. Then I tossed in a little jQuery indexOf() magic to determine if the value of each checkbox was part of said array or not. Took me 10 minutes flat to do this with jQuery, very simple.
Here's some sample code that is live and working fine:
<div class="categories">
<span class="keywords"><?php $categories = array(); $categories = implode(', ', $keywords); echo $categories ?></span>
<em>Please verify category selections with each update.</em><br/>
<?php
include 'db.php';
$sql = mysqli_query($con,"SELECT * FROM categoriesTable ORDER BY Category_Name ASC");
while ($row = mysqli_fetch_assoc($sql))
{
$key = urldecode($row['Category_Name']);
$id = urlencode($row['catID']);
echo "<input type='checkbox' name='Category_Key[]' value='$id' id='cat_$id' $chk> $key<br/>";
}
?>
</div>
CSS sets that div to invisible:
.keywords { display:none; visibility:hidden; }
and the jQuery portion:
$(document).ready(function() {
$('.categories input').each(function(index,data) {
var str=$('.keywords').text();
var catid = $(this).val();
var chk = str.indexOf(catid);
if (chk >= 0) {
$(this).prop('checked', true);
}
});
});
I hope this helps someone else who is stuck wondering why the in_array conditional is failing them. Since this falls in a twilight zone between data and UI regarding data persistence, I think it's a legit route to take. You have one "echo" statement to generate multiple checkboxes (there are around 40 categories in my situation here) and then a simple jQuery .each() to locate what was selected before and render its corresponding boxes as checked.
Hi Stackoverflow i hope you are all well today,
i seem to have run into an issue and am kindly requesting your assistance;
Basically i am using jQuery to manipulate a form, the form then stores in the session and upon returning to the page a foreach loop is used to return the values from the session into the page.
The issue is if I create more than one instance of this foreach loop it gives me an invalid argument (if i add the same code over and over again it works fine)
So firstly here is the code;
jQuery
$(function(){
$('.add_child').click(function(){
var attrName = $(this).attr('name');
var count = $(this).attr('count');
$(this).attr('count', (parseInt(count)+1))
var input = $('<input />');
var lineBreak = $('<br/>');
input.attr('type','text')
input.attr('name',attrName+"["+count+"]" )
$('.children_form').append(input);
$('.children_form').append(lineBreak);
})
$('.add_s_child').click(function(){
var attrName = $(this).attr('name');
var count = $(this).attr('count');
$(this).attr('count', (parseInt(count)+1))
var input = $('<input />');
var lineBreak = $('<br/>');
input.attr('type','text')
input.attr('name',attrName+"["+count+"]" )
$('.spouce_children').append(input);
$('.spouce_children').append(lineBreak);
})
});
and the PHP / HTML CODE -> Button One (add_child)
Children, please name your natural and / or addopted children
<?php foreach($_SESSION['children'] as $index=>$child){ ?>
<?php echo "<input type='text' name='children[{$index}]' value='{$child}'/>";?>
<?php } ?>
<input type="button" count='<?php echo count($_SESSION['children']);?>' name="children" class="add_child" value="Add Another Child"/>
<div class="children_form">
<?php //add the inputs here?>
</div>
and the PHP / HTML CODE -> Button Two (spouce_children)
<label>Spouces Children, please name all natural and addopted children</label>
<input type="text" name="spoucechild" id="spoucechild" />
<?php foreach($_SESSION['spoucechild'] as $index=>$child){ ?>
<?php echo "<input type='text' name='spoucechild[{$index}]' value='{$child}'/>";?>
<?php } ?>
<input type="button" count='<?php echo count($_SESSION['spoucechild']);?>' name="spoucechild" class="add_s_child" value="Add Another Child"/>
<div class="spouce_children">
<?php //add the inputs here?>
</div>
I would like to thank you for any help you can / will provide <3
Error Occurs here:
<?php foreach($_SESSION['spoucechild'] as $index=>$child){ ?>
#Xavier: You could try --
<?php
if (isset($_SESSION['spoucechild'])) {
foreach($_SESSION['spoucechild'] as $index=>$child){
echo '<input type="text" name="spoucechild[' . $index . ']" value="' . $child . '" />' . "\n";
}
}
?>