Display Text from Input-Select field - php

I have a form saving to PHP, which includes the following select input:
<label for="category">
<span>Event Type :</span>
<select name="category" id="category">
<option value="1"> Meeting</option>
<option value="2"> Clean Up</option>
<option value="3"> High Priority</option>
<option value="4"> Special Projects</option>
</select>
</label>
The saved that is then displayed on another page, but instead of displaying the option value, I want it to display the text value - ie. "Meeting", instead of "1"
The script that gets the data from the DB is:
// Get markers from XML - (event_data.php)
$.get("./php/event_data.php", function (data) {
$(data).find("marker").each(function () {
var name = $(this).attr('name');
var description = '<p>'+ $(this).attr('description') +'</p>';
var type = $(this).attr('category');
var edate = $(this).attr('edate');
var point = new google.maps.LatLng(parseFloat($(this).attr('lat')),parseFloat($(this).attr('lon')));
create_marker(point, name, description, edate, type, false, false, false, '');
});
});
And is displayed with this:
var eventContent = $('<div class="event-details">' +
'<h3>Event Details</h3><table class="table">' +
'<tr><th>Event Name: </th><td>' + eName + '</td></tr>' +
'<tr><th>Event Date: </th><td>' + eDate + '</td></tr>' +
'<tr><th>Event Type: </th><td>' + type + '</td></tr>' +
'<tr><th>Event Details: </th><td>' + eForm + '</td></tr>' +
'</table></div>'
);

The simplest solution is to make an php array - the key of the array can be the option value(eg. 1, 2, 3...) and the value can be the text that you want to show.
$categories = [1=>"Meeting", 2=>"Clean up"];
echo ($categories[$_GET['category']]);
Depending of the case it can be much better to have your categories into a database. The value of the options to be the id of the category. Using that approach when you need to show the name of the category you can get it from the database by the id.
Note: If you have relations between categories and something else in the database It is better to make One to Many or Many to Many database relations. And then you can use SQL JOIN syntax to select combined rows from different tables.

Related

jQuery how to not adding number every changed

