PHP Won't Post Table of Values - javascript

I have a table of values in HTML that I want to post. It looks like this:
After the user selects all of the relevant teams, I want to save it into a form, combining all the rows into a form like this:
PHP:
$numRows = 1;
$startMatchNum = 1;
if(isset($_GET['num'])) {
$numRows = $_GET["num"];
$startMatchNum = $_GET["start"];
}
JavaScript:
function getSelectionValue(rowNum, columnNum) {
document.cookie = "rowNum=" + rowNum;
//FOR EXTERNAL PHP FILE
//window.location = "http://example.com/file.php";
var id =
<?php
$index = 0;
$row = 0;
if ( ! empty( $_COOKIE['rowNum'] ) ) {
$row = $_COOKIE['rowNum'];
}
echo '"'.$values[$index].$row.'"';
?>;
var e = document.getElementById(id);
var selectedValue = e.options[e.selectedIndex].value;
}
function postRefreshPage() {
var theForm, newInput1, newInput2, newInput3, newInput4, newInput5, newInput6;
var rows = <?php echo $numRows; ?>;
var nums1 = new Array(rows);
// Start by creating a <form>
theForm = document.createElement('form');
theForm.action = 'addMatch.php';
theForm.method = 'post';
// Next create the <input>s in the form and give them names and values
newInput1 = document.createElement('input');
newInput1.type = 'hidden';
newInput1.name = 'blue1Team';
newInput1.value = "";
for(var i = 0;i < rows;i++) {
newInput1.value += getSelectionValue(i, 0);
if((i + 1) != rows) {
newInput1.value += "|";
}
}
newInput2 = document.createElement('input');
newInput2.type = 'hidden';
newInput2.name = 'blue2Team';
newInput2.value = "";
for(var i = 0;i < rows;i++) {
newInput2.value += getSelectionValue(i, 1);
if((i + 1) != rows) {
newInput2.value += "|";
}
}
newInput3 = document.createElement('input');
newInput3.type = 'hidden';
newInput3.name = 'blue3Team';
newInput3.value = "";
for(var i = 0;i < rows;i++) {
newInput3.value += getSelectionValue(i, 2);
if((i + 1) != rows) {
newInput3.value += "|";
}
}
newInput4 = document.createElement('input');
newInput4.type = 'hidden';
newInput4.name = 'red1Team';
newInput4.value = "";
for(var i = 0;i < rows;i++) {
newInput4.value += getSelectionValue(i, 3);
if((i + 1) != rows) {
newInput4.value += "|";
}
}
newInput5 = document.createElement('input');
newInput5.type = 'hidden';
newInput5.name = 'red2Team';
newInput5.value = "";
for(var i = 0;i < rows;i++) {
newInput5.value += getSelectionValue(i, 4);
if((i + 1) != rows) {
newInput5.value += "|";
}
}
newInput6 = document.createElement('input');
newInput6.type = 'hidden';
newInput6.name = 'red3Team';
newInput6.value = "";
for(var i = 0;i < rows;i++) {
newInput6.value += getSelectionValue(i, 5);
if((i + 1) != rows) {
newInput6.value += "|";
}
}
// Now put everything together...
theForm.appendChild(newInput1);
theForm.appendChild(newInput2);
theForm.appendChild(newInput3);
theForm.appendChild(newInput4);
theForm.appendChild(newInput5);
theForm.appendChild(newInput6);
// ...and it to the DOM...
document.getElementById('hidden_form_container').appendChild(theForm);
// ...and submit it
theForm.submit();
location.reload();
}
Then, after it refreshes, it runs this PHP code:
if($_POST) {
$blueTeam1 = explode ("|", $_POST['blueTeam1']);
$blueTeam2 = explode ("|", $_POST['blueTeam2']);
$blueTeam3 = explode ("|", $_POST['blueTeam3']);
$redTeam1 = explode ("|", $_POST['redTeam1']);
$redTeam2 = explode ("|", $_POST['redTeam2']);
$redTeam3 = explode ("|", $_POST['redTeam3']);
for($i = 0;i < $numRows;$i++) {
$matchNumber = $i + 1;
$query = "INSERT INTO match_info (matchNumber, blueTeam1, blueTeam2, blueTeam3, redTeam1, redTeam2, redTeam3)
VALUES ('$matchNumber','$blueTeam1[$i]','$blueTeam2[$i]','$blueTeam3[$i]','$redTeam1[$i]','$redTeam2[$i]','$redTeam3[$i]')";
$mysqli->query($query);
}
}
However, it doesn't seem to be submitting. Any help is greatly appreciated!
EDIT: I found the error, but I don't know how to fix it. In the Javascript code, the getSelectionValue function returns undefined, but I'm not sure why.

