I am having a weird problem. I am creating a metabox for wordpress and came across an issue where a <tr> will not clone on .click. I am using a while php loop and can get div, p, a, etc tags to clone but not luck with the table. Here is a look at the code.
<?php while($mb->have_fields_and_multi('ingredients')) : ?>
<?php $mb->the_group_open(); ?>
<tr>
<td>Blah</td>
</tr>
<?php $mb->the_group_close(); ?>
<?php endwhile; ?>
add row
Here is the javascript
$('[class*=docopy-]').click(function(e)
{
e.preventDefault();
var p = $(this).parents('.postbox'); /*wp*/
var the_name = $(this).attr('class').match(/docopy-([a-zA-Z0-9_-]*)/i)[1];
var the_group = $('.wpa_group-'+ the_name +'.tocopy', p).first();
var the_clone = the_group.clone().removeClass('tocopy last');
var the_props = ['name', 'id', 'for', 'class',];
the_group.find('*').each(function(i, elem)
{
for (var j = 0; j < the_props.length; j++)
{
var the_prop = $(elem).attr(the_props[j]);
if (the_prop)
{
var the_match = the_prop.match(/\[(\d+)\]/i);
if (the_match)
{
the_prop = the_prop.replace(the_match[0],'['+ (+the_match[1]+1) +']');
$(elem).attr(the_props[j], the_prop);
}
the_match = null;
// todo: this may prove to be too broad of a search
the_match = the_prop.match(/n(\d+)/i);
if (the_match)
{
the_prop = the_prop.replace(the_match[0], 'n' + (+the_match[1]+1));
$(elem).attr(the_props[j], the_prop);
}
}
}
});
if ($(this).hasClass('ontop'))
{
$('.wpa_group-'+ the_name, p).first().before(the_clone);
}
else
{
the_group.before(the_clone);
}
checkLoopLimit(the_name);
$.wpalchemy.trigger('wpa_copy', [the_clone]);
});
});
I apologize for the amount of javascript and I couldn't replicate the problem just jsfiddle.
Related
I'm trying to populate HTML table with filter(two dropdowns) from CSV file by using PHP, JS, and jQuery. When user open the page user will see below dropdown,
the options for this drop downs are file names in the dir.
<form name="form1" method="post">
<select class="form-control col-sm-5" onChange="document.forms['form1'].submit();" id="choosefile" name="choosefile">
<option value="" selected>Choose Term</option>
<?php
foreach ($files as &$value) {
echo '<option value="' . $value . '">' . $value . '</option>';
}
?>
</select>
</form>
when user submit the form below PHP code gets executed
<?php
if(isset($_POST['choosefile']) && !empty($_POST['choosefile'])) {
$t = $_POST["choosefile"];
$filepath = "uploads/$t";
$row = 0;
$the_big_array = [];
$unique_start_date = [];
$unique_ids = array();
if (($h = fopen("{$filepath}", "r")) !== false) {
while (($data = fgetcsv($h, 1000, ",")) !== false) {
$the_big_array[] = $data;
$unique_ids[] = $data[0];
$a unique_start_date[] = $data[1];
}
fclose($h);
}
//closing bracket for parent if statement is at the end of the file
?>
Below two dropdowns act as a filter
<select name="" id="session_id">
<option value="">[Select Session]</option>
</select>
<select name="" id="start_date">
<option value="">[Select Start Date]</option>
</select>
<table border="1" class="table" id="personDataTable">
<thead>
<tr>
<th scope="col">Session</th>
<th scope="col">Start Date</th>
</tr>
</thead>
<tbody id='tbody'>
</tbody>
</table>
<script>
var obj1 = <?php array_shift($the_big_array); echo json_encode($the_big_array); ?>;
var obj2 = <?php array_shift($unique_start_date); echo json_encode(array_unique($unique_start_date)); ?>;
var obj3 = <?php array_shift($unique_ids); echo json_encode(array_unique($unique_ids)); ?>;
var table = document.getElementById("personDataTable").getElementsByTagName("tbody")[0];
var temp,temp1 = {};
var row = 0;
$("#choosefile, #session_id, #start_date").on('change', function() {
var d1 = $( "#session_id" ).val();
var d2 = $( "#start_date" ).val();
$("#tbody").empty();
for (var i = 0; i < obj1.length; i++) {
if (d1 && obj1[i][0] !== d1 && row > -1) continue;
if (d2 && obj1[i][1] !== d2 && row > -1) continue;
row++;
newTr.insertCell(-1).appendChild(document.createTextNode(obj1[i][0]));
newTr.insertCell(-1).appendChild(document.createTextNode(obj1[i][1]));
}
});
</script>
<?php }?>
The problem I'm having is when user submit first dropdown(options with file name) table doesn't get generated or it does not call .on('change', function() under which table generator code is present.
I'm not able to trigger that .on('change', function() for first dropdown but when user click on filter dropdowns that part works well
This answer is an extent to my last comment, as example.
//Put it into a seperate named function:
function fillTable() {
var d1 = $( "#session_id" ).val();
var d2 = $( "#start_date" ).val();
$("#tbody").empty();
for (var i = 0; i < obj1.length; i++) {
if (d1 && obj1[i][0] !== d1 && row > -1) continue;
if (d2 && obj1[i][1] !== d2 && row > -1) continue;
row++;
newTr.insertCell(-1).appendChild(document.createTextNode(obj1[i][0]));
newTr.insertCell(-1).appendChild(document.createTextNode(obj1[i][1]));
}
}
// reference to that function here
$("#choosefile, #session_id, #start_date").on('change', fillTable);
// call when the page is loading:
fillTable();
I an using Javascript when click add button to show multiple text box. but i don't how to store these text box values in database table single column. here i attached my form input coding and javascript for add number of textbox. after submit my form it stores somthing like Array into my table.
<?php
if(isset($_POST['submit']))
{
Include 'db.php';
//$digits = 5;
//$staff_id=STAF.rand(pow(10, $digits-1), pow(10, $digits)-1);
$fromlocation = $_POST['fromlocation'];
$fromlatitude = $_POST['fromlatitude'];
$fromlongitude = $_POST['fromlongitude'];
$tolocation = $_POST['tolocation'];
$tolatitude = $_POST['tolatitude'];
$tolongitude = $_POST['tolongitude'];
// $routes = $_POST['routes'];
//$routesmore = $_POST['routes_more'];
$date=date('Y-m-d H:i:s');
$status=1;
//$usertype=1;
$count = $_POST['count'];
for($i = 0 ; $i < $count ; $i++)
{
//$count++;
$routesmore = $_POST['routes_more'];
$routesmore2 = explode('.', $routesmore[0]);
}
$query = mysqli_query($connect,"INSERT INTO `motorpark-db`.`tbl_route` (`from_location`, `from_latitude`, `from_longitude`, `to_location`, `to_latitude`, `to_longitude`, `route1`, `status`, `created_date`) VALUES ('$fromlocation', '$fromlatitude', '$fromlongitude', '$tolocation', '$tolatitude', '$tolongitude', '$routesmore2', '$status', '$date');");
if($query)
{
header('location:create_route.php#managepart');
}
else
{
header('location:create_staff.php');
}
}
?>
my input box:
<div class="col-lg-8" id="img_upload">
<!-- <input type="text" id="file0" name="routes" style="background:none;width:185px;"> -->
<div id="divTxt"></div>
<p><a onClick="addproductimageFormField(); return false;" style="cursor:pointer;width:100px;" id="add_img_btn" class="btn btn-primary">Add Route</a></p>
<input type="hidden" id="aid" value="1">
<input type="hidden" id="count" name="count" value="0">
My Javascript:
<script type="text/javascript">
function addproductimageFormField()
{
var id = document.getElementById("aid").value;
var count_id = document.getElementById("count").value;
if(count_id < 2)
{
document.getElementById('count').value = parseInt(count_id)+1;
var count_id_new = document.getElementById("count").value;
jQuery.noConflict()
jQuery("#divTxt").append("<div id='row" + count_id + "' style='width:100%'><fieldset class='gllpLatlonPicker'><label for='text- input'>Stop</label><span style='color:red;'> *</span><input type='text' class='gllpSearchField' name='routes_more"+count_id+"' id='file"+count_id_new+"' /></fieldset>  <a href='#' onClick='removeFormField(\"#row" + count_id + "\"); return false;' style='color:#F60;' >Remove</a></div>");
jQuery('#row' + id).highlightFade({speed:1000 });
id = (id - 1) + 2;
document.getElementById("aid").value = id;
}
}
function removeFormField(id)
{
//alert(id);
var count_id = document.getElementById("count").value;
document.getElementById('count').value = parseInt(count_id)-1;
jQuery(id).remove();
}
</script>
Change In JS - Append routes_more[] in jQuery("#divTxt").append in place of routes_more'+count+'.
<script type="text/javascript">
function addproductimageFormField()
{
var id = document.getElementById("aid").value;
var count_id = document.getElementById("count").value;
if(count_id < 2)
{
document.getElementById('count').value = parseInt(count_id)+1;
var count_id_new = document.getElementById("count").value;
jQuery.noConflict()
jQuery("#divTxt").append("<div id='row" + count_id + "' style='width:100%'><fieldset class='gllpLatlonPicker'><label for='text- input'>Stop</label><span style='color:red;'> *</span><input type='text' class='gllpSearchField' name='routes_more[]' id='file"+count_id_new+"' /></fieldset>  <a href='#' onClick='removeFormField(\"#row" + count_id + "\"); return false;' style='color:#F60;' >Remove</a></div>");
jQuery('#row' + id).highlightFade({speed:1000 });
id = (id - 1) + 2;
document.getElementById("aid").value = id;
}
}
function removeFormField(id)
{
//alert(id);
var count_id = document.getElementById("count").value;
document.getElementById('count').value = parseInt(count_id)-1;
jQuery(id).remove();
}
</script>
Change in PHP Code - Find total count of routes_more textbox. And do accordingly. (No Need of checking how much count was there in your html code.)
<?php
if(isset($_POST['submit']))
{
include 'db.php';
//$digits = 5;
//$staff_id=STAF.rand(pow(10, $digits-1), pow(10, $digits)-1);
$fromlocation = $_POST['fromlocation'];
$fromlatitude = $_POST['fromlatitude'];
$fromlongitude = $_POST['fromlongitude'];
$tolocation = $_POST['tolocation'];
$tolatitude = $_POST['tolatitude'];
$tolongitude = $_POST['tolongitude'];
// $routes = $_POST['routes'];
//$routesmore = $_POST['routes_more'];
$date=date('Y-m-d H:i:s');
$status=1;
//$usertype=1;
//For Routes More
$totalRoutesCount = sizeof($_POST['routes_more']);
$totalRoutes="";
for($i=0;$i<$totalRoutesCount;$i++)
{
$totalRoutes = $totalRoutes.$routesmore[$i].",";
}
$totalRoutes = rtrim($totalRoutes, ',');
$query = mysqli_query($connect,"INSERT INTO `motorpark-db`.`tbl_route` (`from_location`, `from_latitude`, `from_longitude`, `to_location`, `to_latitude`, `to_longitude`, `route1`, `status`, `created_date`) VALUES ('$fromlocation', '$fromlatitude', '$fromlongitude', '$tolocation', '$tolatitude', '$tolongitude', '$totalRoutes', '$status', '$date');");
if($query)
{
header('location:create_route.php#managepart');
}
else
{
header('location:create_staff.php');
}
}
?>
HTML :
<input type="text"
id="file0" name="routes[]"
style="background:none;width:185px;">
PHP:
INSERT Query:
'routes'(BD column) = serialize( $post['routes'] );
Display Time:
unserialize the column routes and print with foreach loop
I have created a basket in my PHP form where users can insert their selected movies to it.
Question:
How can I prevent adding duplicate movies to this basket (selected movie list)?
Here is my code: (Sorry, I didn't paste all the code since it was too long)
<div id="basket">
<div id="basket_left">
<h4>Selected Movies</h4>
<img id="basket_img" src="http://brettrutecky.com/wp-content/uploads/2014/08/11.png" />
</div>
<div id="basket_right">
<div id="basket_content">
<span style="font-style:italic">Your list is empty</span>
</div>
</div>
</div>
<script type="text/javascript">
var master_basket = new Array();
$(document).ready(function () {$("input[id='selectType']").change(function(){
// AUTO_COMPLETION PART
$('#btnMove').on('click', function(d) {
console.log(master_basket);
d.preventDefault();
var selected = $("#q").val();
if (selected.length == 0) {
alert("Nothing to move.");
d.preventDefault();
} else {
var obj = {
"movie_name":selected,
"movie_info": ""
};
addToBasket(obj);
}
$("#q").val("");
});
});
function addToBasket(item) {
master_basket.push(item);
showBasketObjects();
}
function showBasketObjects() {
$("#basket_content").empty();
$.each(master_basket, function(k, v) {
$("#basket_content").append("<div class='item_list'>" + v.movie_name + "<a class='remove_link' href='" + k + "'><img width='20' src='http://i61.tinypic.com/4n9tt.png'></a></div>");
});
I personally wouldn't suggest using javascript to prevent this duplication thing since anyone could modify it and manually cause this problem, you should prevent the duplication both in php and javascript.
Anyway to accomplish what you want in the script I think it's enough to modify part of your code to this:
var master_basket = new Array();
selectedMovies = {};
///////
} else {
var obj = {
"movie_name":selected,
"movie_info": ""
};
if(!selectedMovies.hasOwnProperty(selected)){
addToBasket(obj);
selectedMovies[selected] = obj;
}
}
Try modifying your function to
function addToBasket(item) {
var ifExists = false;
for (i = 0; i < master_basket.length; ++i) {
if(master_basket[i] == item)
ifExists = true;
}
if(!ifExists)
master_basket.push(item);
}
}
Here's my view :
$(".qty").keyup(function(){
var qty = $(this).val();
var bt = (this.id);
var bts = $('#bts'+bt).val();
var edge = $('#edge'+bt).val();
for (var i = 1; i<edge; ++i) {
var batas = $('#bts'+i).val();console.log(batas);
}
});
<input type="hidden" id="<?php echo 'edge'.$items['id']?>" value="<?php echo $items['options']['jum']?>"/>
<?php
foreach ($items['options']['stok'] as $stok) {
$er = $stok['stokbagus'];
$length = $items['options']['jum'];
for ($i=1; $i< $length; $i++) {
echo '<input type="text" rel="'.$items['rowid'].'" id="bts'.$i.'" value="'.$er.'"/>';
}
}
?>
$items['options']['jum'] contains = 2.
$stok['stokbagus'] contains = 30 and 21.
It'll display the first one (30). How to display all $stok['stokbagus'] in javascript?
Because i want to compare $(".qty").val() with all of $stok['stokbagus']
Okay. Here is what you should do.
If your $stok['stokbagus'] variable is array, then you should select the first and the second variable like this:
$first = $stok['stokbagus'][0];
$second = $stok['stokbagus'][1];
Else if, your $stok['stokbagus'] variable is a string and has 30,21 like this;
$vars = explode(",", $stok['stokbagus']);
$first = $vars[0];
$second = $vars[0];
You are saying that $stok['stokbagus'] variable has 30 and 21 values then it must be an array.
To show all values in your $stok['stokbagus'];
implode(', ', $stok['stokbagus']; // or just use $er.
Full:
echo '<input type="text" rel="'.$items['rowid'].'" id="bts'.$i.'" value="'.implode(', ', $er).'"/>';
Update:
<?php
foreach ($items['options']['stok'] as $stok) {
$er = $stok['stokbagus'];
$length = $items['options']['jum'];
for ($i=1; $i < $length; $i++) {
if(is_array($er)) {
foreach($er as $key => $value) {
echo '<input type="text" rel="'.$items['rowid'].'" class="bts" data-id="'.$i.'" value="'.$value.'"/>';
}
} else {
echo '<input type="text" rel="'.$items['rowid'].'" id="bts'.$i.'" value="'.$er.'"/>';
}
}
}
Js:
$(".qty").keyup(function(){
var qty = $(this).val();
var bt = (this.id);
var bts = $('#bts'+bt).val();
var edge = $('#edge'+bt).val();
for (var i = 1; i<edge; ++i) {
// I don't know what do you want to do with batas variable...
if($('.bts').length > 1) {
$('.bts').each(function(){
console.log($(this).val());
});
} else {
var batas = $('#bts'+i).val();console.log(batas);
}
}
});
Can any one help how to sort the database results in php
i have pasted the my code below. it display the result but sorting cannot be done.
Any help in this regard
<script language="JavaScript" type="text/javascript">
<!--
var sortedOn = 0;
function SortTable(sortOn) {
var table = document.getElementById('results');
var tbody = table.getElementsByTagName('tbody')[0];
var rows = tbody.getElementsByTagName('tr');
var rowArray = new Array();
for (var i=0, length=rows.length; i<length; i++) {
rowArray[i] = rows[i].cloneNode(true);
}
if (sortOn == sortedOn) { rowArray.reverse(); }
else {
sortedOn = sortOn;
if (sortedOn == 0) {
rowArray.sort(RowCompareNumbers);
}
else if (sortedOn == 3) {
rowArray.sort(RowCompareDollars);
}
else {
rowArray.sort(RowCompare);
}
}
var newTbody = document.createElement('tbody');
for (var i=0, length=rowArray.length; i<length; i++) {
newTbody.appendChild(rowArray[i]);
}
table.replaceChild(newTbody, tbody);
}
function RowCompare(a, b) {
var aVal = a.getElementsByTagName('td')[sortedOn].firstChild.nodeValue;
var bVal = b.getElementsByTagName('td')[sortedOn].firstChild.nodeValue;
return (aVal == bVal ? 0 : (aVal > bVal ? 1 : -1));
}
function RowCompareNumbers(a, b) {
var aVal = parseInt(a.getElementsByTagName('td')
[sortedOn].firstChild.nodeValue);
var bVal = parseInt(b.getElementsByTagName('td')
[sortedOn].firstChild.nodeValue);
return (aVal - bVal);
}
function RowCompareDollars(a, b) {
var aVal = parseFloat(a.getElementsByTagName('td')
[sortedOn].firstChild.nodeValue.substr(1));
var bVal = parseFloat(b.getElementsByTagName('td')
[sortedOn].firstChild.nodeValue.substr(1));
return (aVal - bVal);
}
//-->
</script>
Php MySql Query
<?php
$job_id = $_GET['id'] ;
$sql="SELECT date, fullname, city, education from table_name
WHERE id = 'job_id'";
$result=mysql_query($sql); ?>
<table id="results" style="width:980px;">
<thead>
<tr>
<th style="width:60px;"><a onclick="SortTable(0);" href="javascript:;">Date</a></th>
<th style="width:150px;"><a onclick="SortTable(1);" href="javascript:;">Name</a></th>
<th style="width:70px;"><a onclick="SortTable(2);" href="javascript:;">City</a></th>
<th style="width:70px;"><a onclick="SortTable(3);"href="javascript:;">Education</a>
</th>
<?php while($rows=mysql_fetch_array($result)){
?>
<tbody>
<tr>
<td>1</td>
<td><? echo $fullname ; ?></td>
<td><? echo $city ; ?></td>
<td><? echo $b_education ; ?></td>
</tr>
</tbody>
<?
}
?>
</table>
$job_id = $_GET['id'] ;
$sql="SELECT date, fullname, city, education from table_name
WHERE id = 'job_id'";
will not work,
first it should id = '" . $job_id . "' (your WHERE condition search for the id "job_id" not the $job_id variable
2nd based on this lines, google the words "sql injection" ... thats a big security issue! (msyql_real_escape for example)
3rd, mysql provides ORDER functions... if you want client side order, build the result, convert it to json (json_encode) and handle it with javascript, but yours is crappy ^^
regards
Thomas