jQuery change the value of a variable on dropdown select from database - javascript

I am working on a project where I am stuck at a point right now. I need to change the value of a DIV live on select of the dropdown using jQuery.
Example:
I want this:-
<select name="">
<option value="10">10 clicks</option>
<option value="20">20 clicks</option>
<option value="30">30 clicks</option>
<option value="40">40 clicks</option>
</select>
<div id="chpln">Clicks: 0 clicks</div>
When I will select option 1 the value will be displayed in place of 0 in DIV live. The problem is that as this select value fetches data from the database I am not understanding how to do it.
Example:
<select name="" id="pln" class="select-box" style="margin-top: -40px;" />
<?php while($ac_fetch = mysql_fetch_array($qur_ac)){ ?>
<option value="<?php echo $ac_fetch['adclk_clicks']; ?>"><?php echo $ac_fetch['adclk_clicks']; ?> clicks</option>
<?php } ?>
</select>
jQuery that I used currently:-
$(document).ready(function(){
$("#pln").click(function(){
$("#chpln").text("Plan: <?php echo $ac_fetch['adclk_clicks']; ?> secs");
});
});
This jquery is changing the value currently but I am getting only the first value of the database i.e., 10. When I choose different option it still displays the first value from the database i.e., 10 while it should actually display the second value that is 20. Please help me. FIDDLE will be appreciated.

click is a wrong event for selection box
you can utilize change event for your result.
$(document).ready(function(){
$("#pln").change(function(){
$("#chpln").text("Plan: "+$(this).val()+" secs");
});
});

For Dropdown, click(function() is not applicable. Use change(function().
I gave you 2 way. Use any one.
I) Method - 1 (Using Ajax)
<select name="" id="pln" class="select-box" style="margin-top: -40px;" />
<?php while($ac_fetch = mysql_fetch_array($qur_ac)){ ?>
<option value="<?php echo $ac_fetch['adclk_clicks']; ?>">
<?php echo $ac_fetch['adclk_clicks']; ?> clicks
</option>
<?php } ?>
</select>
<div id="chpln">Clicks: 0 clicks</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$('.select-box').change(function(){
var selectBoxClicks = $('.select-box').val();
$.ajax({url:"AjaxShowClickValue.php?selectBoxClicks="+selectBoxClicks,cache:false,success:function(result){
$('#chpln').html(result);
}});
});
</script>
Create a new page, namely AjaxShowClickValue.php.
AjaxShowClickValue.php (Make Sure, if you changing page name here. Then, change in <script></script> tag too. Both are related.)
<?
echo "Clicks: ".$_GET['selectBoxClicks']." clicks";
?>
II) Method - 2
<select name="" class='select-box'>
<option value="10">10 clicks</option>
<option value="20">20 clicks</option>
<option value="30">30 clicks</option>
<option value="40">40 clicks</option>
</select>
<div id="chpln">Clicks: 0 clicks</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$('.select-box').change(function(){
$("#chpln").text("Clicks: "+$(this).val()+" clicks");
});
</script>

use jQuery Ajax for making request to the php file..
and use on .change() rather than .click() for changing the dropdown value..
the code will be placed in JS file which make ajax call to the php file on your server..
The php file will takes some params (if any) and perform select query to the databases and return result in response.. in php use json_encode(data) for that..
These examples may also help:
http://www.plus2net.com/php_tutorial/ajax_drop_down_list.php
http://www.plus2net.com/php_tutorial/php_drop_down_list.php
You will find many other examples - Just Google It and understand the key concept!
Hope this helps.

Related

PHP Echo SUM session value & form select

