I have this script for money conversion so user can choose it's currency from the list like Us to Euro so I want to make it remain same after page refresh like if user have chosen Euro and he refresh the page it should remain same.
Here is my Javascript and Code
<script>
function updatePrice(val) {
p = document.getElementById("original_price").value;
newp = p * val;
document.getElementById("calculated_price").value = newp;
}
</script>
Php Code:
<?php
$pr = 180;
?>
<select onchange="updatePrice(this.value)">
<option value="1">US</option>
<option value="98">RS</option>
<option value="61">Ind</option>
</select>
<input type="hidden" id="original_price" value="<?php echo $pr; ?>" />
Price: <input type="text" id="calculated_price" value="<?php echo $pr; ?>" />
Update 1 After Implementing Session
<?php
session_start();
// store session data
$_SESSION['value']=".updatePrice(this.value).";
if(isset($_SESSION['value']));
?>
<?php
$pr = 180;
?>
<select onchange="<?php echo $_SESSION['value']; ?>">
<option value="1">US</option>
<option value="98">RS</option>
<option value="61">Ind</option>
</select>
<br>
<hr>
<input type="hidden" id="original_price" value="<?php echo $pr; ?>" />
Price: <input type="text" id="calculated_price" value="<?php echo $pr; ?>" />
<script>
function updatePrice(val) {
p = document.getElementById("original_price").value;
newp = p * val;
document.getElementById("calculated_price").value = newp;
}
</script>
Actually PHP dosent offer any viewstate mechanism, as far as i know , So what you can do is store this in some hidden field.The best way and my personal recommendation is to use a session variable for this purpose
http://www.w3schools.com/Php/php_sessions.asp
And if you need to solve this issue using javascript, You can use Cookies too
http://www.w3schools.com/js/js_cookies.asp
I have done this using jquery and javascript by setting a cookie, hence i dont want you to get confused with jquery plugin for cookie. You can do this in a much more simpler way using jquery plugin for cookie.
Here's the code
HTML
<select id="selectCurrency">
<option value="1">US</option>
<option value="98">RS</option>
<option value="61">Ind</option>
</select>
jquery/javascript
$(document).ready(function(e){
var name = "Currency=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++){
var c = ca[i].trim();
if (c.indexOf(name)==0) $('#selectCurrency').val(c.substring(name.length,c.length));
}
});
$('#selectCurrency').change(function(e){
var cookieVal = "Currency="+$(this).val();
document.cookie = cookieVal ;
});
Fiddle
http://jsfiddle.net/AmarnathRShenoy/HM3Zj/
You can use session or store the selected values somewhere in database, inUpdate price function make an ajax call which stores, your selected value and keep pdating at, on onchange event. now, each time your page gets refreshed, the previuosly selected value will get fetched from the database and you can show it seleted.
Related
I am kinda new in JavaScript and need some help.
I have a search form in my navigation menu.
Here is my code php+html for the form.
<form action="search.php" name="form-name" method="GET" enctype="multipart/form-data">
<div class="row">
<div class="col-lg-2 col-md-12 col-sm-12 search">
<label>Destination</label>
<select required name="country" id="destination" onChange="getCity(this.value);">
<option value="">Any destination</option>
<?php $query = "SELECT * FROM countries";
$select_region_query = query($con, $query);
while ($row = fetch($select_region_query)) {
$region_id = $row['country_id'];
$region_name = $row['country_name'];
echo "<option value='".str_replace("&", "and",$full_region)."'>$full_region</option>";
}
?>
</select>
</div>
<div class="col-lg-2 col-md-12 col-sm-12 search ">
<label>City</label>
<select name="city" id="city" onChange="get_dropdown_ajax(this.value);">
<option value="">Any Cruise Line</option>
<?php $query = "SELECT * FROM cities";
$select_city_query = query($con, $query);
while ($row = fetch($select_city_query)) {
$city_id = $row['city_id'];
$city_name = $row['city_name'];
$city_name_value = str_replace("&"," and ",$row['city_name']);
echo "<option value='$city_name_value'>$city_name</option>";
}
?>
</select>
</div>
<div class="input-group col-lg-4 col-md-12 col-sm-12 search">
<label>Dates</label>
<select name="date_1" id="date_1">
<option value="">Any Day</option>
<?php
for($i=0;$i<31;$i++){
$i = str_pad($i,2,"0",STR_PAD_LEFT);
echo "<option value='$i'>$i</option>";
}
?>
</select>
<select name="date" id="date">
<option value="">Any Month</option>
<?php
for ($i = 0; $i <= 36; $i++) {
$time = strtotime(sprintf('+%d months', $i));
$value = date('Y-m', $time);
$label = date('F-Y', $time);
$label = str_replace("-", " ", $label);
echo "<option value='$label'>$label</option>";
}
?>
</select>
<input type="hidden" id="datepicker">
</div>
<div>
<button type="submit" name="search" class="search_button_nav btn btn-info">
<span class="glyphicon glyphicon-search"></span></button>
</div>
</div>
</form>
What I need to achieve is when the user doing a search to get these URL parameters and use these to change my select options based on their choices.
e.g If they search for country United Kingdom on search page my dropdown on countries to display United Kingdom instead of Any Destination.
I tried to do that with php $_GET but I am not sure is a good idea, because my country list is really big and I can create for every country if(issets($_GET)=='United Kingdom)' etc..
Is that something can complete with javascript without have to check the query of url like i tried with php?
I seach for solution and I find on other posts that (window.location); probably can help me.
I tried to console.log(window.location) and I can see the parameters, but how can I split them properly and use them with php?
Any feedback would be helpful.
P.S My url is looking like this one : nameofmysite/search.php?country=+United+Kingdom&chk=1&city_name=%25date_1=05&date=July+2018
I am not sure whether I understand your problem If you just want to set the dopdown-item to the city the user is searching for, using $_GET is no bad idea. You just have to check whether the parameter is given, then you can use it in PHP.
if(isset($_GET['search'])) {
echo "<option value='".$_GET['search']."'>".$_GET['search']."</option>";
} else {
echo "<option value=''>Any destination</option>";
}
I think you are trying to mix the use of the parameter.
Once the request is sent, the server will process that request and interpret the PHP page in the server before send it to the client (the browser). If you need to check a parameter then you can get it with the global variable $_GET and do whatever you want and build your page conveniently.
Get request parameters from URL in PHP GET URL parameter in PHP
Once the page is built it is sent to the client wich interpret it and your browser renders it. Then you can get the URL with window.location and parse it conveniently with split method or Regular expressions to get what you want from there.
Get request parameters from URL in Javascript How to get URL parameters with Javascript?
But the page is already rendered and what you can do then is manipulate the DOM of the page.
How to display form inputs without loosing data entered before refresh the page? I mean After refresh my page I want to display all the values entered in forms.
I have 2 inputs One is select option and one is text.
<input type="text" name="worked_month" value="<?php echo $_SESSION['worked_month']; ?>" />
<select name="sex">
<option value="">Select Sex</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
I am using following PHP code to display text enter before I refresh the page
isset($_POST['worked_month'])?$_SESSION['worked_month'] = $_POST['worked_month']:$_SESSION['worked_month']="";
It works fine but don't know how to select the option that are selected before refresh. But I don't have to always select same default value. User can select any value
Explanation. For each option, check if the post variable matches the value and then use selected attribute to select the matched option.
<select name="sex">
<option value="">Select Sex</option>
<option <?php echo isset($_POST['sex']) && $_POST['sex']=='male'? 'selected="selected"' = '' ?> value="male">Male</option>
<option <?php echo isset($_POST['sex']) && $_POST['sex']=='female'? 'selected="selected"' = '' ?> value="female">Female</option>
</select>
To select option you have to use PHP dynamic variable.Check this reference
<?php
$sex = $_SESSION['sex'];
${$sex.'_checked'} = "selected";
?>
<select name="sex">
<option value="">Select Sex</option><option value="male" <?php echo $male_checked; ?> >Male</option><option value="female" <?php echo $female_checked; ?>>Female</option></select>
Dynamic variable: automatic convert your selected value into variable whose value is "selected".
I just made something like that saving the values at Local Storage and then retrieving them:
//Saving the input values at local storage
var temp = [];
$('.keep-values').each(function(){
temp.push({
id:$(this).attr('id'),
value:$(this).val().trim(),
checked:$(this).is(':checked')
});
});
localStorage['valuesCache'] = JSON.stringify(temp);
Then i retrive the values and i populate the fields:
//Retrieving the values from local Storage and populating the inputs
var tmp = JSON.parse(localStorage['valuesCache']);
for(i in tmp) {
$('#'+tmp[i].id).val(tmp[i].value);
if(tmp[i].checked){
$('#'+tmp[i].id).attr('checked','');
}
}
I think thats a good start for your final solution, read more about Local Storage
i want to pass selected option value in id to codeigniter controller.
<p>
<select id="quantity" name="quantity" tabindex="2" onchange="calculate(this)" required autofocus>
<option value="">Choose Your Quantity</option>
<?php
if($prodqty)
{
foreach($prodqty as $qty)
{
for($i = $qty->quantity_from; $i <= $qty->quantity_to; $i++)
{
?>
<option value="<?=$i?>" id="<?=$qty->discount?>"><?=$i?></option>
<?php } } } ?>
</select>
</p>
i am already getter selected option value, now i want to get id value also i.e. id="discount?>"
function add_cart_prod()
{
if(isset($_POST['submit']))
{
this is controller where i want to get id value
Use ajax call on change event of the selection of the options:
Just Changed your code little :
<select id="quantity" name="quantity" tabindex="2" onchange="calculate(this)" required autofocus>
<option value="0">Choose Your Quantity</option>
<?php
if( !empty($prodqty)):
foreach($prodqty as $qty):
for($i = $qty->quantity_from; $i <= $qty->quantity_to; $i++): ?>
<option value="<?php echo $i?>" id="<?php echo $qty->discount?>"><?php echo $i?></option>
<?php endfor;
endforeach;
endif; ?>
</select>
Your javascript function :
<script type="text/javascript">
function calculate(id)
{
var id=id;
$.ajax({
type:'POST',
url:'your controller/add_cart_prod',
data:{'id':id},
success:function(data){
// the next thing you want to do
}
});
}
</script>
Your Controller Function:
function add_cart_prod()
{
$id=$this->input->post('id',true);
//send this value to your model
}
If you subitted the data via POST, which I suppose, because you test the POST-Array, you should get them this way:
$this->input->get_post('quantity');
But perhaps you used in your HTML the option GET for the form submission, then this should work:
$this->input->get('quantity');
If you want to get both values XSS-clean you should add a second paramenter, which is set to TRUE:
$this->input->get_post('quantity',TRUE);
As discussed below you should change the value of the option to:
<option value="<?=$i?>_<?=$qty->discount?>"><?=$i?></option>
And then explode the array by this char: "_" to get the two values:
$valuearray = explode ( "_" , $this->input->get_post('quantity'));
$valuearray[0] should contain your $i-part and $valuearray[1] the discount.
Important is, that the delimiter-char cannot be a value of either $i or $qty->discount. Otherwise choose a different char
You should try this, maybe it will work, Inside the calculate(this) function:
var discount = $("select[name='quantity'] option:selected").attr('id');
alert( discount );
$("#discount").val( discount ); //this will save the discount value in the hidden field
EDIT:
Put a hidden field in your form to contain the discount value
<input type="hidden" name="discount" id="discount">
Now, submit the form as usual. Hope it helps.
I am using this code I found to try and make this drop down menu.
http://www.javascriptkit.com/script/cut183.shtml
Ignore my variables and values, they are all place holders.
The problem is, it calls the value in Javascript, but I want to call a specific function in PHP depending on what option in the menu you chose.
<html>
<body>
<form name="doublecombo" form action"index.php" method="POST">
<p><select name="example" size="1" onChange="redirect(this.options.selectedIndex)">
<option>Amazon</option>
<option>Apple</option>
<option>Logitech</option>
<option>Nike</option>
</select>
<select name="stage2" size="1">
<option value="http://javascriptkit.com">Kindle Fire</option>
<option value="http://www.news.com">Kindle DX</option>
<option value="http://www.wired.com">Kindle Charger</option>
<option value="http://www.microsoft.com">Kindle Paperweight</option>
</select>
<input type="button" name="test" value="Generate"
onClick="gen()">
</p>
<script>
var groups=document.doublecombo.example.options.length
var group=new Array(groups)
for (i=0; i<groups; i++)
group[i]=new Array()
group[0][0]=new Option("Kindle Fire","http://javascriptkit.com")
group[0][1]=new Option("Kindle DX","http://www.news.com")
group[0][2]=new Option("Kindle Charger","http://www.wired.com")
group[0][2]=new Option("Kindle Paperweight","http://www.microsoft.com")
group[1][0]=new Option("MacBook","http://www.cnn.com")
group[1][1]=new Option("iPhone","http://www.abcnews.com")
group[1][2]=new Option("iPad","http://www.yahoo.com")
group[1][3]=new Option("iMac","http://www.apple.com")
group[2][0]=new Option("G602 Wireless Gaming Mouse","http://www.hotbot.com")
group[2][1]=new Option("G19s Gaming Keyboard","http://www.infoseek.com")
group[2][2]=new Option("G430 Surround Sound Gaming Headset","http://www.excite.com")
group[2][3]=new Option("PowerShell Controller","http://www.lycos.com")
group[3][0]=new Option("Nike FuelBand","http://www.nike.com")
var temp=document.doublecombo.stage2
function redirect(x){
for (m=temp.options.length-1;m>0;m--)
temp.options[m]=null
for (i=0;i<group[x].length;i++){
temp.options[i]=new Option(group[x][i].text,group[x][i].value)
}
temp.options[0].selected=true
}
function gen(){
location=temp.options[temp.selectedIndex].value
}
</script>
<?
function kindlegen(){
?>
<textarea name="message" placeholder="CODES" rows="10">
<?
{ $amount = "5"; $i = 1; while ($i <= $amount)
{ $rand_letter1 = substr(str_shuffle("123456789"), 0, 2); $ran = rand(1, 6); echo "D0FB A0A0 343".$ran." 0A".$rand_letter1."\n"; $i++; } } ?>
</textarea>
<?
}
?>
</form>
</html>
</body>
PHP is executed server side, HTML and Javascript client side.
This means no, there is no way you can execute PHP inside your Javascript (never ever).
You can only post information back to the server, via ajax, which allows you to make further operations. When these are finished on the server, your ajax call receives the result and returns it back to the client for further processing.
I have a problem with my javascript. First of all here is my code partitions:
<select class="inputTxt" style="width: 120px;" id="yearCombo" name="yearCombo">
<option value="0">2013</option>
<option value="1">2012</option>
<option value="2">2011</option>
</select>
function searchClicked() {
var operationField = document.getElementById("<%=FeedbackReportCtrl.PARAM_OPERATION%>");
operationField.value = "<%=FeedbackReportCtrl.OPERATION_SEARCH%>";
var yearFilter = document.getElementById("<%=FeedbackReportCtrl.PARAM_YEARFILTER%>");
yearFilter.value = document.getElementById("yearCombo").options[document.getElementById("yearCombo").selectedIndex].text;
var mainForm = document.getElementById("main");
mainForm.submit();
}
Here what goes wrong is the following;
For example, when I choose the year 2011 from the combo box and then hit the search button, it brings me the desired results;however, the selected index of the box returns back to 2013. How can I sustain my selection after search function?
The issue you have isn't a javascript one. When you submit a form you refresh the whole page, removing any client-side (user or javascript) adjustments to it.
It should be set by the php/java that is generating the page you post your form to, to set a selected="selected" or relevant, based on the value you just posted.
In php this would be
if($_POST['year'] == '2013') echo ' selected="selected"';
In java or jsp there are similar ways of doing this. Javascript itself could do the same probably.
Submitting the form refreshes the page (unless done via AJAX), thus returning to the default selected value, i.e the first one.
To overcome this you need to send along with the form the chosen year - assuming that you are self-submitting - and explicitly mark this year as the selected option.
In PHP Your code would then be something like:
<?php $year = $_POST['year']; ?>
<select class="inputTxt" style="width: 120px;" id="yearCombo" name="yearCombo">
<?php for ($i=2013;$i>2010;$i--): ?>
<option value="<?php echo $i; ?>" <?php if ($year==$i) echo "selected"; ?> >
<?php echo $i; ?>
</option>
<?php endfor; ?>
</select>