You can try to remove
location.reload();
in getSelectionValue() function, because you submit but in the same time you reload the initial script.

I figured it out. It was a variety of issues. First of all, the IDs in my PHP code didn't match the IDs in the JavaScript table. Secondly, my use of cookies to pass JavaScript variables to PHP didn't work, so I copied the PHP array I wanted to access and set it again in JavaScript. So, the function getSelectionValue(rowNum, columnNum); doesn't need to access the PHP code. Lastly, my table in the database didn't have the matchNumber column in it, so the whole process failed.
Thanks to all those that helped!

Related

CheckBox for all and for single does not work correctly

I am trying to make an array of listing using checkbox function, the function checks if the all checkbox is clicked then put all listings in the array, if it is clicked to uncheck it pulls all array values, and if a single listing is checked it adds to the array , and if its unchecked when its single or all listing values its value from the array is taken out. Yet on the first run if all selected i cant remove a single value by selecting one checkbox, and after all are checked and unchecked i cant add a single value into array by checking a single option.
var lstsToEdit = [];
lstDisplay("act");
$(".tab-listings-selection").on("click", function() {
var lstType;
if(this.id == "mnLstAct") lstType = "act";
if(this.id == "mnLstInact") lstType = "inact";
if(this.id == "mnLstDraft") lstType = "draft";
document.getElementById("mnLstAct").style.fontWeight = "normal";
document.getElementById("mnLstInact").style.fontWeight = "normal";
document.getElementById("mnLstDraft").style.fontWeight = "normal";
this.style.fontWeight = "bold";
lstDisplay(lstType);
});
function lstDisplay(type){
document.getElementById("main").innerHTML = "";
var tblLsts = document.createElement("table");
tblLsts.setAttribute("id", "tblLsts");
$("#main").append(tblLsts);
var tblLstsHRow = tblLsts.insertRow(0);
var tblLstsHThumb = tblLstsHRow.insertCell(0);
var tblLstsHTitle = tblLstsHRow.insertCell(1);
var tblLstsHStock = tblLstsHRow.insertCell(2);
var tblLstsHPrice = tblLstsHRow.insertCell(3);
var tblLstsHExpiry = tblLstsHRow.insertCell(4);
var tblLstsHSection = tblLstsHRow.insertCell(5);
var tblLstsHAll = tblLstsHRow.insertCell(6);
tblLstsHThumb.outerHTML = "<th></th>";
tblLstsHTitle.outerHTML = "<th>Title</th>";
tblLstsHStock.outerHTML = "<th>In Stock</th>";
tblLstsHPrice.outerHTML = "<th>Price</th>";
tblLstsHExpiry.outerHTML = "<th>Expiry</th>";
tblLstsHSection.outerHTML = "<th>Section</th>";
tblLstsHAll.outerHTML = "<th>All<input id=\"lstsAllChk\" class=\"lstChk\" type=\"checkbox\"/></th>";
var lstThumb = [];
var listings;
if (type == "act") lsts = lstAct;
if (type == "inact") lsts = lstInact;
if (type == "draft") lsts = lstDraft;
for (var lstIndex = 1; lstIndex < lsts.results.length+1; lstIndex++){
var lst = lsts.results[lstIndex-1];
var row = document.getElementById("tblLsts").insertRow(lstIndex);
var colThumb = row.insertCell(0);
var colTitle = row.insertCell(1);
var colStock = row.insertCell(2);
var colPrice = row.insertCell(3);
var colExpiry = row.insertCell(4);
var colSection = row.insertCell(5);
var colSelect = row.insertCell(6);
var lstJ = JSON.parse($.ajax({url: "listings/" + lst.listing_id + ".json", async: false}).responseText);
colThumb.innerHTML = "<img src=\"" + lstJ.results[0].url_75x75 +"\">";
colTitle.innerHTML = lst.title;
colStock.innerHTML = lst.quantity;
colPrice.innerHTML = lst.price;
colSelect.innerHTML = "<input id=\"" + lst.listing_id + "\" class=\"lstChk\" type=\"checkbox\"/>";
for (var secIndex = 0; secIndex < sects.results.length; secIndex++){
if (sects.results[secIndex].shop_section_id == lst.shop_section_id)
colSection.innerHTML = sects.results[secIndex].title;
}
}
$.getScript("tableSort.js");
}
$(".lstChk").on("click", function() {
if(this.id == "lstsAllChk" && this.checked){
for(var lstIndex = 0; lstIndex < document.querySelectorAll(".lstChk").length; lstIndex++){
var lstId = document.querySelectorAll(".lstChk")[lstIndex].id;
//if(lstsToEdit.findIndex( function(value){ value == lstId;}) == -1){;
$("#"+lstId).prop("checked");
lstsToEdit.push(lstId);
//}
}
}
else if(this.id == "lstsAllChk" && !this.checked){
for(var lstIndex = 0; lstIndex < document.querySelectorAll(".lstChk").length; lstIndex++){
var lstId = document.querySelectorAll(".lstChk")[lstIndex].id;
$("#"+lstId).prop("checked", false);
var index = lstsToEdit.findIndex( function(value){ value == lstId;});
lstsToEdit.splice(index, 1);
}
}
else if(this.checked) lstsToEdit.push(this.id);
else {
var index = lstsToEdit.findIndex( function(value){ value == this.id;});
lstsToEdit.splice(index, 1);
}
if(lstsToEdit.length > 0) document.getElementById("lstEdit").style.display = "block";
else document.getElementById("lstEdit").style.display = "none";
console.log(lstsToEdit);
});
table sort js
$("th").on("click", function() {
var table = this.closest("table");
var selection = $(this).text();
var col = this.cellIndex;
var tbl = [];
var order = [];
for (var rowIndex = 0; rowIndex < table.rows.length; rowIndex++){
if (rowIndex > 0){
tbl.push([]);
for (var colIndex = 0; colIndex < table.rows[rowIndex].cells.length; colIndex++){
tbl[rowIndex-1].push(table.rows[rowIndex].cells[colIndex].innerHTML);
if (colIndex == col){
order.push([]);
order[rowIndex-1].push(tbl[rowIndex-1][colIndex]);
order[rowIndex-1].push(rowIndex-1);
}
}
}
}
for (var rowIndex = table.rows.length-1; rowIndex > 0; rowIndex--){
table.deleteRow(rowIndex);
}
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g
order.sort (function (a,b){
var aA = a[0].replace(reA, "").toLowerCase();
var bA = b[0].replace(reA, "").toLowerCase();
if(aA == bA) {
var aN = parseInt(a[0].replace(reN, ""), 10);
var bN = parseInt(b[0].replace(reN, ""), 10);
return aN == bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
};
});
for (var orderIndex = 0; orderIndex < order.length; orderIndex++){
var row = table.insertRow(orderIndex + 1);
for (var colIndex = 0; colIndex < tbl[orderIndex].length; colIndex++){
var cell = row.insertCell(colIndex);
var index = order[orderIndex][1];
cell.innerHTML = tbl[index][colIndex];
}
}
});
index
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?php
include 'menu.php';
include 'shopJson.php';
?>
<div id="lstEdit">edit</div>
<div id="main"></div>
</body>
</html>
<script>
var lstActURL = "listings/active.json";
var lstInactURL = "listings/inactive.json";
var lstDraftURL = "listings/draft.json";
var sectURL = "listings/sect.json";
var lstAct = JSON.parse($.ajax({url: lstActURL, async: false}).responseText);
var lstInact = JSON.parse($.ajax({url: lstInactURL, async: false}).responseText);
var lstDraft = JSON.parse($.ajax({url: lstInactURL, async: false}).responseText);
var sects = JSON.parse($.ajax({url: sectURL, async: false}).responseText);
$("#mnLstAct").append("(" + lstAct.results.length + ")");
$("#mnLstInact").append("(" + lstInact.results.length + ")");
$("#mnLstDraft").append("(" + lstDraft.results.length + ")");
document.getElementById("mnLstAct").style.fontWeight = "bold";
$.getScript("listings.js");
</script>
The JQuery .attr() method correlates to the actual attributes of a DOM element. However, from the JavaScript perspective, many elements have DOM properties that seem like they are the same as their HTML attribute counterparts, but are not because the property is updated in memory, while the attribute change updates the DOM. Sometimes, there are properties that don't even have an attribute counterpart (i.e. selectedIndex on select elements).
The point is that you have thess lines:
$("#"+lstId).attr("checked", true);
$("#"+lstId).attr("checked", false);
Where you are attempting to force an element to be checked, but that may not correlate to what you get when you check the checked property.
To account for this, use the prop() method instead of the .attr() method:
$("#"+lstId).prop("checked", true);
$("#"+lstId).prop("checked", false);
See the documentation for .prop() for details and a comparison between attributes and properties.