I have a PHP echo statement of a session value like this:
<?php echo $userinfo['RenewAgreementAmount'] ;?>
I have a form select element like this:
<select id="Lock" name="Lock">
<option value="1" selected="selected">1 Year</option>
<option value="2">2 Years</option>
<option value="3">3 Years</option>
<option value="4">4 Years</option>
</select>
I'm trying to update the <?php echo $userinfo['RenewAgreementAmount'] ;?> output by taking what the user selects in the select value id Lock with this session value while interacting with the form?
I've tried <?php echo ($userinfo['RenewAgreementAmount'] * #Lock) ;?> with no luck.
What is the easiest way to update this value as the user interacts with the select form input in real time?
<script>
renewAmount = <?= $userinfo['RenewAgreementAmount']; ?>
function calc(year){
var amount = renewAmount*year;
// here you can perform an ajax request to update the amount on server
}
</script>
<select id="Lock" name="Lock" onchange="calc(this.value)">
<option value="1" selected="selected">1 Year</option>
<option value="2">2 Years</option>
<option value="3">3 Years</option>
<option value="4">4 Years</option>
</select>
it's because your PHP is interpretted before your HTML. That's the whole point of PHP. One way you can work around that is to store your $userinfo['RenewAgreementAmount'] into a Javascript variable and works with this variable. EX:
<script>var RenewAgreementAmount = <?php echo $userinfo['RenewAgreementAmount'] ?></script>
And then, you can put the value of the newly created RenewAgreementAmount javascript variable where you want to show it using :
<span id="renewAgreementAmountField"></span>
<script>
document.getElementById("renewAgreementAmountField").innerHTML = RenewAgreementAmount
</script>
You can then work with your variable and change the value.
RenewAgreementAmount = RenewAgreementAmount * document.getElementById("Lock").value;
If you want to update the value on the server side, you can use an AJAX request ( XMLHttpRequest in plain Javascript) with your new variable.
Ok so you have this dropdown and you want to get the real-time options everytime something is selected:
$('#Lock').on('change',function() {
var option
option = $('#Lock').val()
$.ajax({
type: 'post',
url: "your_php_file.php",
dataType: 'data',
data: {
option: option
}
})
})
This code will get the value every time a value is selected from this dropdown and will make an ajax call to your php class that you want to handle. your php class name should be put in the url: field
After that in your php you just retrieve the data like this:
$option=$_POST['option'];
Well this means that you execute an ajax call everytime something is selected. I propose that you put a button and trigger the ajax when the user clicks the button, so setup and onClick event.
Don't forget in your html-head to include the jquery version :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
Approach using some jQuery, would be something like this--
<?php
session_start();
$_SESSION["RenewAgreementAmount"] = 50;
?>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
</head>
<body>
<select id="Lock" name="Lock">
<option value="1" selected="selected">1 Year</option>
<option value="2">2 Years</option>
<option value="3">3 Years</option>
<option value="4">4 Years</option>
</select>
<script>
$(document).ready(function() {
$("#Lock").bind("change", function(index){
var value = $(this).val();
//console.log("Changed to: " + value);
$.post("updateSessionValue.php". {"newVal": value});
});
});
</script>
</body>
</html>
For updateSessionValue.php page:
<?php
session_start();
$_SESSION["RenewAgreementAmount"] = $_POST["newVal"];
Obviously, just an example code... make sure to take all the necessary security precautions!

set selected value of <select> into what I choose lat time before submitting the form

Here's the process I want to realize:
1.on index page, select one option from the list of items;
2.submit form,directing to the index page ;
3.select label showing the default value which equals what I chose in step 1.
e.g.
<html>
<select>
<option value="1">1<option/>
<option value="2">2<option/>
<option value="3">3<option/>
</select>
</html>
On index page if I chose 1 ,and submit it and the page is submitted to itself(the index page).Now,on the index page, <option value="1">1<option/> is selected by default.
I don't know which correct direction I should go and I haven't found any solutions from the Internet yet.Anybody has any ideas??
Thanks a lot!
Using PHP function and javascript onchange:
<html>
<?php
if (isset($_POST["myselect"])) {
$myselect = $_POST["myselect"];
}
else {
$myselect = 1;
}
function isselected(A,B) {
if ($A == $B){
return "selected";
}
else{
return false;
}
}
?>
<form action="index.php" method="post">
<select name="myselect" onchange="this.form.submit();">
<option value="1" <?php echo isselected(1,$myselect) ?> >1<option/>
<option value="2" <?php echo isselected(2,$myselect) ?> >2<option/>
<option value="3" <?php echo isselected(3,$myselect) ?> >3<option/>
</select>
</form>
</html>
1st : Name attribute is must for form elements .otherwise element value would not passed to server.
2nd : Check the post value and add the selected attribute for that option like below .
<select name="select1">
<option value="">Select</option>
<option value="1" <?php echo (isset($_POST['select1']) && $_POST['select1']==1 )? 'selected':''; ?>>1</option>
<option value="2" <?php echo (isset($_POST['select1']) && $_POST['select1']==2 )? 'selected':''; ?>>2</option>
<option value="3" <?php echo (isset($_POST['select1']) && $_POST['select1']==3 )? 'selected':''; ?>>3</option>
</select>
coudn't understand your question quite well but..If you want to select any other value by default, once the page comes back to the index page, you will have to send the selected value back to the index page.
<html>
<select>
<option value="1">1<option/>
<option value="2" selected="selected">2<option/>
<option value="3">3<option/>
</select>
</html>
The above would select option 2, so you just have to set it accordingly.

PHP variable falls outside the scope of Javascript, how do I get it in the scope?

