I have a table displaying data from the database. I have a select box where the person can select the currency in which he wants the data to be displayed.
When he does so, i need the data to be refreshed and displayed as the new currency. And I can't figure out how to do so without refreshing the whole page.
Any ideas please?
<select id="currency">
<option value = "rub">В рублях</option>
<option value = "usd">USD</option>
<option value = "eur">EURO</option>
</select>
<table id="servers" cellpadding="0" cellspacing="0">
<tr>
<td width="400"><b>Сервер</b></td>
<td width="100"><b>1 кк адены</b></td>
<td width="100"><b>1 ккк адены</b></td>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `prices`");
while($r = mysql_fetch_array($sql)) {
echo("\t\t<tr>\n");
echo("\t\t\t<td>".$r['name']."</td>\n");
echo("\t\t\t<td>$".round($r['kk']/$dollar, 2)."</td>\n");
echo("\t\t\t<td>$".round($r['kkk']/$dollar, 2)."</td>\n");
echo("\t\t</tr>\n");
} ?>
</table>
You can use Ajax, which allows to request the DB and retrieve the data without refreshing the whole page.
Here is an introduction : http://www.w3schools.com/jquery/jquery_ajax_intro.asp
Then, have a look to the jquery API and take a look at the examples : http://api.jquery.com/jQuery.ajax/
Good luck
If you can hold factors for data transformation (for conversion USD>AUS USD>EUR or whatever) you can delegate the change throughout the table by using one general selector.
first you place all the factors in the js vars like this(this must be doe inside php file and other stuff can be done in separated js):
var USDtoEUR = <?php echo $php2eur; ?>
Next thing you do, you bind event to click on the select box, button or whatever, let's say it is select with id "currency":
$('#currency'). click(function() {
switch ($('this').val()) {
case 'EUR' {
//Code we will discuss is going here
}
break;
//... etc...
So, we want to change all the data we are assuming is in USD on click, so we have all the factors to convert from usd to other values stored in separate vars USDtoXXX. Note that we need one USDtoUSD, too.
Now... Whatever the structure is, the element containing dynamically changed data should have class and inusd attributes like this:
<li class="price" inusd="123">123</li>
th price in usd should be stored to an attribute to keep it independant from the dom content that will change.
so for the above example we do this:
$('.price').each(function() {
$(this).text()=$(this).attr('inusd')*USDtoEUR; //If user selected EUR
}
Be carefull to use breaks and default in the switch statement... javascript switch lets cases drop their conditions through.
Also, when working with money, please do the in depth testing of the calculating functions, javascript can mess that upp, too, from time to time :D
Related
Basically, it's a form that needs specific information, "Tamanho"/"Tamanhos" means "size"/"sizes", which I have a list of acceptable sizes that goes from 8 to 30 that are registered in a database (to make it easier to add more acceptable sizes if needed), the user should be able to chose many "sizes" and put a quantity of "how many products of that size?" in an input right after it.
I was able to create an JavaScript function AddTam() called by a button that generates one more block to fill, with a select, and all the block's select inputs are named Tam[], so their values pass as an array, and their respective inputs named as "TamQnt8", the number 8 at the end refers to the size chosen, it changes every time the user chooses other size for the same block using other function DefTam(), that way, I could verify the sizes array in the Back-End, and use it to get their respective quantities and organize it all in an array, to finally send it to the database.
But for some reason, when I test if the information is passing through correctly, it doesn't send any data in the key "Tam" saying it's undefined when I tested it, in PHP I'm testing: if(!empty($_POST['Tam'])) but i also tried isset().
I just don't know what's wrong, so I was asking if isn't it the method I'm using insertAdjacentHTML() to generate the blocks, and if it works as well as createElement() in forms.
Also, when I created the blocks manually and instead of many selects I used checkboxes, it was working, just decided to change to the generated method because the checkboxes took way too much space in the screen, even worse for mobile.
Here's a simplification of the code in HTML:
<form method="post">
<section>
<div class="littlebutton" id="addTamanho" onclick="AddTam()">Add Tamanho</div>
</section>
<script>
var contador = 0;
function AddTam(){
let tamTitulo = document.querySelector('#addTamanho');
tamTitulo.insertAdjacentHTML("afterend",
'<div class="cellTam cell">'+
'<select name="Tam[]" class="'+contador+'tam8 '+contador+'" onchange="DefTam(this)">'+
'<?php foreach ($_SESSION["tamanhos"] as $key => $value) { ?>'+
'<option value="<?php echo $value["tamanho"];?>"><?php echo $value["tamanho"];?></option>'+
'<?php }?>'+
'</select>'+
'Tem => <input class="qnt" id="'+contador+'tam8" name="TamQnt8" type="number" min=1>'+
'</div>');
contador++
}
function DefTam(ElementTam){
let infoTam = ElementTam.value;
let refTam = ElementTam.getAttribute("class");
refTam = refTam.split(" ");
let relInput = document.getElementById(refTam[0]);
ElementTam.setAttribute("class", refTam[refTam.length-1]+"tam"+infoTam+" "+refTam[refTam.length-1]);
relInput.setAttribute("name", "TamQnt"+infoTam);
relInput.setAttribute("id", refTam[refTam.length-1]+"tam"+infoTam);
}
</script>
<button class="post" name="Inserir" type="submit">Postar</button>
</form>
Output: The Add Tamanho button, 3 generated blocks of the form and the Elements tab of browser's Developer tools
Sorry if I wrote something wrong or weirdly, still learning English, or if it's just a silly mistake in my code, also, any help is welcome.
I did some research already but can't find a good solution to this. I am sure it's simple, but I could use some help.
I am using HTML -> Javascript -> PHP to get info back from a database.
My goal is to have the data return, but have it add check boxes at the end of each row where if the person check it, it will add them to another table.
In my example, it will return a list of cards and if the person uses the check box it will add each card they checked to a "have" list. For my code provided below, it's a "display all" so I didn't use any javascript. I put it straight from html to php. I figure if I can get the most simple example working, adding the js to my other search display will be easy.
HTML
<fieldset>
<form action="display_all.php" method="post">
Order by: <select name="order_all" id="order_all">
<option value="parallel">Parallel</option>
<option value="faction">Faction</option>
</select>
<input type="submit" value="display all cards">
</form>
</fieldset>
PHP (to save space I cut out some of the standard code)
$order_all = $_POST['order_all'];
// Create SQL statement
$query = "SELECT * FROM cards ORDER BY $order_all ASC";
// Execute SQL statement
if (!($result = # mysql_query ($query, $connection)))
showerror();
// Display results
while ($row = # mysql_fetch_array($result)) {
echo "<tr><td>{$row["parallel"]}</td>
<td>{$row["faction"]}</td>
<td>{$row["in_set"]}</td>
<td>{$row["card_name"]}</td>
<td>{$row["color"]}</td>
<td>{$row["number_in_set"]}</td>
<td>{$row["rarity"]}</td>
<td>{$row["sold_out"]}</td>
<td>{$row["series"]}</td>
</tr>";
}
I tried adding different things to the while { } at the end of the PHP file but I don't really know the proper way to do that. Based on what I saw around, people suggest doing this in javascript and creating a function for it. Start with my ajax call and callback? I planned on linking my checkboxes to the ID of each card (which is stored in the database, but not printed) I figure they will just be linked to query insert commands. Like if check [ insert command ] and form submit? idk looking for some suggestions, I am still new to using databases in this sort of way.
FOUND A SOLUTION TO MY PROBLEM, well sorta.
It was a bunch of little things. I haven't added functionality, but I at least got the checkbox to show up.
while ($row = # mysql_fetch_array($result)) {
echo"
<tr>
<td>{$row["parallel"]}</td>
<td>{$row["faction"]}</td>
<td>{$row["in_set"]}</td>
<td>{$row["card_name"]}</td>
<td>{$row["color"]}</td>
<td>{$row["number_in_set"]}</td>
<td>{$row["rarity"]}</td>
<td>{$row["sold_out"]}</td>
<td>{$row["series"]}</td>
";
echo'<td><input type="checkbox" value="submit" id="{$row["id"]}/></td>';
echo"</tr>";
}
Your code is paradise for SQL injection! You have to check user input, at least escaping with mysql_real_escape_string or
Switch to newer, better and safer mysqli (or PDO) interface and use prepared statements. I recommend mysqli anyway.
Note: in this particular case is best to use switch with options.
To question: why don't you get checkbox value from post and then take actions, but I'm not sure what are you asking.
I'm trying to find the best way to make my teachers' lives a little easier.
I've got a select field and list of options generated by a tlist sql query. The select field itself already has a javascript attached to it, which fleshes out other field values (credit values and credit types) elsewhere based on the id of the select option chosen. This is the javascript that works for that purpose:
<script type="text/javascript">
function changeValue(){
var option=document.getElementById('courseno').value;
if(option=="E100"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngFresh";
}
else if(option=="E200"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngSoph";
}
}
</script>
I also need to populate a hidden field that is (and must remain) outside the tlist sql tag that generates the select list.
Here is my sql code:
<select id="courseno" name="course_number" onchange="changeValue();">
<option value="">Select a Course</option>
~[tlist_sql;
SELECT cc.course_number, cc.section_number, c.COURSE_NAME
FROM cc cc
RIGHT JOIN COURSES c ON c.COURSE_NUMBER = cc.course_number
RIGHT JOIN STUDENTS s ON cc.studentid = s.id
WHERE cc.studentid = ~(curstudid)
AND TERMID = ~(curtermid)
AND c.CreditType LIKE 'English%'
AND NOT EXISTS (
SELECT * FROM storedgrades sg
WHERE sg.studentid = ~(curstudid)
AND sg.course_number = c.course_number
)
ORDER BY c.course_name;]
<option name="~(course_no)" value="~(course_no)" id="~(secno)">~(course_no).~(secno) (~(cname))</option>
[/tlist_sql]
</select></td>
</tr>
And just below that is the hidden field I would like to populate:
<td width="25%" class="bold"> </td>
<td><input type="text" id="secnum" name="section_number" value=""> </td>
I gave each of the options the section number as its ID, thinking I could use the ID element of each of those options and some clever jquery to populate the hidden field, but I'm having no luck. I just read on another question that was ably answered by the community that you shouldn't use an option ID tag that begins with a number... so now what can I do?
Could somebody please help me?
Thanks forever,
Schelly
I don't think your problem comes from the ID being a number. We haven't seen what jQuery you've tried, but you most likely don't need jQuery at all. Assuming what you have is working correctly, and the PowerSchool code is putting out elements the way you expect them to be (View Source in your browser to be sure, if this doesn't work), you should be able to grab the ID from the selected option inside your changeValue function, store it in a variable, and push that value into the "secnum" field as follows:
function changeValue(){
var courseDropdown = document.getElementById('courseno');
var selectedElement=courseDropdown.options[courseDropdown.selectedIndex];
var option=selectedElement.value;
var courseNo = selectedElement.getAttribute("id");
if(option=="E100"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngFresh";
}
else if(option=="E200"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngSoph";
}
document.getElementById('secnum').value=courseNo;
}
I changed the way that your "option" variable is being set, but it will work the same way. You might end up wanting to move the last line, where the "secnum" field is being set, or wrap it in an "if", etc.; I don't know your full requirements.
All that said, there would be nothing wrong with using jQuery in this situation, but it's not necessary in this case unless you need extreme backwards-browser compatibility.
Working Example Here
You can use multiple on change events to do whatever you want. On change add a new event and populate the hidden input. You can define custom attributes to any html element with any data that is required to populate the hidden input
<select id="myselect">
<option>Select</option>
<option data-number="1">One</option>
<option data-number="2">Two</option>
<option data-number="3">Three</option>
<option data-number="4">Four</option>
<option data-number="5">Five</option>
</select>
<input type="hidden" id="hiddenInput"/>
$(document).ready(function(){
$('#myselect').on('change', mySelectChange);
function mySelectChange(){
console.log('your standard change value here');
}
$('#myselect').on('change', mySelectChange2);
function mySelectChange2(){
var option = $("#myselect option:selected");
console.log(option.text());
console.log(option.attr('data-number'));
}});
I have this rather tricky problem to solve whereby I have used the following to display a list of named shops with ID number for selection from a drop down list when creating a new employee record. This works well at this point. A piece of javascript splits the displayed text from the the user selection and sends the shop ID number off with the new employee details to be inserted into the employee table in the database. I am using a hidden shopID text box to store the number as can be seen in the javascript.
Here is the code PHP first then javascript:
$result = mysqli_query($link,"SELECT shopID, shopName FROM SHOP");
echo "<br><select class='formInput' name='listbox' id='listbox' onchange='captureShopID()' tabindex=9>";
#Use onchange instead of onclick where Keyboard is used. onclick does not register changes fro keyboard
while($row = mysqli_fetch_array($result))
{
$shopID = $row['shopID'];
$shopName = $row['shopName'];
$allText = "$shopID, $shopName";
echo "<option value='$allText'>S00$shopID $shopName</option>";
}
echo "</select>";
AND (including this, because it may contain hints to a solution for my problem)
<script>
function captureShopID()
{
var sel = document.getElementById("listbox");
var result;
result = sel.options[sel.selectedIndex].value;
var shopNumber = result.split(',');
document.getElementById("shopID").value = shopNumber[0];
}
</script>
OK. So all good so far. What I am trying to do is use the same set up for amendments to the same record. So the update layout is similar to the one for creating the record. I have the list element again but what I would like is to have it showing the shop that the employee works at otherwise it is confusing as the list defaults to the first item in the list, in most cases not the actual shop that the employee works in.
So, instead of:
S001 London
Maybe it should be:
S003 Paris… Where the employee works.
I have tried various things but it is a tricky one. The fact that there is the option value concatenation of $shopID and $shopName may be complicating things a bit in my quest for a solution.
Pretty new to PHP and javascript (javascript pretty mysterious) and programming as a whole. Learning quickly but suffer many days of brain cell overload.
Any pointers in the right direction appreciated.
My Solution… After some outside the box tangental thinking working on some other aspects of my project.
<?php
include "../db.php";
$result = mysqli_query($link,"SELECT shopID, shopName FROM SHOP");
echo "<br><select class='formInput' name='listbox' id='listbox' onchange='captureShopID()' tabindex=9>";
#Use onchange instead of onclick where Keyboard is used. onclick does not register changes from keyboard
echo '<option>Works at:'.$shopName.'</option>';
while($row = mysqli_fetch_array($result))
{
$shopID = $row['shopID'];
$shopName = $row['shopName'];
$allText = "$shopID, $shopName";
echo "<option value='$allText'>S00$shopID $shopName</option>";
}
echo "</select>";
?>
I achieved what I wanted by adding the extra to the top of the list outside the loop to act as the default item listed:
echo 'Works at:'.$shopName.'';
This has the result of presenting the update employee record so that shop from their record is what you see in the menu like so:
Works at: London Southwark
And the list pops up to show the other shop options
Works at: London Southwark
S001 DISTRIBUTION CENTRAL Paris
S002 Paris Montmartre
S003 London Southwark
S004 Roma Trastevere
and so on.
Not exactly what I initially intended but just as good
I am aiming for a clean and spasre interface without too many labels and this solution makes the list element self explanatory.
If any one has a good suggestion for the thread title please post as this one is quite useful.
I'm going to use Joomla K2 component as a directory system only, So just show Extra-Fields in front-end contents.
Therefore in the K2 item submission form which is available to registered users, I tend to remove all further inputs (including content tab and its huge textarea for writing post, attachment tab, title input, publish radio buttons and so on) and keep extra-fields' inputs only. I tried to do this through k2 template overriding by hiding those inputs using CSS or HTML however it's not a good idea because users are still able to show and see hidden stuff by set display to normal via browsers' developer tools.
Also it isn't possible to achieve this purpose by put those fields in an always false PHP condition since some inputs need to have at least one value, It seems.
Below is the default layout of K2 submission form in user section, Red areas are those I want to make them removed and inactive:
And here's the source of default layout:
com_k2/templates/default/itemform.php
By hiding category input from users, I also need to set a predefined category which all contents that users submit would apply to it and Extra-fields related to that category are shown to users in submission form.
Is there any way to define a value in template overriding files and hide its related field completely? (It's better to be by variable but constant would work too). I would need it to Auto title assignment for item submitted by users too (However it's not as necessary as
other things)
All these change would be in K2 adding item form in front-end site and not Admin section.
What's the workaround to this all?
Regards
I know this question is old but this is my idea, I did something similar, not exactly the same.
Because you can't submit the form if you remove the required fields like Category or Title, you can put a hidden INPUT field with a random value, as long as it is not empty value. In your override file templates/YOUR TEMPLATE/html/com_k2/default/itemform.php instead of showing category selection:
<tr>
<td class="adminK2LeftCol">
<label><?php echo JText::_('K2_CATEGORY'); ?></label>
</td>
<td class="adminK2RightCol">
<?php echo $this->lists['categories']; ?>
</td>
</tr>
You use something like this
<input type="hidden" id="catid" name="catid" value="-1">
Yes naughty users can use Firebug to put their values in that INPUT, but you still can build a plugin and listen to onBeforeK2Save event then set your default value of category to your own value (0, 1 , 2 anything) before saving the content to database. By using this way, you can generate title for your K2 item too.
<?php
defined('_JEXEC') or die ;
JLoader::register('K2Plugin', JPATH_ADMINISTRATOR.'/components/com_k2/lib/k2plugin.php');
class plgK2MyExample extends K2Plugin
{
var $pluginName = 'myexample';
var $pluginNameHumanReadable = 'My Example K2 Plugin';
function onBeforeK2Save(&$item, $isNew)
{
$item->catid = 10000;
$item->title = 'my own title';
}
}
Check the example plugin here: https://github.com/joomlaworks/example-k2-plugin (onBeforeK2Save is missing in the example plugin).
onBeforeK2Save is called in administrator/components/com_k2/models/item.php ("save" function).