by clicking on input box twice it's printing it's own html code inside input box

I am creating a dynamic table and getting td values from array, my goal was when I click on any cell that convert to input box and get this td value as input value so we can change and when I click on another td the previous td turn back to it's original position with new or same old value.
Now this is almost happening, problem is when I click on td it turn to input box and when I click again on the same input box it prints it's html code inside the text box as it's value and then the all td's go crazy, like this: <input id='thisInputId' type='text' value='"+thisInHtml+"' style='width: 100px;'> it creates two input boxes in same time and sometime prints the html code inside td without creating input box. I am new to these things trying to learn and stuck on this for two days.
var getInput = ""; var inputsParent = ""; var inputs = ""; var thisInHtml = ""; var getInputVal = "";
var thisTdInnerHtml = ""; var input = ""; var flag = 1;
var getInputLength = getInput.length+1;
for(var j=0; j<allTds.length;j++){
allTds[j].onclick = function(){
thisInHtml = this.innerHTML;
var thisId = this.id;
if(inputs.length != 0){
inputsParent.removeChild(inputs);
inputsParent.innerHTML = getInputVal;
flag = 1;
}
this.innerHTML = thisInHtml;
if(getInputVal != ""){
input = this.innerHTML = "<input id='thisInputId' type='text' value='"+thisInHtml+"' style='width: 100px;'>";
getInput = document.getElementsByTagName("input");
getInputVal = document.getElementById("thisInputId").value;
}
if(getInputLength > 0){
for(var k =0; k<getInputLength;k++){
inputsParent = getInput[k].parentNode;
inputs = inputsParent.childNodes[0];
}
}
}
}
}
http://jsfiddle.net/mohsinali/npckf9xs/6/
After some struggle I came up with the solution on my own and I fix the issue, I also figure it out that it's always simple we just have to think right. It can be more optimize I believe.
var getInput = ""; var inputsParent = ""; var inputs = ""; var thisInHtml = ""; var getInputVal = "";
var thisTdInnerHtml = ""; var input = ""; var flag = 0; var thisInputVal = ""; var thisTdId = "";
var cellIndex = ""; var thisRowIndex = "";
for(var j=0; j<allTds.length;j++){
allTds[j].ondblclick = function(){
thisInHtml = this.innerHTML;
getInput = document.getElementsByTagName("input");
if(getInput.length === 0){
input = this.innerHTML = "<input id='thisInputId' type='text' value='"+thisInHtml+"' style='width: 100px;'>";
thisTdId = this.id;
cellIndex = this.cellIndex;
var rows = document.getElementsByTagName('tr');
for(var o=0; o<rows.length;o++){
rows[o].ondblclick = function(){
thisRowIndex = this.rowIndex-1;
}
}
}
else if(getInput.length > 0){
for(var k=0; k<getInput.length; k++){
inputsParent = getInput[k].parentNode;
inputs = inputsParent.childNodes[0];
thisInputVal = inputs.value;
inputsParent.removeChild(inputs);
flag = 1;
}
}
if(flag === 1){
var getTdById = document.getElementById(thisTdId);
getTdById.innerHTML = thisInputVal;
if(cellIndex === 0){
proArr[thisRowIndex] = thisInputVal;
}
else if (cellIndex === 1){
proColorArr[thisRowIndex] = thisInputVal;
}
else if (cellIndex === 2){
proPriceArr[thisRowIndex] = thisInputVal;
}
flag = 0;
}
}
}
}