I'm trying to make a dropdown in HTML, but I want to have it's default value to be determined by the value of a PHP variable. I wanted to do it with JavaScript, but I end up with the famous "Uncaught ReferenceError: $ is not defined" error :/.
PHP:
while(list($ArtikelID, $Type) = mysql_fetch_array($result))
{
$arid = $ArtikelID;
$te = $Type;
}
HTML + JS:
<form name="send" method="post" action="editartticlesdef.php">
articlenumber: </br>
<input readonly="readonly" name="ArticleID" value=<?php echo $arid ?>></br>
Type: </br>
<select name="Type">
<option value="Article">Article</option>
<option value="Code">Code</option>
<option value="News">News</option>
<option value="Project">Project</option>
</select></br>
<script>
document.getElementById("Type").selectedIndex = <?php echo '$te'; ?>;
</script>
</form>
I tried to place the script on other places on the page but had no success :/. I suspect the variable falls outside the scope, but I don't know how to get it back in :/.
It should be -
<select name="Type" id="Type">
And
document.getElementById("Type").selectedIndex = '<?php echo $te; ?>';
Provided $te is an integer between 0 and 3, then you need to:
Give your select an id attribute:
<select name="Type" id="Type">
<option value="Article">Article</option>
<option value="Code">Code</option>
<option value="News">News</option>
<option value="Project">Project</option>
</select>
remove the quotes areound the php variable itsself and place them in the html:
<script>
document.getElementById("Type").selectedIndex = "<?php echo $te; ?>";
</script>
Sorry for not answering the question, but you should not use mysql_, it's deprecated and unsafe (See PHP Manual). Use MySQLi or PDO.

Enable field when selecting from drop-down box

My contact form page, for user edit details, has two drop-down fields, ‘country’ and ‘city’.
I would like when a user is edit his details that the ‘city’ field will be disabled until something is selected in the ‘country’ drop-down menu.
<form name="item" action="<?php echo base_url(true) ?>" method="post">
<label><?php _e('Country', 'my_theme'); ?></label>
<?php ItemForm::country_select(get_countries(),user()) ; ?>
<label><?php _e('City', 'my_theme'); ?></label>
<?php ItemForm::cities_select(get_cities(),user()) ; ?>
<button class="itemFormButton" type="submit"></button>
</form>
I’ve tried ‘onchange’ in javascript, probably with wrong syntax…
How can I create this?
Thx.
This might help you http://jsfiddle.net/GZ269/. This uses jquery.
Country:<br />
<select id="drop1">
<option value="">Select Country</option>
<option value="c1">Country 1</option>
<option value="c2">Country 2</option>
</select>
<br />
City:<br />
<select id="drop2" disabled >
<option value="">Select Country</option>
<option value="c1">Country 1</option>
<option value="c2">Country 2</option>
</select>
Javascript function:
$("#drop1").change(function(){
var country = $(this).val();
if(!country){
$("#drop2").attr("disabled", true);
return false;
}
$("#drop2").attr("disabled", false);
});​
You should do this with Javascript's onchange event, and when this event is fired, you have two options:
Query the cities for the country selected with ajax.
This is good if you support (almost) all the countries in the world.
Here you must develop a PHP script to be queried when this event is fired.
Have a great array with the cities for all the countries supported.
Too bulky if need you to cover many countries.
Less flexible, if you need to add more cities for any country.

Send form based on html select error

I have a select form that sends the value when you change the select. Unfortunately, everytime it sends it goes back to the option "10". How can I have it (for example) so you can click on the 20 option and send form and stay on 20?
Here is the code:
<form method='get' name='FormVote'>
<select name="vote" onChange="document.forms['FormVote'].submit()">
<option selected="selected" value='10'>10</option>
<option value='20'>20</option>
<option value='30'>30</option>
<option value='40'>40</option>
</select>
</form>
Any help will be greatly appreciated! Thanks!
it's staying on 10 because of the
selected="selected"
attribute in the option for 10
To have it remember where the user put it you'll need to fetch its value from the database and then do something like this in PHP:
foreach ($optionsArray as $option) {
echo '<option ';
if ($theOptionValue == $savedUserOptionValue)
echo 'selected="selected"';
echo 'value="', $theOptionValue, '>', $theOptionValue, '</option>';
}
Or you could use AJAX to send the form to the server in which case the page won't refresh and the option box will stay where it is.
Use Ajax or,
<form method='get' name='FormVote' target='hidden'>
<select name="vote" onChange="document.forms['FormVote'].submit()">
<option selected="selected" value='10'>10</option>
<option value='20'>20</option>
<option value='30'>30</option>
<option value='40'>40</option>
</select>
</form>
<iframe name='hidden' id='hidden' style='display:none' width='0' height='0' border='0'></iframe>

Categories