jquery with variable php - 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);
});

Related

Replace an onclick by a submit button

I am looking for create a submit button, But I don't know how to get an answer ID and convert it in javascript variable.
My code:
<div id="<?php echo $question_ID?>">
<form method="post">
<p><?php echo $question ['question_content']; ?></p>
<p>
<?php
$poll_option_selection = "SELECT option_ID, option_content FROM poll_options WHERE question_ID='$question_ID'";
$poll_option_result = mysqli_query ($connect,$poll_option_selection) ;
foreach ($poll_option_result as $poll_option) {
$option_ID = $poll_option ['option_ID'] ;
$option_content = $poll_option ['option_content'] ;
?>
<input type="radio" name="option_selected" value ='<?php echo $option_ID ?>' onclick='getVote(this.value) ;' required />
<?php echo $option_content ?>
</br>
<?php } ?>
</form>
</div>
I found my answer after several test.
First. I put this the label "on submit=" on my form.
<form onsubmit='getVote(question_ID);'>
After this, I create my function
<script> function getVote(question_ID) {
var option_ID = document.querySelector('input[id="option"]:checked').value; </script>
Thank you for everthing

Keep select list on reload

I have a select list, but on page reload , the data in the list is not saved of corse.
I have fixed this with TextBoxes and Radio buttons by reading the variables from $_GET.
Here is an example of the form I have now:
<form action="" id="exampleForm" method="get">
<input type="checkbox" name="exampleCheckbox" <?php if (isset($_GET['exampleCheckboxStatus'])) {echo "checked";} ?>>Check this
</br>
<select name="exampleList" multiple>
<option>Apple</option>
<option>Banana</option>
<option>Cherry</option>
</select>
<input type="submit" value="Submit" id="submitButton"> </form>
I would like to keep the values of the 'exampleList' once submitted
(I stay on the same page)
I have seen posts on here that almost look like what I ask, but most of them want to use javascript. Is there an solution for my problem, wich look similiar to what I already have right now? I would like to fix this with php because I dont think I have enough knowledge of Javascript (yet)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
var opts = localStorage.getItem('opts'); // get selected items from localStorage key
opts = opts.split(','); // split result from localstorage to array
$('#exampleList').val(opts); // select options with array
});
</script>
<html>
<body>
<select id="exampleList" multiple>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
</select>
</body>
</html>
When you POST the form you only need to write the selected option values, comma separated, to the localstorage.
I finally found a solution:
The only flaw is the order of the :)
But since I use a plugin for displaying it does not matter much.
The fix:
I created 2 Array lists
list1 with everying in it
list2 with all selected values
Then I subtract list2 from list1 and dont have duplicates
So I can print both in different print methods.
<?php error_reporting(E_WARNING);
$fruitArray = array("Apple", "Banana", "Cherry", "Durian", "Eggfruit", "Fig", "Grapefruit");
$selectedFruitArray = $_GET['exampleList'];
$fruitArray = array_diff($fruitArray, $selectedFruitArray);
?>
<form action="" method="get">
<select name="exampleList[]" multiple>
<?php
foreach($fruitArray as $value) {
echo "<option value='$value'>$value</option>";
}
foreach($selectedFruitArray as $value) {
echo "<option value='$value' selected>$value</option>";
}
?>
</select>
<input type="submit">
</form>
Use FormRepo, a plugin specially made for retaining form data
on page refreshes.
Its usage is also simple:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="FormRepo.js"></script>
<script>
var $form = $('#input')
, $output = $('#output')
, repo = new FormRepo('restclient')
;
// get the last submitted values back
repo.restore($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
$form.submit(function (e) {
// preserve the last submitted values
repo.preserve($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
});
console.log( repo.all() );
</script>
You can do it by using session. This is the way using it you can store last selected value in session. Session value will not be destroyed even if you reload paga.
For e.g.,
<?php
session_start(); // Other Code
<div>
<p>Subtitle needs to be
<input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] != "LIKE") echo "checked"; ?> value="LIKE">contain
<input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] == "=") echo "checked"; ?> value="=">be equal to
</p>
<input type="search" name="subTitleSearchBox" placeholder="filter for subtitle" class="chosenStyle" value="<?php echo $_GET['subTitleSearchBox'];?>">
</div> //Other Code
?>
PHP Code for set value in session after submit :
<?php
session_start(); //Not required if your form action is on same page, else required //Rest code
$_SESSION['subTitleRadio'] = $_GET['subTitleRadio'] // OR $_POST['subTitleRadio']; // Rest code
?>
Same code works for me.
first of all at value parameters to the options, then you can check if exampleList has the right value and use that. for example:
<option value="apple" <?php if (isset($_GET['exampleList']) && $_GET['exampleList'] == "apple") echo "selected=\"selected\""; ?>>Apple</option>
Well, you could try something along these lines. It's a bit lengthy, you could shorten it up quite a bit. By showing it this way, I hope it's simpler to understand.
<form action="" id="exampleForm" method="get">
<?php
if (isset($_GET['exampleCheckboxStatus'])) {
echo '<input type="checkbox" name="exampleCheckbox" checked> Check this';
} else {
echo '<input type="checkbox" name="exampleCheckbox"> Check this';
?>
<br />
<select name="exampleList[]" multiple>
<?php
if( in_array('apple', $_GET['exampleList']) ) {
echo '<option value="apple" selected>Apple</option>';
} else {
echo '<option value="apple">Apple</option>';
}
if( in_array('banana', $_GET['exampleList']) ) {
echo '<option value="banana" selected>Banana</option>';
} else {
echo '<option value="banana">Banana</option>';
}
if( in_array('cherry', $_GET['exampleList']) ) {
echo '<option value="cherry" selected>Cherry</option>';
} else {
echo '<option value="cherry">Cherry</option>';
}
?>
</select>
<input type="submit" value="Submit" id="submitButton">
</form>
Note that I added [] to the select's name and corrected the br tag.
Adding [] will change the type from "string" (text) to an array (several texts). Then we can check what texts are included.
Try it for yourself, play around with the code a bit.

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>

Ratings using HTML radio buttons and javascript

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.

What is the button text retrieved through jQuery here?

The php and html are pretty simple:
<?php
session_start();
$_SESSION['liked_or_not']=0;
?>
<button class="photo_like" value="<?php if($_SESSION['liked_or_not']==0){ echo 'Like';} else{ echo 'Unlike';} ?>" ><?php if($_SESSION['liked_or_not']==0){ echo 'Like';} else{ echo 'Unlike';} ?>
jQuery snippet:
<script type="text/javascript">
$(document).ready(function(){
alert("alert one ="+ $('.photo_like').text());
if($('.photo_like').text()=='Like'){
alert("alert two ="+ like_text);
}
});
</script>
The above code gives the ouput as 'alert one =Like' and then after a few invisible line breaks on the alert box a square. How does that square appear there?
And the second alert box does not appear, as the square box is not included in the if($('.photo_like').text()=='Like'){ comparison.
Also Chrome console says :Uncaught TypeError: Cannot read property 'hasPort' of undefined
Explanation?
You should close your button.
<button class="photo_like" value="<?php if($_SESSION['liked_or_not']==0){ echo 'Like';} else{ echo 'Unlike';} ?>" ><?php if($_SESSION['liked_or_not']==0){ echo 'Like';} else{ echo 'Unlike';} ?></button>
And use ternary operator can make your code more clear.
<?php $like_or_not = $_SESSION['liked_or_not']==0 ? 'Like' : 'Unlike'; ?>
<button class="photo_like" value="<?php echo $like_or_not; ?>"><?php echo $like_or_not; ?></button>
if you want the value Like and Unlike the set in into the hidden input box like:
<input type="hidden" name="getTxt" value="<?php if($_SESSION['liked_or_not']==0){ echo 'Like';} else{ echo 'Unlike';} ?>" >
and use something like this:
var getHiddenVal = $('input[name="getTxt"]').val();
// Return the value
its far easy with messing the codes.
$('.photo_like') can return multiple objects. To be sure it returns only one object use $('.photo_like:first')
To get the value of a button i always use val() instead of text().
So your if should be like this: if($('.photo_like:first').val()=='Like'){}

Categories