Javascript and multiple select values

I have a form with 2 <select>, select1 allows simple selection and select 2 allows multiple selection. What I want is, when the user select something in select1, associated data in select2 should be selected according to my array of data.
function selectIt() {
var divArray = new Array();
// this is the value for first element on select1
divArray[0] = 3;
// these are the corresponding values on select2 that should be selected
divArray[0] = new Array();
divArray[0][0] = 5;
divArray[0][1] = 1;
divArray[0][2] = 2;
// and so on
divArray[1] = 2;
divArray[1] = new Array();
divArray[1][0] = 6;
divArray[1][1] = 3;
divArray[1][2] = 2;
var select2 = document.getElementById("secondSelect");
for (var i=0; i < select2.options.length; i++)
select2.options[i].selected = false;
}
So if the user selects index 1, in select2 items 2,3 and 6 should be selected.
First I deselect previously selected items using:
var select2 = document.getElementById("secondSelect");
for (var i=0; i < select2.options.length; i++)
select2.options[i].selected = false;
After that, I do not know what to do.
some loop here
select2.options[i].selected = true;
Any help will be greatly apreciated!!!!
You can declare arrays in this way:
divArray[0] = [5, 1, 2];
I will just try to answer by writing it without testing so bare in mind it can have some errors:
document.getElementById("firstSelect").onchange = function() {
var optionIndex = this.selectedIndex; // in this function 'this' is select element
var optionsToSelect = divArray[optionIndex];
var select2 = document.getElementById("secondSelect");
for (var i = 0; i < optionsToSelect.length; i++){
select2.options[optionsToSelect[i]].selected = true;
}
};
Becuase I need some database data I combined some PHP code inside the JS:
<script type="text/javascript">
function selectM() {
var divArray = new Array();
<?
if ($result = $database->getDivs()){
$cont = 0;
while ($divs = mysql_fetch_array($result)) {
$da = "divArray[".$divs['iddiv']."]";
if ($resultEd = $database->getEdic($divs['iddiv'])){
if ($cont == 0) $da .= " = [";
$tot = mysql_num_rows($resultEd);
while ($divEd = mysql_fetch_array($resultEd)) {
$da .= $divEd['ed_id']." ";
$cont++;
if ($cont < $tot) $da .= ", ";
}
}
$da .= "]; ";
$cont = 0;
echo $da;
}
}
?>
var largo, valor;
var inexE = document.getElementById("idDiv").value ;
var ediciones = document.getElementById("ediciones");
if (inexE > 0) {
var toSelect = divArray[inexE];
for (var i=0; i < ediciones.options.length; i++) {
ediciones.options[i].selected = false;
valor = ediciones.options[i].value;
largo = toSelect.length;
for(var j = 0; j < largo; j++) {
if(toSelect[j] == valor)
ediciones.options[i].selected = true;
}
}
} else {
for (var i=0; i < ediciones.options.length; i++)
ediciones.options[i].selected = false;
}
}
</script>
Works perfect!
Thank you for pointing me in the right direction!!!