I have an order form. If the user change the packages, the price will be changed.
HTML
<select name="item" id="item">
<option value="i1">Item1</option>
<option value="i2">Item2<option>
</select>
<select name="detail" id="detail">
<option value="d1">Detail1</option>
<option value="d2">Detail2</option>
</select>
<p>Price : <span id="price"></span></p>
The PHP below will send the data gotten from the form
PHP
$item=$_POST["item"];
$detail=$_POST["detail"];
$price=0;
if($item=="p1"){
$price=$price+10;
}
else{
$price=$price+5;
}
if($detail=="d1"){
$price=$price+2;
}
else{
$price=$price+1;
}
// codes for sending the data to database
jQuery below will show the price of the chosen package. I want it to show the price everytime it's changed
jQuery
var item=$("#item").val();
var detail=$("#detail").val();
var price=0;
$("#item").on('change',function(){
if(item=="i1"){
price=price+10;
$("#price").html("$ "+price);}
else{
price=price+5;
$("#price").html("$ "+price);}
})
$("#detail").on('change',function(){
if(detail=="d1"){
price=price+2;
$("#price").html("$ "+price);}
else {
price=price+1;
$("#price").html("$ "+price);}
})
I want : price=price(item)+price(detail). The problem is, if the user change it more than once, it will add the number, althought the PHP will not send the number from jQuery.
Let's say, a user chooses Item1 and Detail2. The price shows 11. But, if the user changes it to Detail1, it will shows 13, etc, and finally, the user chooses Item2 and Detail1. PHP will send 7, but the jQuery will show more than 7. Any idea?
Hi :) You can use this code instead:
For you HTML:
<select name="item" id="item">
<option value="0" disabled selected>Select your option</option>
<option value="10">Item1</option>
<option value="5">Item2<option>
</select>
<select name="detail" id="detail">
<option value="0" disabled selected>Select your option</option>
<option value="2">Detail1</option>
<option value="1">Detail2</option>
</select>
<p>Price : <span id="price"></span></p>
and for your Jquery:
$(document).ready(function () {
$("#item,#detail").on('change',function() {
var item=$("#item").val() || 0;
var detail=$("#detail").val() || 0;
var price = 0;
price = parseInt(item) + parseInt(detail);
$("#price").html("$ "+price);
});
});
The simplest solution is to have one function that calculates the total when either of the values change, meaning it will recalculate the total price every time instead of having two functions affecting the same value. here is my solution below:
// Storage for the item prices
var itemDict = {
"p1": 10,
"p2": 4,
"p3": 0
};
// Storage for the detail prices
var detailDict = {
"d1": 2,
"d2": 5,
"d3": 2
};
$("#item").on('change', function () {
CalcPrice();
})
$("#detail").on('change', function () {
CalcPrice();
})
function CalcPrice() {
var price = 0;
const itemPrice = itemDict[$("#item").val()] || 2; // 2 as a default
const detailPrice = detailDict[$("#detail").val()] || 1; // 1 as a default
$("#price").html("$ " + price);
}
The problem is with these lines:
var item=$("#item").val();
var detail=$("#detail").val();
var price=0;
You are declaring and setting the values globally. And it will get set only once when the page is loaded. So, when you access these variables within the change event of #item and #detail, you are accessing the values from these global variables and doing the math and saving it back! So, the next time any of these change event is fired (that is, if user changes the item or detail from the dropdowns), you are again accessing the values from the global variables which contains the data from the previous calculation!
That's why you were getting wrong values.
So, the solution is to move those three variables to inside each of those change events
(what #JYoThi suggested), like these:
$("#item").on('change',function(){
var item=$("#item").val();
var detail=$("#detail").val();
var price=0;
if(item=="i1"){
price=price+10;
$("#price").html("$ "+price);}
else{
price=price+5;
$("#price").html("$ "+price);}
});
$("#detail").on('change',function(){
var item=$("#item").val();
var detail=$("#detail").val();
var price=0;
if(detail=="d1"){
price=price+2;
$("#price").html("$ "+price);}
else {
price=price+1;
$("#price").html("$ "+price);}
});
This will probably solve your issue for now!
#Vinia and #Cornelis has provided some good solutions too, hope you would be able to understand it on looking at it.
Cheers!

How to make get request with multiple values for one form element

I have a form, whose elements are drop down menus which you can select multiple values from.
For example:
<form class="ui form" id="filterImageForm" action="query.php">
<div class="field" id="species" style="display: none;">
<label>Species:</label>
<select class="ui dropdown multiple" name="species" id="speciesSelect">
<option></option>
</select>
</div>
<input type="submit" class="ui primary button">
</form>
These values are determined by the following code:
function populateSelect(selectName){
// don't cache get request responses
$.ajaxSetup({ cache : false });
// form get request
var data = "request="+selectName;
// send get request to formFill.php which interacts with db
$.getJSON("formFill.php", data, function(response){
// select the select element
var select = document.getElementById(selectName+'Select');
// for each response from db, create new option for select and add the option to the select box
for (var i = 0; i < response.length; i++) {
var opt = document.createElement('option');
if (selectName == 'trapper' || selectName == 'trapper_site') {
opt.innerHTML = response[i].option_id;
opt.value = response[i].option_id;
} else {
opt.innerHTML = response[i].option_id + ' - ' + response[i].option_name;
opt.value = response[i].option_id;
select.appendChild(opt);
}
});
Where formfill.php is a script that queries a database and echoes the result in an array.
So the form will have a list of species to select from as options.
On submit, the form is passed to query.php. However, if more than one species is selected, the url for the php page is something like: http://localhost/query.php?species=Hedgehog&species=Rabbit
How do I submit it so I can use both values, rather than the first value being overwritten by the second (in this case, if I echo $_GET['species'] I get "Rabbit", and the 'Hedgehog' value is lost). Ideally I would have one get value containing an array of species.
Thanks in advance.

Edit Drop-Down List with Json Object

I have category drop-down list in my project e.g
<select name="salescategory_id" id="salescategory_id">
<option value="">Sales Category</option>
<option value="1">HPC</option>
<option value="2">BTY</option>
<option value="3">GRO</option>
<option value="4">OTH</option>
</select>
I have to edit this list with json. I am using the following approach to edit this list and other form fields:
function editamazonresearch(id)
{
$.ajax({
type: "GET",
url: '<?php echo SITE_URL;?>products/list/' + id,
success: function(data){
$("#title").val(json_data_object.data.amazontitle);
options = '<option value="' + json_data_object.Salecategory.id + '">' + json_data_object.Salecategory.salescategory + '</option>';
$("select#salescategory_id").html(options);
$("#usercomment").val(json_data_object.data.usercomment);
}
});
}
But this line of code doesn't give me the desire out put as it removes other option values while editing.
From your javascript it doesn't appear that you are looping over a list of products and adding anything.
You are just replacing the content of the select#salescategory_id with the options string
From your question I would expect something more like
$.each(data, function(k, v) {
option = '<option value="' + v.Salecategory.id + '">' + v.Salecategory.salescategory + '</option>';
$("select#salescategory_id").append(option);
});
in your success method
But without knowing the data structure of the response to your ajax call, its very hard to guess at what you are trying to do

Appending html select box to page that is populated with MYSQL query results

Normally when creating dynamically populated drop-downs I'd use a simple foreach loop as below to get the data:
<select name="region" id="region" tabindex="1">
<option value="">Select a Course</option>
<?php foreach ( $courses as $course ) : ?>
<option value="<?php echo $course->coursename; ?>"><?php echo $course->coursename; ?></option>
<?php endforeach; ?>
</select>
*where $courses = select("SELECT * FROM courses");
etc etc
What I'm not sure is possible is to use this in anything like its current form inside a javascript function such as the one below that I've been using on some forms to append additional input fields per the requirements of the user. This works fine for a text input, for example (and as below I can use it if I type out each input option manually) but I'm not at all sure as to the best way to recreate the PHP/mySQL example above where javascript doesn't get in the way. I've tried to look into whether this could easily be done with AJAX but have not been able to find any examples of what I'm trying to do.
<script type="text/javascript">
var count = 0;
$(function(){
$('p#add_field').click(function(){
count += 1;
$('#container').append(
'<h4>Link #' + count + '</h4>&nbsp'
+'<select id="field_' + count + '" name="fields[]">' + '<option>Select a Course</option>'+'</select>');
});
});
</script>
Many thanks for any advice about the best way to do this.
Update - I eventually managed to answer my own question - solution as per the code below.
<script type="text/javascript">
var count = 0;
$(function(){
$('p#add_field').click(function(){
count += 1;
$('#container2').append(
'<strong>Golf Course ' + count + '</strong>&nbsp&nbsp&nbsp'
+'<select id="field_' + count + '" name="fields[]">' + "<?php foreach ( $courses as $course ) { $name = $course->coursename; ?>"+"<?php echo '<option value=\''.htmlspecialchars($name).'\'>'.$name.'</option>'; ?>"+"<?php } ?>"+'</select><br />')
});
});
</script>

Fill out select box depending on other two select boxes - jquery

I had three drop down menus. Depending on items selected on two lists, the third list should be filled out (ajax post).
This is the html code:
Source Language:
<select name='source_lang' id='source_lang' $dis size='6'>
<option value='en'>EN</option>
<option value='sq'>SQ</option>
.....
</select>
Target Language:
<select name='targ_lang' id='targ_lang' $dis size='6'>
<option value='en'>EN</option>
<option value='sq'>SQ</option>
.....
</select>
Supplier:
<select name='supplier_id' id='supplier_id'>
<option value='1'>Supplier 1</option>
<option value='2'>Supplier 2</option>
</select>
On target and source language change, the supplier select list should be filled out.
Anybody can help me with the jquery? I need to ajax post the source, target language values and as response fill out the supplier select list with the data.
Is this something you're looking for?
$('#targ_lang, #source_lang').change(function(){
$.ajax({
url : '',
method : 'post',
type : 'json',
data : {
select1 : $('#targ_lang').val(),
select2 : $('#source_lang').val()
},
complete : function(result){
var options = $.parseJSON(result);
$('#supplier_id').html("");
for(i=0; i < options.length; i++) {
$('#supplier_id').append(
'<option value="'+ options[i] + '">' + 'Supplier' + options[i] + '</option>'
);
}
});
});
});
On the PHP side you need to send your result like this:
$array = new Array(1,2,3,4); // supplier IDs
echo json_encode($array);
Example using jQuery's .post() method:
$('#targ_lang, #source_lang').change(function(){
$.post("test.php", { source: $('#source_lang').val(), target: $('#targ_lang').val()},
function(data) {
//Change the data of the 3rd select
});
});

Categories