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.
Related
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 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"';
}
}
}
I have a new question about a project I had been working on. I was designing a grid with different colored cells. it has a hidden div which shows when a cell is clicked, however I realized that only one cell(the last one of it's type) will show. i.e. if I have 2 objects with the column "objaffinity" as 0 ("enemy") it will show both red cells on the grid, however only the last one will actually work.
how can I make it so that it will show the proper information for each cell?
here's my code:
mapgen.php:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="cellinfo.js"></script>
<script src="cmenu.js"></script>
<?php
require("sql.php");
$sql = <<<SQL
SELECT *
FROM `maps`
WHERE `objpresent` = 1
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
} // ran the query
//$xobj = array();
//$yobj = array();
$otype = array();
$oname = array();
$xyobj = array();
while($row = $result->fetch_assoc()){
$xyobj[$row['x']][$row['y']] = true;
$otype[$row['id']]=$row['objaffinity'];
$oname[$row['id']]=$row['object'];
}
// get the rows
$cellid=1;
//find whether the row is obstructed
for ($y = 0; $y < 20; $y++) {
echo '<tr>';
for ($x = 0; $x < 25; $x++) {
echo "<td>";
//Detect what type of object it is
if (isset($xyobj[$x][$y])) {
if($otype[$cellid] == 2)
{
echo "<a href='#'> <div class='foe'> </div><div class='foepopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
elseif($otype[$cellid] == 1)
{
echo "<a href='#'><div class='friend'></div><div class='friendpopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
else
{
echo "<a href='#'> <div class='neutral'></div><div class='neutralpopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
$cellid++;
}
echo '</td>';
}
echo '</tr>';
}
?>
Cellinfo.js:
$(document).ready(function(){
//initially hide all popups
$(".foepopup").hide();
$(".neutralpopup").hide();
$(".friendpopup").hide();
//foebutton selected
$(".foe").on("click",function(e){
$(".friendpopup").hide();
$(".neutralpopup").hide();
$(".foepopup").show();
});
//close foe when selected
$(".foepopup").on("click",function(e){
$(".foepopup").hide();
});
//neutral button pressed
$(".neutral").on("click",function(e){
$(".foepopup").hide();
$(".friendpopup").hide();
$(".neutralpopup").show();
});
//close neutral
$(".neutralpopup").on("click",function(e){
$(".neutralpopup").hide();
});
//friend button pressed
$(".friend").on("click",function(e){
$(".foepopup").hide();
$(".neutralpopup").hide();
$(".friendpopup").show();
});
//close friend
$(".friendpopup").on("click",function(e){
$(".friendpopup").hide();
});
});
In your functions you use selectors, so for the script it does not matter which div was clicked.
Let me show you some examples:
$(".foepopup").on("click",function(e){
$(".foepopup").hide();
});
It should be something like this rather:
$(".foepopup").on("click",function(e){
$(this).hide();
});
And another example:
$(".neutral").on("click",function(e){
$(".foepopup").hide();
$(".friendpopup").hide();
$(".neutralpopup").show();
});
Rewrite it like this:
$(".neutral").on("click",function(e){
var td_tag = $(this).parent().parent();
td_tag.children(".foepopup").hide();
td_tag.children(".friendpopup").hide();
td_tag.children(".neutralpopup").show();
});
Rewrite other code on your own. this is the element on which click was triggered. td_tag will contain parent cell of a div clicked. After that, children method will allow you to find needed elements already inside specific cell.
Good luck!
I have this script:
<script type='text/javascript' src='js/jquery-1.4.4.mi.js'></script>
<script type='text/javascript'>
$('.filterMonth').change(function(){
alert('ijijiji');
$.ajax({
url: 'ajax/filterMandays.php',
//type: 'GET',
success: function(data){
//data is returned back
$('#mandayTable').html(data);
}
});
});
</script>
and this html:
<select name ="filterMonth">
<?php
$array_month = array("January","February","March","April","May","June","July","August","September","October","November","December");
foreach($array_month as $key => $month)
{
$value_month = $key+1;
echo "<option value = '$value_month'>$month</option>";
}
?>
</select>
-
<select name = "filterYear" onChange = "filter(filterMonth.value, filterYear.value)">
<?php
$curYear = date('Y');
for($i = 1990; $i<=$curYear+10; $i++)
{
if($i == $curYear)
{
echo "<option value = '$i' selected = 'selected'>$i</option>";
}
else
{
echo "<option value = '$i'>$i</option>";
}
}
?>
</select>
</td>
</tr>
</br>
</br>
<tr>
<div id="mandayTable"></div>
and this php page:
<?php
include("all.php");
$q = "SELECT md.mandays_id,md.employeenum,md.month,md.year,md.required_man_days,d.firstname,d.lastname
FROM tbl_mandays md,tbl_employee_details d
WHERE md.active = '1'
AND md.employeenum = d.employeenum
AND md.month = '10';";
$res = $db->Execute($q);
echo "<table border = 1>";
echo "<tr><th>Employee Number</th><th>First Name</th><th>Last Name</th><th>Month-Year</th><th>Required Man Days</th><th>Edit/Delete</th></tr>";
while($rows = $res->FetchRow())
//for($i=0;$i<5;$i++)
{
//iterating through // check if employee
// // if(isset($row[])) { }
$mandays_id = $rows[0];
$empnum = $rows[1];
$month_year = $rows[2] ."-" .$rows[3];
$required_man_days = $rows[4];
$firstname = $rows['month'];
$lastname = $rows[6];
//echo approvers here are not taken
//<a href=\"view_team.php?id=".$empnum."\" -> for someone to view the people beneath them (like org tree)
echo "<tr><td>".$empnum . "</td><td>".$firstname ."</td><td>".$lastname ."</td><td>" . $month_year ."</td><td>" .$required_man_days . "</td><td width = \"200\" align = \"center\"><a href = 'edit_mandays.php?mandays_id=$mandays_id');'>Edit/Delete</a></td></tr>";
}
echo "</table>";
?>
the script should basically load the php page in the div in the html once the "filterMonth" has been changed. but it doesn't work.
what seems to be the problem? :(
The selector in your jQuery is $('.filterMonth') but your select box doesn't have the filterMonth class. You need to change it to $('select[name=filterMonth]').
In order for the jQuery selector to contain your select, you need to make sure that it runs after the Select element is in the DOM (ie: lower down the HTML), or run your JavaScript once the document has finished loading, for example:
<script type='text/javascript' src='js/jquery-1.4.4.mi.js'></script>
<script type='text/javascript'>
jQuery(function() {
// do your DOM selections here, this function only runs once the document is loaded
});
</script>
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.