I need your help to figure this out.
I have a table (link on top) of prices for typographic company. Let's say, to print business cards. My goal is to create a system where customer can press on a price and confirmation popup will appear with information from table.
For example: I need 500 business cards with Option #1.
I press on the price 740 and popup window appears with info: "You have ordered 500 business cards with Option #1 by price 740.
Manually I can create all variations like (row-1, cell-5) + (row-3, cell-1) + (row-3, cell-5) but this is not an options, even though the logic is right.
I have a table and popup already created and working. All prices are variables and I can change them from my back-end. I need help with combining variables.
How can I achieve my goal using php?
You need JavaScript to do a popup, not PHP. You can use PHP to create an array for JavaScript to use to retrieve the values.
In this example I am creating a JavaScript array ($JS) that will have the same values as the displayed table.
In the Table I add buttons to each cell (I use buttons because the default style display is inline-block and their purpose is to be clicked) where when selected will pass the row,column of the table.
$JS = 'var cells['; // initialize JavaScript array
$ndx = 0;
while ($row = mysqli_fetch_array($results, MYSQL_NUM)){
echo "
<tr><td><button type="button" onclick="sel($ndx,0)">$row[0]</button></td>
<td><button type="button" onclick="sel($ndx,1)">$row[1]</button></td>
<td><button type="button" onclick="sel($ndx,2)">$row[2]</button></td>
<td><button type="button" onclick="sel($ndx,3)">$row[3]</button></td>
<td><button type="button" onclick="sel($ndx,4)">$row[4]</button></td><tr>";
$JS .= [$ndx[$row[0],$row[1],$row[2],$row[3],$row[4],$row[5]][";
$ndx++;
}
echo '</table>'
$JS = substr($JS,0,-1) . ']]'; // trim the trailing `[` and close the array
echo <<<EOT
<script type="text/javascript">//<![CDATA[
$JS
function sel(r,c){
var selected = cells[r,c];
}
//]]>
</script>
EOT;
The main thing I wanted to show in the above is how PHP can pass values to JavaScript. It is not really needed as you could just pass the value in the sel($ndx,0,$row[x]) where x is the column number in the table
But there is a better way that would be more user friendly:
This example the user makes selections by checking the check box. The form is submitted (to same script) for confirmation.
There is a hidden input where name=sub and value=1. so when the confirm is clicked this can be checked by checking the value of $_POST['sub']
$sub = intval($_POST['sub']);
if($sub == 1){
$selections = array();
foreach($_POST as $key => $val){
if(substr($key,0,1) == 'c'){
$row = intval(substr($key,1,1));
$col = intval(substr($key,2,1));
$selections[$row][$col] = $val;
}
}
// Confirmation (e.g. create popup box) code goes here
}
.
echo '<form action="???.php" method="post"><div><table>';
$ndx = 0;
while ($row = mysqli_fetch_array($results, MYSQL_NUM)){
echo <<<EOT
<tr><td><div id="d$ndx0"<input type="checkbox" name=\"c$ndx0\" value=\"$row[0]\"/>$row[0]</div></td>
<td><div id="d$ndx1"<input type="checkbox" name=\"c$ndx1\" value=\"$row[1]\"/>$row[1]</div></td>
<td><div id="d$ndx2"<input type="checkbox" name=\"c$ndx2\" value=\"$row[2]\"/>$row[2]</div></td>
<td><div id="d$ndx3"<input type="checkbox" name=\"c$ndx3\" value=\"$row[3]\"/>$row[3]</div></td>
<td><div id="d$ndx4"<input type="checkbox" name=\"c$ndx4\" value=\"$row[4]\"/>$row[4]</div></td>
EOT;
}
echo '</table><input type="submit" value="Confirm Selections"/><input type="hidden" name="sub" value="1"/></div></form>';
To style the checked check boxes:
Add an onclick event to each check box
<input type="checkbox" name=\"c$ndx0\" value=\"$row[0] onclick=\"chk($ndx0)\" \>
Then this JavaScript will change the background color of the div which encapsulates the check box giving visual feedback to the user.
The init() function creates an array for each check box eliminating the document.getElementById() each time a check box is checked or unchecked
It also colors the background based on whether the checkbox is checked or not.
<script type="text/javascript"> //<![CDATA[
var div=0;
var c = new Array;
var d = new Array;
toggle = new Array;
toggle[true] = 'checked="checked"';
toggle[false] = '';
bg = new Array;
bg[true] = '#f00';
bg[false] = '#2985EA';
function chk(id){
d[id].style.backgroundColor=bg[c[id].checked];
}
function init(){
var checked,did;
var divs = document.getElementsByTagName("div");
for (div=0; div<divs.length; div++){
did = divs[div].getAttribute("id");
if (did != null){
if (did.substring(0,1) == "d"){
var i = did.substring(1,3);
c[i] = document.getElementById('c' + i);
d[i] = document.getElementById('d' + i);
checked = c[i].checked;
d[i].style.backgroundColor=bg[checked];
}
}
}
}
window.onload = init;
//]]>
</script>
Then when the form is submitted for confirmation you can check the selected check boxes by adding $checked to each checkbox
<td><div id="d$ndx0"<input type="checkbox" name=\"c$ndx0\" value=\"$row[0]\" $checked[$ndx0] />$row[0]</div></td>
Then add $checked["$val"] = 'checked="checked"'; to the $_POST loop
$checked = array();
$sub = intval($_POST['sub'];
if($sub == 1){
foreach($_POST as $key => $val){
if(substr($key,0,1) == 'c'){
$row = intval(substr($key,1,1));
$col = intval(substr($key,2,1));
$selections[$row][$col] = $val;
$checked["$val"] = 'checked="checked"';
}
}
}
Related
I want to submit values to my WordPress MySQL database table table1 from all the textboxes. But before submit data, if the textbox value of match1, match2, match3 and so on, already exist in table2 (column name ref_code) then textbox border (or shadow) should turn green individually. If value does not exist in table2 (column name ref_code) then border should turn red of that specific match textbox.
Please take a look at my current code and give me valuable suggestion. (The given code is only to insert data in table1 but I want to search in table2 column:ref_code)
<?php
if (!empty($_POST)) {
global $wpdb;
$data = array(
'order_id' => $_POST['order_id'],
'raw_data' => $_POST['raw_data']
);
for( $i=1; $i<6; $i++) :
$data['match'.$i] = $_POST['match'.$i];
$data['buy'.$i] = $_POST['buy'.$i];
$data['percent'.$i] = $_POST['percent'.$i];
endfor;
$success=$wpdb->insert( 'test1', $data, $format=NULL );
if($success){
echo "=> DATA SAVED" ;
?>
<form method="post">
<div class='mainIn'>Order ID<br>
<input type="text" name="order_id"></div>
<div class='mainIn'>Raw Data<br>
<textarea type="text" name="raw_data"></textarea></div>
<br><br><div style='display:flex;flex-wrap:wrap'>
<?php for( $i=1; $i<6; $i++) : ?>
<div id='allpeaks' style='flex:0 0 100%'>
Match<?php echo $i;?><input class='inCol' name='match<?php echo $i;?>'>
Buy<?php echo $i;?><input class='inCol' name='buy<?php echo $i;?>'>
Percent<?php echo $i;?><input class='inCol' name='percent<?php echo $i;?>'>
</div><br><br>
<?php endfor;?>
</div>
<br><input type="submit">
</form>
You cannot render a style after the php runtime unless you use ajax to check if value exists.
Here you have a simple example of a html input, Javascript Ajax and SQL query:
https://www.w3schools.com/php/php_ajax_php.asp
You can use something like this. So after the user submit the value on input order_id, you can check with ajax if value exists. You will need a php file to check it:
<?php // This is yourcheck.php
$order_id = $_GET["order_id"];
$exists = $wpdb->get_var("SELECT ref_code FROM $wpdb->table2 WHERE ref_code = $order_id");
// Here check if value already exists in table2
if($exists){
$response = array("exists" => true);
echo json_encode($response);
} else {
// Here insert your data in table1
//...
$wpdb->insert( 'table1', $data, $format=NULL );
}
?>
With your input you will need to include this script:
<script>
var order_id = document.getElementById("order_id").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Check if exists value in table2, if true change border color of input
if(this.exists){
document.getElementsByName("order_id")[0].style.borderColor = "red";
}
}
};
xmlhttp.open("GET", "test.com/yourcheck.php?order_id="+order_id, true);
xmlhttp.send();
</script>
<input type="text" name="order_id">
This is the snippet in my index:
<p id="text" style="display:none">hello</p>
echo '<tr>';
echo '<td>'.$s['school_name'].'</td>';
echo '<td>'.$s['location'].'</td>';
echo '<td>'.$s['population'].'</td>';
echo '<td>'.$s['cost'].'</td>';
echo '<td>'.$s['topnotchers'].'</td>';
echo '<td>'.$s['rating'].'</td>';
echo '<td><input type="checkbox" name="userSelection" name="userSelection" onclick="userSelection()" value="'.$s['school_id'].'"</td>';
echo '</tr>';
}
And here is my js:
function userSelection(){
var checkBox = document.getElementsByName("userSelection")[0];
var text = document.getElementById("text");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
The text only displays when I check on row[0] since I set it to row[0]. But, what should be done if I need the function to be true to all rows when I check it?
The above code only displays text on first loop.
Is "*" going to work?
I'm a beginner, a help would be appreciated.
You have hard coded the index 0. So js function will run only for checkbox with zero index.
First of all change the name of checkboxes to checkbox1, checkbox2,... This will simplify the case.
Then You need to run a for loop for each checkbox. Use
`
for(i=0; i < 6; i++){
currentCheckBox = document.getElementById("checkbox"+i)
var text = document.getElementById("text");
if (currentCheckBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
`
You have to specify a name as an array like below,
<input type="checkbox" id="userSelection1" name="userSelection[]" onclick="userSelection()" value="">
Then only you can able to loop in javascript to check the status
var checkBoxArr = document.getElementsByName("userSelection[]");
I have come about quite a problem while programming an order submitting page, the aim of the page is to submit a dispute for an order - providing two fields are filled in, but only if one field is less than another one.
Basically, one is a drop down and the other is a disputes box, the queries are as follows:
If DisputesTextBox = "" and a drop down box = "Please Select..."
Everything is fine - submit button enabled
If DisputesTextBox != "" and dropdown box = "Please select..."
Error ( and vice versa, so if disputes is populated but dropwn = please select...) - submit button disabled
If DisputesTextox != "" and dropdown box = "Other"
Everything is fine - submit button enabled
If DisputesTextBox > shippedbox
Error - submit button disabled
<table>
<thead>
<tr><th>Item ID</th><th>Description</th><th>Dispute Quantity</th><th>Shipped Quantity</th><th>Ordered Quantity</th><th>Reason</th></tr>
</thead>
<tbody>
<?php
$data = mysql_query("SELECT * FROM `artran09` WHERE `invno` = '$invoiceno'") or die(mysql_error());
echo "<center>";
$i = -1;
echo "<form action=\"submitdispute.php?invno=".$invoiceno."&ordate=".$placed."\" method=\"POST\" onsubmit=\"return confirm('Are you sure you are ready to dispute your order?');\">";
while ($info = mysql_fetch_array($data)) {
$i += 1;
echo "<tr>";
echo "<td>".$info['item']."</td>";
echo "<td>".$info['descrip']."</td>";
echo "<td><input type=\"text\" input name=".$i." onKeyPress=\"return numbersonly(this, event)\" maxLength=\"3\"></td>";
echo "<td><input type=\"text\" value=".$info['qtyshp']." onKeyPress=\"return numbersonly(this, event)\" maxLength=\"3\" disabled=\"disabled\"></td>";
echo "<td><input type=\"text\" value=".$info['qtyord']." onKeyPress=\"return numbersonly(this, event)\" maxLength=\"3\" disabled=\"disabled\"></td>";
echo "<td><select name = \"reason$i\">";
echo "<option>Please Select...</option>";
echo "<option>Short/Not received</option>";
echo "<option>Damaged Goods</option>";
echo "<option>Product Not Ordered</option>";
echo "</select></td>";
echo "</tr>";
}
?>
</tbody>
</table>
</div>
</div>
<p><input type = "submit" value = "Dispute" name ="Submit">
</form>
Thanks, hope anyone can help!
Edited for Wolf/anyone who can help - what's up with this code here:
-- code i edited --
function validateSubmit(){
// this will loop through each row in table
// Make sure to include jquery.js
$('tr').each( function() {
// Find first input
var input1 = $(this).find('input').eq(0);
var qty1 = input1.val();
// Find Second input
var input2 = $(this).find('input').eq(1);
var qty2 = input2.val();
// Find third input
var input3 = $(this).find('input').eq(2);
var qty3 = input3.val();
// Find select box
var selectBx = $(this).find('select');
var selectVal = selectBx.val();
// Add your validation code here for the inputs and select
// Return true if all validations are correct
// Else return false
if(qty1 = "" && selectVal = "Please Select...") {
return true;
alert("You have an error somewhere, please check over your quantites.");
break;
}
if (qty1 > qty2) {
return false;
alert("You have an error somewhere, please check over your quantites.");
break;
}
});
}
return true;
alert("You have an error somewhere, please check over your quantites.");
break;
If you call return, execution of the current function is halted immediately and the value is returned. This means that nothing after a return statement is executed. The alert() will not run, because the functions ends with the return true.
this is my javascript that allows for a filter search field ...
function escape4regex(text)
{
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
function searchRegExFieldKeyUp()
{
var table = document.getElementById('ModelFilter');
var cells = table.getElementsByTagName('div');
var searchterms = escape4regex(this.value);
var regVar = '(?=.*' + searchterms.replace(/\s/g, '.*)(?=.*') + '.*)';
var i=cells.length;
while (i--)
{
var cell = cells[i];
var rowStr = cell.innerHTML;
// remove all tags
rowStr = rowStr.replace(/<(?:.|\n)*?>/gm, '').replace(/\n|\s{2,}/gm, ' '); // searches whole row
var regex = new RegExp(regVar,"gi");
var result = (regex.test(rowStr));
if(result)
{
cell.style.display = "";// check if compat with IE
}
else
{
cell.style.display = "none";
}
}
}
this creates checkboxes from databse inputs
<div id="ModelFilter">
<?php
while ($row = mysqli_fetch_assoc($result))
{
echo"<div class=\"modelfilter_td\" id=\"modelfilter_td\">";
echo"<input type=\"checkbox\" id = \"$row[ModelID]\"
name = \"selectedModels[]\"value =\"$row[Model]\" onclick=\"chkcontrol.apply(this);\">";
echo "$row[Model]";
echo"</div>";
}
echo"</div>";
I want to do the following :
when the checkbox is checked, it stays visible, even if it is not in the search terms of the filter field.
when the checkbox is checked , the background color is changed.
the checkbox and the title for the checkbox is held within a div, I want to allow the user to click anywhere in the div to allow toggling of the checkbox.
Anyone start me ont the right track with this?
EDIT: here is a solution to problem "3."
<script language="javascript">
$(document).ready(function(){
$(".modelfilter_td").click(function(e){
var chk = $($(this).find("input[type='checkbox']"));
if(chk.attr('checked'))
{
chk.attr('checked',false);
}else{
chk.attr('checked',true);
}
});
});
This is not a solution for you problem, but a recommendation on php-usage in html context:
<div id="ModelFilter">
<?php while ($row = mysqli_fetch_assoc($result)): ?>
<div class="modelfilter_td" id="modelfilter_td">
<input
type="checkbox"
id="<?php echo $row['ModelID'] ?>"
name="selectedModels[]"
value="<?php echo $row['Model'] ?>"
onclick="chkcontrol.apply(this);"
>
<?php echo $row['Model'] ?>
</div>
<?php endwhile ?>
</div>
This enables most IDEs to deal with HTML-autocompletion and code-analysis.
General overview:
I have three php pages:
one is the data-entry page which has a text field which onkeydown changes the URL of a iFrame,
the iFrame contains a page that searches an LDAP and mySQL database for email addresses. When a search result is clicked on it adds a disabled text input to the data-entry page.
and there is an action page which receives the form information and sends emails.
The problem is that none of the form data is being passed to the action page, from either the static form elements or the dynamic ones created by JavaScript.
form.php
<SCRIPT type="text/javascript">
// <!--
function delRecipient(object) {
var answer = window.confirm("Remove recipient?")
if (answer){
countChildren = object.parentNode.parentNode.childNodes.length;
oldName = "recipient" + countChildren;
newName = object.parentNode.id;
object.parentNode.parentNode.removeChild(object.parentNode);
document.getElementById(oldName).id = newName;
}
}
function iFrameHeight(id) {
var content_height=document.getElementById(id).contentWindow.document.body.scrollHeight;
document.getElementById(id).height=content_height;
document.getElementById(id).style.display='block';
}
function iFrameOpen(id) {
document.getElementById(id).style.display='block';
iFrameHeight(id);
}
function iFrameClose(id) {
var dt = new Date();
while ((new Date()) - dt <= 250) { /* Do nothing for 250 miliseconds. */ }
document.getElementById(id).style.display='none';
}
var selectNum=-1;
function iFrameSearch(e) {
var keynum;
var keychar;
var numcheck;
if(window.event) {
keynum = e.keyCode;
}
else if(e.which) {
keynum = e.which;
}
// Use up and down arrow keys to select recipient:
// Keynum 38 is the up arrow key,
// 40 is the down arrow key
// 13 is the enter key (for future use...)
if(keynum==38) { --selectNum; }
else if(keynum==40) { ++selectNum; }
else {
selectNum=-1;
}
keychar = String.fromCharCode(keynum);
keychar = keychar.replace(/([^- 'a-zA-Z])/gi,"");
document.getElementById('members').src='iframe.php?keyword=' + document.getElementById('search').value + keychar + '&select=' + selectNum;
iFrameHeight('members');
return false;
}
// -->
</SCRIPT>
<div class="content">
<form name="form" id="form" method="post" action="action.php">
<h3>Select Recipients</h3>
To:
<div id="recipients" class="recipients"></div>
<input type="text" id="search" class="search" autocomplete="off" onfocus="iFrameOpen('members'); iFrameHeight('members'); if(this.value=='Type name here to add a recipient...'||this.value=='Type name here to add another recipient...'){this.value='';}" onblur="if(this.value==''&&document.getElementById('recipients').getElementsByTagName('div').length>0){this.value='Type name here to add another recipient...';} else if(this.value==''){this.value='Type name here to add a recipient...';}" value="Type name here to add a recipient..." onkeydown="iFrameOpen('members'); iFrameSearch(event); iFrameHeight('members');" /><br>
<iframe src="" id="members" width="400" height="0" frameborder="0" scrolling="no" onmouseout="iFrameClose('members')" style="display: none; position:relative; top:0px; left:0px;"></iframe>
<input type="hidden" name="message" value="<?php $_REQUEST['var_from_previous_page'] ?>" />
<input type="submit" value="Send" />
</form>
</div>
iFrame.php
<SCRIPT type="text/javascript">
// <!--
function newRecipient(name,email) {
var recipientNumber = parent.document.getElementById("recipients").childNodes.length++;
var recipient = document.createElement("DIV");
recipient.id = "recipient" + recipientNumber;
recipient.className = "recipient";
recipient.innerHTML = "<INPUT type=\"text\" name=\"recipient" + recipientNumber + "\" value=\"" + name + " <" + email + ">\" disabled=\"disabled\" /><div class=\"delete\" onclick=\"javascript:delRecipient(this)\"> </div>";
parent.document.getElementById("recipients").appendChild(recipient);
parent.document.forms[0].search.value = "";
parent.document.forms[0].search.focus();
parent.document.getElementById("members").style.display="none";
}
// -->
</SCRIPT>
<?php
// CUT-OUT A BUNCH OF IRRELEVANT PHP which searches the LDAP and mySQL databases, sorts, formats, etc.
echo "<TABLE cellspacing=\"0\" callpadding=\"0\" width=\"1000\">\n";
for ($i=0; $i<$returned; $i++) {
$row_type = ($i%2 == 0) ? "even" : "odd";
$select = $_REQUEST['select'] % $returned;
if($i == $select) { $row_type .= " selected"; $selected = true; }
else { $selected = false; }
$name = explode(" (",$info[$i]["cn"][0]);
$name_boldkeyword = nameCapitalize(str_ireplace(strtolower($_REQUEST['keyword']), "<b>" . strtolower($_REQUEST['keyword']) . "</b>", $name[0]));
$email_boldkeyword = strtolower(str_ireplace( $_REQUEST['keyword'], "<b>" . $_REQUEST['keyword'] . "</b>", $info[$i]["mail"][0]));
echo '<tr class="' . $row_type . '" onclick="newRecipient(\'' . addslashes(ucwords($name[0])) . '\',\'' . $info[$i]["mail"][0] . '\');"><td height="20" style="overflow: hidden;">' . ucwords($name_boldkeyword) . ' <' . $email_boldkeyword . "></td></tr>\n";
}
echo '<tr class="last"><td>Showing ' . $returned . ' of ' . $info["count"] . " entries.</td></tr>\n";
echo "</table>";
action.php
var_dump($_REQUEST) contains only session cookies and advertising cookies. No $_POST variables.
If you play with the URL it will dump the variables you add.
You don't seem to be specifying any name="" parameters other than on the <form>, where it's not really useful.
Try doing that and you should be good.
I had the same problem. My solution was also adding the name attribute.
this is the way I create my element
var myElement = document.createElement('input');
myElement.setAttribute('type', 'text');
myElement.setAttribute('id', 'txtElement');
myElement.setAttribute('name', 'txtElement');
myElement.setAttribute('style', 'margin:5px;width:120px;');
myElement.setAttribute('value', 'my value');
this is the way I add my element to a div in the form.
document.getElementById("myDiv").appendChild(myElement);
i had this issue... search and search for a resolve this fix and dont dont find nothing...
after of many minutes... i fix that.
first u should to create the form as same way that u create or will create the form elements.. but this process when y load u page:
var formGrabar = document.createElement('form');
now.. u can to create a table and fill it with u form objects... remember always with document.create
so important is create the input type button dynamically too.
Conclusion:
for submit form elements created with JavaScript by POST, everything elements should be create dynamically, because when u create elements those ones are an object different from those who are created with html directly.
#m4rloncs #3inlabs
I'm pretty sure the problem arises from you making the input "disabled". Disabled form fields are not submitted along with the post data. Perhaps rather make the input a "hidden" input, or alternatively include a hidden input alongside the disabled text input.