I have a form containing a select field id="projects" which upon being changed shows(using js) a hidden select field 'task' dynamically populating the tasks for the selected project by querying the dB. User can then enter hours which are updated on proj_id,task_id combination from the selects.
echo '<div id="dynform"><div class="rowhours"><select id="projects" name="project">';
if(mysqli_num_rows($res)==0)
echo '<option>No Projects assigned</option>';
else{
echo '<option value="0">Project - Choose one</option>';
while (list($proj_id, $title) = mysqli_fetch_row($res))
{
echo "<option value=$proj_id>$title</option>";
}
}
echo '</select></div><input type="button" id="add"></div>';
<select name="task" class="tasks" onchange="showOther(this, 'new');" onmouseover="showOther(this, 'new');"></select><br>
function showOther(fieldObj, otherFieldID) //Function displays text box for creating a new task on Addhours.php
{ //for the selected project when "Enter New Task" option chosen
var fieldValue = fieldObj.options[fieldObj.selectedIndex].value;
var otherFieldObj = document.getElementById(otherFieldID);
otherFieldObj.style.visibility = (fieldValue=='other') ? '' : 'hidden';
return;
}
Now I added an 'Add Row' button, this generates the same form many times.
<input type="button" value="Add Row" id="add">
jquery used to add rows: $(document).ready(function () {
$('#add').click(function () {
$('.rowhours').clone().appendTo('#dynform');
});
});
Now when I change the projects of any row, the tasks select fields of all rows get affected, I know this is because they have the same Id's.
Question is how can I make them have different Id's and be able to use them seperately in the same manner using jquery. Also as of now I just update using the if(isset($_POST['submit'])) What can I use for the multiple rows now?
I have a working example here http://fracktal.in/tms/addhours.php
I am basically looking for having a project[] and task[] that I have no clue how to access using jquery or to get the posted values on form submit to update dB
Once you add rowhours access the last element and change the id
$(".rowhours).last().attr("id","newId");
you can use arrays easily, just name your fields project[] (not project) and then access them with $_POST['project'][0], $_POST['project'][1], etc.
$total = count($_POST['project']);
foreach($_POST['project'] as $num=>$project) {
// do your code here, send to DB or whatever
// $project contains value of input (or select) and $num contains number of row
}
Related
EDIT : PLEASE FIND MY SOLUTION BELLOW
I have two select boxes in a FORM that i populate from two different tables.
SELECT1 displays client specific options.
SELECT2 displays all available options except those already on SELECT1
Everything works fine populating them, moving items from one to the other etc.
What I don't have a clue is how to, after submit of the FORM, I store those items of SELECT1 back to the database.
For each item on that SELECT box I need to check if it already exists on MY_TABLE_2 and if it does not, store it.
When I check var_dump(SELECT1) I only see the value of the last selected item but it normally contains more than one item in SELECT1.
For now I'm calling a stored procedure for all the other fields that will go on MY_TABLE_1 and that is OK.
I would need to do some transaction that updates the two tables or rolls back if i get an error. That is working if i store only one item.
But how I send to the stored procedure ALL the items.
Any help or clues?
Here's a print-screen if it can help understand:
The code to generate the form:
echo '<select name="ed_clilabelcodes" id="ed_clilabelcodes" style="width: 200px" multiple>';
while($row = sqlsrv_fetch_array($dvclilablist)){
echo '<option value="'.$row[0].'">'.$row[0].' - '.$row[1].'</option>';
}
echo '</select>';
----------- MY SOLUTION -----------
All items on any of those select boxes exist in a table (dbo.MyItems) identified by the field OptCode.
What I really needed was to store witch of those items were selected by a particular client.
I was thinking of having a second table where I would store those items but I was in reality duplicating information and I didn't find it to be the best solution.
Since I really only needed those selected codes attached to the client file I did the following:
I have one javascript function inspired from HERE that allows me to move items between the two select boxes and, by the way, from HERE to create a function that sorts the items in the boxes.
Each time I add or remove an item from the client's list box I immediately call the sort function, so I just update a hidden input value with all item values (codes) present in the select box immediately calling this javascript function :
function RecheckCodes() {
var vlist = document.getElementById("ed_clilabelcodes");
var vlabcodes = "";
var i;
for (i = 0; i < vlist.length; i++) {
if (i == 0) {
vlabcodes = vlabcodes + "\'" + vlist.options[i].value + "\'";
}
else {
vlabcodes = vlabcodes + ",\'" + vlist.options[i].value + "\'";
}
}
document.getElementById("v_clilabcodes").value = vlabcodes;
}
On FORM Post i just save that string in a client field.
Latter i can repopulate the boxes for edit using following 2 stored procedures to get the items (first SQL will get the string with the codes and is called from the 2nd one that gets the item description from items table).
ALTER PROCEDURE [dbo].[DavGetOptCodeByClient]
#vclicode nvarchar(12),
#vopttype nvarchar(12),
#voptcodes nvarchar(300) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT #voptcodes = optcodes
FROM dbo.dav_client_options
WHERE clinumber = #vclicode AND opttype = #vopttype
END
ALTER PROCEDURE [dbo].[DavGetOptDetailByClient]
#vclicode nvarchar(12),
#vopttype nvarchar(12)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #v2optcodes nvarchar(1000)
DECLARE #vsql nvarchar(1000)
exec dbo.DavGetOptCodeByClient #vclicode,#vopttype, #v2optcodes OUTPUT
SET #vsql = 'SELECT optcode, optdetail ' +
'FROM dbo.dav_global_options ' +
'WHERE ("optcode" IN ('+#v2optcodes+')) AND (opttype = '''+#vopttype+''')'
EXEC sp_executesql #vsql
END
So everything is working fine for what I needed even if I'm sure some improvement can be made on the code.
to be able to send all the elements the simplest option is to select them, it is not enough that they are in the list but they have to be selected, for that it must be activated the "multiple" option of the select, once done that by pressing the key "control" or "shift" you can make multiple select in your list.
<form action="#" method="post">
<select name="Color[]" multiple> <!--the option multiple must be active and be array -->
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>
<input type="submit" value="Get Selected Values" />
</form>
Another option is to add this small javascript (jQuery) in an html so you do not have to press or control or shift when you select several options, just click and you will be selected
$('option').mousedown(function(e) {
e.preventDefault();
$(this).prop('selected', !$(this).prop('selected'));
return false;
});
Source :How to avoid the need for ctrl-click in a multi-select box using Javascript?
And at the end you have your data with a simple php
<?php
$data=$_POST;
if($data) {
foreach ($data['Color'] as $option) {
echo $option;
}
var_dump($data);
}
?>
Im trying to search two of the fields in my table. (Database table contains cocktail names, with their name, ingredients and description) When a user types their desired term into the search box, auto complete results are given using Ajax/jquery.
I've got it working searching one field (Name) but can't seem to get it to do more than the one(Name & Ingredients). Another problem is when the results are given (they are given as links) When you select them it puts the data in the entry box instead of taking you to the next page.
index.php:
<script>
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true
});
});
</script>
<label>Tag:</label>
<input name="tag" type="text" id="tag" size="40"/>
autocomplete.php:
<?php
$q=$_GET['q'];
$my_data=mysql_real_escape_string($q);
$mysqli=mysqli_connect('localhost','ignitet1','password','ignitet1_WhatCocktail') or die("Database Error");
$sql="SELECT Name FROM tblCocktail WHERE Name LIKE '%$my_data%' ORDER BY Name";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error());
if($result)
{
while($row=mysqli_fetch_array($result))
{
echo "<a href=\"details.php\">";
echo $row['Name']."," , "<br />";
echo "</a>";
}
}
?>
Any help would be appreciated.
I'm not sure about forcing a link to that page, but for a quick and dirty fix on the search I would add:
OR Ingredients LIKE '%$my_dat%'
before the ORDER clause.
Update:
user710502 is correct about the fields to be selected in the query. As for the autocomplete, I looked at the documentation and it looks like you will have to create a custom event handler for the autocompleteselect event. This event fires when the user chooses an option from the dropdown. The default behavior (as you know) is to fill the field with the 'value'. Your added code will look something like this:
$("#selector-for-field").bind('autocompleteselect',function(event,ui){
event.preventDefault(); // this will stop the field from filling
// maybe make the value sent from the serverside a hyperlink,
// eg. http://www.wherever.com/you/want/the/item/to/link-to
// then in here do something like:
window.location(ui.item.value);
});
You'll have to double check that ui.item.value works because I didn't check it.
I am having trouble trying to get a value from a drop-down list and multiplying the value by a number in the 'ticket' table. I've been trying to implement this calculation in both PHP and javascript but having no luck :(
Here is the form (which is returned to the homepage by AJAX):
$pcSearch = $_POST['postcodeSearch'];
$postCodeSQL = "SELECT * FROM ticket WHERE locationID IN (SELECT locationID FROM location WHERE postCode LIKE '$pcSearch') ";
$postCoderesult = mysql_query($postCodeSQL) or die(mysql_error());
while ($pcRow = mysql_fetch_assoc($postCoderesult)) {
$venue = $pcRow['venue'];
$ticketPrice = $pcRow['tPrice'];
$date = $pcRow['date'];
$time= $pcRow['time'];
echo "<tr>\n";
echo "<td>$venue</td>\n";
echo "<td>£$ticketPrice</td>\n";
echo "<td><form id=\"quantity\" method=\"post\" name=\"ticketQuantity\">
<select name =\"showQuantity\" id=\"showQuantity\" class =\"showQuantity\" >
<option value=\"1\">1</option>
<option value=\"2\">2</option>
<option value=\"3\">3</option>
<option value=\"4\">4</option>
<option value=\"5\">5</option>
</select>
</form>
</td>\n";
echo "<td>$date</td>\n";
echo "<td>$time</td>\n";
echo "<td><form name=\"buyTicket\" class=\"buyTicket\" id=\"buyTicket\" >
<input type= \"button\" id= \"buyMe\" class= \"buyMe\" value= \"Buy\" name=\"buyMe\">
</form>
</td>\n";
echo "</tr>\n";
}
Basically, what I wanting to do is when a user clicks and choose the quantity of tickets they want i.e. 3, this number will be multiplied by the price of the ticket ('tPrice'). Is there a way of getting both these values and multiplying them together in PHP?
I've tried adding jQuery to listen for the button click function but to no avail...I even tried debugging it but for some strange reason it won't output the alert:
$(document).ready(function() {
$(".buyMe").click(function() {
alert('click');
});
});
However if I were to use jQuery, how would I even get the value of 'tPrice' from the form?
Thanks very much for any help :)
The first thing i would do is add a class to the ticket price td :
echo "<td class=\"ticketPrice\">£$ticketPrice</td>\n";
What that does it make it a lot easier to get the price using jQuery.
So now .. you can do this :
$(".buyMe").click(function() {
var priceForOne = $(this).siblings('.ticketPrice').text().substr(1);
});
Infact as you have access to the source of the HTML a better way would probably using data() :
echo '<input type="button" class="buyMe" value="Buy" data-ticket-price="'.$ticketPrice.'"/>';
then you can change your click to be :
$(".buyMe").click(function() {
var priceForOne = $(this).data('ticketPrice');
});
A couple of other points ..
remove the id attribute from here :
<input type= \"button\" id= \"buyMe\" class= \"buyMe\" value= \"Buy\" name=\"buyMe\">
there is no need for a form around the select list as its doing nothing ... similarly the form around the button is doing nothing either !
Updated
The click method won't work for DOM elements added after the document has been loaded (ie via AJAX) ... you need to use the on() method :
$(document).on('click','.buyMe',function() {
// handle the click here
});
the $(document) above needs to be a parent element of the buyMe element and present on the DOM at load, in your case you could replace $(document) with $('#idOfYourTable')
Docs for data() and Docs for on()
You're referencing a non-existent class name instead of the id. Change .buyme to #buyme
$(document).ready(function() {
$("#buyMe").click(function() {
alert('click');
});
});
Edit missed that the class is on there too. However since you're just referencing a single element you should use the ID anyway.
In Dreamweaver I have a list box or menu/list.
I am dynamically adding data from an array into it, so when the page loads, I have a list-box with names in.
This is how it looks
<?php
echo "<select name="."username"."id="."username".">";
foreach ($user_array as $arr) {
echo "<option>$arr</option>";
}
echo "</select>";
?>
Now how do I go about making the listbox executesomething when the user selects something in it?
Because I have three other textboxes, and when the user selects a name in the list box, I want to put that name he selected into a variable (also don't know how I'm going to do that with a list box) and then search through my database and insert some of the data of that person in the textboxes.
So all i need to know is:
How to create that on event click event and
How to put that selected value then in a variable (inside the event)
You can easily execute a javascript function by using something like this:
<select name=".$username."id=".$username." onchange='yourfunction()' >
The following php code generated a select field with a dynamic number of options.
<?php
$user_array = Array("Smith", "John", "Bob", "Jake");
echo "<select name="."username"." id="."username".">";
foreach ($user_array as $arr) {
echo "<option>$arr</option>";
}
echo "</select>";
?>
The following JavaScript handles change events on the select element.
$(document).ready(function() {
var username = $('#username');
var selectedValue = null;
username.change(function(){
alert(username.val());
selectedValue = username.val();
});
});
Using some code to create a form dynamically which I got here: http://www.trans4mind.com/personal_development/JavaScript2/createSelectDynamically.htm
This works great. However I have a regular html table I generate with html/php to get data out of a DB. I want to replace that data with a form so when users click the edit button the original entry is replaced with a form (either textbox or pull down menu). The user makes a selection and the new table comes back with the appropriate edit.
So for example one part of the data has this in the table:
<td><?php echo $result[0] ?></td>
Using the link about to create a form dynamically I change this to:
<td id="paraID"><form id="form1" name="form1" method="post" action enctype="text/plain" alt=""><?php echo $result[0] ?></form></td>
Also note the onclick event for the edit button:
This is hard to explain but hoping someone can help me with this interaction. I need some way to say:
if (user clicks edit button)
then
replace html table with form for each entry (for example, the table returns a name called foo and a textbox will appear with foo in it but now they can edit to change the name).
If you can start out with an id for the td then it will make things easier. Then you will need an edit button somewhere. Notice: It might be nice to replace "result_0" with the name for the value/field:
<td id="result_0_parent"><?php echo $result[0] ?><input type="button" onClick="editField('result_0','select')" value="Edit" /></td>
Then in your javascript you will have the editField function defined so that it sets the content of the td to be the dynamic form. Looking at makeForm function in the example javascript, you see this happening with appendChild(myform); The function editField will be like the makeForm function except you will pass in the field_id and field_type as parameters:
function editField(field_id, field_type)
I suggest you change the line that defines mypara to define mytd or better yet, field_parent instead since in your case it will not be a paragraph element, but a td (or possibly some other type of element):
field_parent = document.getElementById(field_id+"_parent");
The example code create a select (dropdown), but I am guessing you want to create other field input types so I recommended having field_type as a second parameter to the function. This means that it would make more sense for your implementation to use myfield instead of myselect and then use the field_type parameter to decide what myfield will be.
Replace the line in the makeForm / editField function:
myselect.setAttribute("id","selectID");
with
myfield.setAttribute("id",field_id);
One more thing: To set the initial value of the input field to be the displayed content, you will need to copy the "innerHTML" of the "parent" element. So place something like this right after defining field_parent:
initial_value = field_parent.innerHTML;
and I think you can figure out the rest. If not, I can elaborate a little more.
This works great. However I have a regular html table I generate with
html/php to get data out of a DB. I want to replace that data with a
form so when users click the edit button the original entry is
replaced with a form (either textbox or pull down menu). The user
makes a selection and the new table comes back with the appropriate
edit.
This is a script that allows with a double click on values to edit them and has a button to send them back. Maybe it would be of some help to use it (or use parts of it).
<?PHP
if(count($_POST)>0)
{
echo 'You gave:<br><per>';
print_r($_POST);
echo '<a href=http://localhost/temp/run.php>Start over</a>';
exit;
}
?>
<html>
<head>
<script type="text/javascript">
/**formEditor Class
*/
function formEditorCls( )
{
/**
Constructor simulator
*/
this.lastFieldEditedId = null;
/** Change span with input box, hide the eddit button and store theses IDS
*/
this.edit=
function (field)
{
//if there was a field edited previously
if(this.lastFieldEditedId != null)
this.save();
//get the inner element of the div, it can be span or input text
var childElem = document.getElementById(field).getElementsByTagName('*')[0];
//then replace the span element with a input element
document.getElementById(field).innerHTML="<input type=text name=n_"+field+
" id=id_"+field+" value="+childElem.innerText+">";
//store what was the last field edited
this.lastFieldEditedId =field;
}//func
this.save=
function ()
{
dbq="\"";sq='\'';
//get the last value
var lastValue = document.getElementById(this.lastFieldEditedId).
getElementsByTagName('*')[0].value;
//store it as span
document.getElementById(this.lastFieldEditedId).innerHTML="<span ondblclick="+dbq+
"formEditor.edit("+sq+this.lastFieldEditedId+sq+");"+dbq+" >"+lastValue+"</span>" ;
//now must reset the class field attribute
this.lastFieldEditedId=null;
}//func
this.submit=
function (path)
{
this.save();//if ay field was edited put new values in span elements
var form = document.createElement("form");//create a new form
form.setAttribute("method", "post");
form.setAttribute("action", path);
var myDiv = document.getElementById( "fieldsDiv" );//get the div that contains the fields
var inputArr = myDiv.getElementsByTagName( "SPAN" );//get all span elements in an array
//for each span element
for (var i = 0; i < inputArr.length; i++)
{
var hiddenField = document.createElement("input");//create an input elemet
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", i);
hiddenField.setAttribute("value", inputArr[i].innerText);
form.appendChild(hiddenField);//append the input element
}
document.body.appendChild(form);//append the form
form.submit();//submit the form
}//func
}//class
formEditor = new formEditorCls( );
</script>
</head>
<body onclick="rt();">
Double click any value to change it..<br><br>
<div id="fieldsDiv">
Name:<font id="nameField">
<span ondblclick="formEditor.edit('nameField');" >Mark</span>
</font><br>
Surname:<font id="surnameField" >
<span ondblclick="formEditor.edit('surnameField');">Smith</span>
</font><br>
</div>
<input type=submit name="submit"
onclick="formEditor.submit('http://localhost/temp/run.php');" value="Submit">
</body>
</html>