Is there a way I can pass the php option value variable $option_value['price'] into javascript as a string, then each time a different option is chosen, the javascript 'updates' the string with the new value. I have tried with onchange() but must be doing something wrong. I am sure my mistake is because php is server side and javascript is client side, but I have no idea how to get the two to act how I want.
<?php if ($options) { ?>
<?php foreach ($options as $option) { ?>
<?php if ($option['type'] == 'select') { ?>
<span id="option-<?php echo $option['product_option_id']; ?>" class="option">
<select name="option[<?php echo $option['product_option_id']; ?>]" onchange="getIt(this)">
<?php foreach ($option['option_value'] as $option_value) { ?>
<option value="<?php echo $option_value['product_option_value_id']; ?>"><?php echo $option_value['name']; ?>
<?php if ($option_value['price']) { ?>
<?php $option_value['price']; ?>
<?php } ?>
</option>
<?php } ?>
</select>
</span>
I have tried:
<script type="text/javascript">
function getIt(elm) {
var val = elm.options[elm.selectedIndex].text;
window.alert(val);
}
</script>
and
<script type="text/javascript">
function getIt() {
var val = "<?php $option_value['price']; ?>";
window.alert(val);
}
</script>
Here is an example how you can do it. What you have to do are:
Analyze the code (notice that I use jquery from google's account. You will need to at some point install jquery on your web site and use this one instead of the google's one.
Build your fruits array so it looks like the one in the example.
I have prepared page that will show you this working here: http://jsfiddle.net/7uudp/
Below is what it contains. Notice that this example does not use your variables. You will need to use them the way you want/need. I have also defined entry_fruit to show you how to chose the default one to be selected. Hope it will help.
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
fruits = [{n:"apple",p:1},{"n":"strawbery",p:3}];
entry_fruit="strawbery";
function build_select(select,list,which)
{
$.each( list, function(i,v){
var selopt="" ;
if ( v.n == which ) selopt="selected" ;
$(select).append("<option "+selopt+" value="+i+">"+v.n+" - $"+v.p+"</option>");
}) ;
}
$(document).ready(function(){
build_select($("select[name=fruits]"),fruits,entry_fruit);
$("select[name=fruits]").change(function(){
alert("Price is $" + fruits[$(this).val()].p);
}) ;
})
</script>
</head>
<body>
<select name="fruits"></select>
</body>
</html>
<script type="text/javascript">
function getIt() {
var val = "<?php echo $option_value['price']; ?>";
window.alert(val);
}
</script>
Like so? Looks to me like you just forgot the "echo".
EDIT-
<script type="text/javascript">
var val = "<?php echo $option_value['price']; ?>";
function getIt(elm) {
val = elm.options[elm.selectedIndex].text;
window.alert(val);
}
</script>
Okay, Revoking my previous entry.
What you need to do is to add selected keyword to your <option> element when you match your option_value['price']
Now yuou need to arrange your data in a little bit different way.
In your javascript, prepare an array that will map $option_value['product_option_value_id'] to $option_value['price'];. When you build your <select>, for each $option_value['product_option_value_id'] check if its price matches the one that came in initially from php.
Your getIt will simply take the <option value="___"> value, find it in that map, and show it to the user using the alert() window.
Related
i have a php website, there is a form which user can submit, i want to disable few dates if they are already present in database, so i did like below:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input id="niy" name="idate" value=""/>
<?php
$queryusersz = "SELECT * FROM invoice";
$dbz = mysqli_query($con, $queryusersz);
while($row = mysqli_fetch_array($dbz)) {
$names[] = $row['idate'];
?>
<script>
var array = <?php $names ?>;
$('#niy').datepicker({
language:'TR',
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [ array.indexOf(string) == -1 ]
}
});
</script>
<?php }?>
however the input box doesnt show date and neither i get any errors in console, can anyone please help me with this, thanks in advance.
For jQuery DatePicker, You need to add jQuery UI JS and CSS.
There are two things you need to follow:
You can not directly write var array = <?php $names ?>; in JS as It will give error, You need to do JSON Encode or You need to add it in quote.
For Exmaple: var array = <?php echo json_encode($names); ?> or var array = '<?php echo implode(",",$names); ?>'
One more thing you missed in code is You didn't added echo for PHP variable which you are using in JS.
For Example: Right now your code is var array = <?php $names ?>;, It is without echo so that $name value will not store in JS variable until you echo it.
For more reference see below code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<input id="niy" name="idate" value=""/>
<?php
$queryusersz = "SELECT * FROM invoice";
$dbz = mysqli_query($con, $queryusersz);
while ($row = mysqli_fetch_array($dbz)) {
$names[] = $row['idate'];
?>
<script>
var array = '<?php echo implode(",",$names) ?>';
$('#niy').datepicker({
language:'TR',
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [ array.indexOf(string) == -1 ]
}
});
</script>
<?php }?>
i want to pass PHP variable to Javascript array.
It is a test code, but in further i want to pass the printed product id's and name's to this ajax function to send it to cart
The code above is working without printing the button with echo.Any better ideas are welcome :)
<html>
<?php
$num=3;
echo "<button onclick='funkt('<?php echo $num ?>');'>cc</button>
";
?>
</html>
<script>
function funkt(x){
var c=x;
alert(c);
}
</script>
You weren't properly escaping the quotes inside the echo statement. Also, HTML attributes use double quotes (onclick="..."), not single quotes.
Try this:
<!DOCTYPE html>
<html>
<head>
<script>
function funkt(x) {
var c = x;
alert(c);
}
</script>
</head>
<body>
<?php
$num = 3;
echo "<button onclick=\"funkt('" . $num . "');\">cc</button>";
?>
</body>
</html>
Better option is to add an input field of type hidden and pass the number/name/ID to it. On submission of form or button click, you can fetch it wtih the field Id and pass the value to ajax.
<input type="hidden" id="number" value="<?php echo $num;?>" />
<script>
function funkt(x) {
var c = document.querySelector("#number").value;
alert(c);
}
</script>
You can try to declare variable inside "script" tag, and then use this variable in the javascript afterwards like this:
<?php $num = 5; ?>
<script>
var link_label = '<?php echo $num ?>';
//use your link_label value to load it in ajax here or in other files that has been loaded after this script
</script>
I need to echo multiple line error in JS alert and I am using below code
Working code
$str = "This is a error1\\n";
$alert = $str."This is error2";
if(!empty($alert)){
?>
<script type="text/javascript">
alert('<?php echo $alert;?>');
</script>
<?php
}
but I need to work on an old written code so this has addslashes function before echo alert like below:
$str = "This is a error1\\n";
$alert = $str."This is error2";
$alert = addslashes($alert);
if(!empty($alert)){
?>
<script type="text/javascript">
alert('<?php echo $alert;?>');
</script>
<?php
}
Output : This is a error1\nThis is error2
I need this to print in two lines I have also tried with only \n but it is not working then.
I'd make javascript do the hard work.
<script type="text/javascript">
var alertArr = ["<?php echo $string1; ?>", "<?php echo $string2; ?>"];
alert(alertArr.join("\n"));
</script>
https://jsfiddle.net/0uwmmm3n/
(Magnificent random url by the way)
EDIT: less messy version, maybe more legitimate
<?php $alertArr = [$string1, $string2]; ?>
<script type="text/javascript">
var alertArr = <?php echo json_encode($alertArr); ?>;
alert(alertArr.join("\n"));
</script>
RE-EDIT: nah, too much work for a job so simple, two conversions is way too much
$str = "This is a error1\\n";
$alert = $str."This is error2";
$alert = addslashes($alert);
if(!empty($alert)){
?>
<script type="text/javascript">
alert('<?php echo $alert;?>');
</script>
<?php
}
I have used this code and it working fine according to your need
if still issue continues then clear your cache
I have this line of code
<script type="text/javascript">
document.title = "<?php include('pot1.php');?>"
</script>
My pot1.php gives me an echo with one random number, but that code does not seem to work and I don't know why the echo doesn't appear in my title. Is anything wrong with the code?
pot1.php code:
<?php
#include_once('link1.php');
$cg = fetchinfo("value","info","name","current_game");
$cb = fetchinfo("cost","games","id",$cg);
$cb=round($cb,2);
echo '$'.$cb;
?>
This echo is working and is giving me values because I can see them in one div.
You should just do it like this:
<?php include('pot1.php');?>
Now we know that there is a variable set. Echo that into the title tag.
<script type="text/javascript">
document.title = "<? echo $cb ?>"
</script>
The way you're doing it now... I don't think you can include an entire PHP page and expect to behave like a simple string, even if that's all it returns.
Put the value you want inside a variable in the pot1.php file and use it on the title
<?php include('pot1.php');?>
<script type="text/javascript">
document.title = "<?php echo $yourVar;?>"
</script>
I am trying to change a drop down so that a user can add a custom input instead.
I am using VQMod and have currently set up a PHP array as follows:
<td><select name="electricColours">
<?php foreach (array("", "White", "Black", "Add Custom Colour..." ) as $eColours) { ?>
<?php if ($electricColours == $eColours) { ?>
<option value="<?php echo $eColours;?>" selected="selected"><?php echo $electricColours; ?></option>
<?php } else { ?>
<option value="<?php echo $eColours;?>"><?php echo $eColours; ?></option>
<?php }?>
<?php } ?>
<td class="left"><a onclick="AddCustomColour();" class="button"><?php echo "Add Custom Colours"; ?></a></td>
</select>
How would I be able to add new values to the eColours using the "Add Custom Colour..." so that the user inputs something and that colour is added on to the array.
I thought using Javascript so that it shows up as an alert and the user gets to choose their option would work however it keeps saying the variable is not defined.
<SCRIPT TYPE="text/javascript">
function AddCustomColour()
{
var colour=prompt("Please add custom colour","Silver");
var arrays = <?php echo json_encode($electricColours); ?>;
if (colour!=null)
{
electricColours.push(colour);
}
}
</SCRIPT>
Thanks
Use the DOM API:
var option = document.createElement("option");
option.setAttribute("value", value);
option.appendChild(document.createTextNode(value));
document.getElementById("the_select_element").appendChild(option);
Instead of:
document.getElementById("the_select_element")
You could do something like:
document.forms.the_form.electricColours
replace this code
<SCRIPT TYPE="text/javascript">
function AddCustomColour()
{
var colour=prompt("Please add custom colour","Silver");
var arrays = <?php echo json_encode($electricColours); ?>;
if (colour!=null)
{
electricColours.push(colour);
}
}
</SCRIPT>
With this Code
<script type="text/javascript">
function AddCustomColour()
{
var colour=prompt("Please add custom colour","Silver");
var ob = $("#electricColours");
if (colour!=null)
{
ob.prepend("<option value="+ val +">" + text + "</option>");
}
}
</script>