Javascript function not recognizing id in getElementById

I am adding a row to a table, and attached an ondblclick event to the cells. The function addrow is working fine, and the dblclick is taking me to seltogg, with the correct parameters. However, the var selbutton = document.getElementById in seltogg is returning a null. When I call seltogg with a dblclick on the original table in the document, it runs fine. All the parameters "selna" have alphabetic values, with no spaces, special characters, etc. Can someone tell me why seltogg is unable to correctly perform the document.getElementById when I pass the id from addrow; also how to fix the problem.
function addrow(jtop, sel4list, ron4list) {
var tablex = document.getElementById('thetable');
var initcount = document.getElementById('numrows').value;
var sel4arr = sel4list.split(",");
var idcount = parseInt(initcount) + 1;
var rowx = tablex.insertRow(1);
var jtop1 = jtop - 1;
for (j = 0; j <= jtop1; j++) {
var cellx = rowx.insertCell(j);
cellx.style.border = "1px solid blue";
var inputx = document.createElement("input");
inputx.type = "text";
inputx.ondblclick = (function() {
var curj = j;
var selna = sel4arr[curj + 2];
var cellj = parseInt(curj) + 3;
inputx.id = "cell_" + idcount + "_" + cellj;
var b = "cell_" + idcount + "_" + cellj;
return function() {
seltogg(selna, b);
}
})();
cellx.appendChild(inputx);
} //end j loop
var rowCount = tablex.rows.length;
document.getElementById('numrows').value = rowCount - 1; //dont count header
} //end function addrow
function seltogg(selna, cellid) {
if (selna == "none") {
return;
}
document.getElementById('x').value = cellid; //setting up for the next function
var selbutton = document.getElementById(selna); //*****this is returning null
if (selbutton.style.display != 'none') { //if it's on
selbutton.style.display = 'none';
} //turn it off
else { //if it's off
selbutton.style.display = '';
} //turn it on
} //end of function seltogg
You try, writing this sentence:
document.getElementById("numrows").value on document.getElementById('numrows').value
This is my part the my code:
contapara=(parseInt(contapara)+1);
document.getElementById("sorpara").innerHTML+="<li id=\"inputp"+contapara+"_id\" class=\"ui-state-default\"><span class=\"ui-icon ui-icon-arrowthick-2-n-s\"></span>"+$('#inputp'+contapara+'_id').val()+"</li>";
Look you have to use this " y not '.
TRY!!!!

jQuery: Initial data for rating

I have found a pretty stuff for rating entries: http://www.fyneworks.com/jquery/star-rating/. It's good and easy. But I still need some more.
My code:
<div data-rating="4/5" class="entry"></div>
Desired function:
function init_rating(rate) { //... }
$(".entry").html( init_rating($(this).attr("data-rating")) );
Thanks much,
Here:
function init_rating(selector) {
var entry = $(selector);
var output = "";
var input = "<input name=\"star\" type=\"radio\" class=\"star\""
var checked = " checked=\"checked\"";
var close = "/>";
var params = entry.attr("data-rating").split("/", 2);
var rating = parseInt(params[0]);
var total = parseInt(params[1]);
for (var i = 0; i < total; i++) {
output += input;
if (i == rating - 1) output += checked;
output += close;
}
entry.html(output);
$('input[type=radio].star').rating();
}
init_rating(".entry");
fiddle: http://jsfiddle.net/qcxvW/20/

Categories

Resources