as before the below code is in a while loop . it out puts values id=pro0 then next loop through i get id=pro1 and if i have another record i get id=pro3
print "<td><input style=\"text-align:center\" type=\"text\" name=\"productitemsupdate_$num\" value=\"$row[productitems]\" size=\"5\" id=\"pro$num\"></td>";
the above code works with
var pro = document.getElementById('pro0');
what im after is a loop in java script which will take the last $num from the php from and use that for the amount of times to loop the javascript function.
something like this i think
var i=0;
while (i<=$num) {
var pro[i] = document.getElementById('pro'[i]);
if (pro[i].value == "") {
inlineMsg('pro'[i],'This cannot Be blank'[i],10);
return false;
} else {
i++;
}
}
breaks when it is false when all fields are right it is true.
if i get this working it will save me guessing how many variable to check.
i have tried this but i cant this working either
var i=0;
var pro[i] = document.getElementById('pro' + i);
for(var i = 0; i < <?php $num ?>; i++) {
if(pro[i].value == "")
alert("You entered: " + pro[i].value)
return false;
}
this works but only for the first line. if the 2nd line is emtpy and the first line is not it does not produce the alert
var i=0;
for(var i = 0; i < 3; i++) {
var pro = document.getElementById('pro' + i);
if(pro.value == "")
alert("You entered: " + pro[i].value)
return false;
}
i also changed the $num variable to a static number for my test record to see if it was my variable not being passed and it still did't work for the 2nd record any ideas
thanks
steve
working solution thanks for your help
var i=0;
var pro = [];
for(var i = 0; i < 2; i++) {
pro[i] = document.getElementById('pro' + i);
if(pro[i].value == ""){
alert("You entered: " + pro[i].value)
return false;}
}
PHP is server-side. JavaScript is client-side. If you want to insert a PHP variable into JavaScript, you have to treat your JS like HTML and use PHP to create the script. Something like this:
<!-- ... -->
<script>
var num = <?php echo $num ?>;
</script>
<!-- ... -->
Then you can use this value of num elsewhere, even in external scripts (as long as num is declared beforehand).
Edit
Your if statement in the for loop is missing braces. Try this:
var i=0,
pro[i] = document.getElementById('pro' + i);
for(var i = 0; i < <?php echo $num ?>; i++) {
if(pro[i].value == "")
{
alert("You entered: " + pro[i].value)
return false;
}
}
Make sure that this JS is actually being processed by PHP. The easiest way to do that is to put the code into an inline <script> tag.
In javascript, you concatenate strings using +. Therefore, you need to write
pro[i] = document.getElementById('pro' + i);
For your loop, that'd look something like
for(var i = 0; i < <?php echo $num ?>; i++) {
...
}
Complete code:
var i=0;
var pro = [];
for(var i = 0; i < <?php echo $num ?>; i++) {
pro[i] = document.getElementById('pro' + i);
if(pro[i].value == "") {
alert("You entered: " + pro[i].value)
return false;
}
}
If you don't need the actual array for anything, for later, you could simply do:
var i=0;
for(var i = 0; i < <?php echo $num ?>; i++) {
var pro = document.getElementById('pro' + i);
if(pro.value == "") {
alert("You entered: " + pro.value)
return false;
}
}
What ever your PHP (not my expertise), here is an example looping through: http://jsfiddle.net/UpG57/
Related
i wrote some codes in Codeigniter to assign query result into each polygons with $.getJSON but i found some problems.
Here is my $.getJSON code
$.getJSON("<?php echo base_url(); ?>Request/showData", function(data) {
var area_data = new Array(3);
var total_data = new Array(3);
for (var i = 0; i < data.length; i++) {
area_data[i] = data[i].Area;
total_data[i] = data[i].total;
}
layer.bindPopup(area_data + ':' + total_data);
})
from this js script, i got this kind of result
The expected result is each polygon shows its alphabet and value same like the red color. but right now i have each polygon shows all alphabets and values from query.
model function
public function map()
{
$query = $this->db->query(
"SELECT Area, sum(Value) as total from ( select Area,Value from try_1 union all select Area,Value from try_2 ) view_vall group by Area"
);
return $query->result_array();
}
controller function
public function showData()
{
$aa = $this->model_request->map();
echo json_encode($aa);
}
Thanks in advance
turns out that i found the answer..
it needs to add conditional with if after the looping and add variable to put value inside bindpopup.
$.getJSON("<?php echo base_url(); ?>Request/showData", function(data) {
var area_data = new Array(3);
var total_data = new Array(3);
for (var i = 0; i < data.length; i++) {
area_data[i] = data[i].Area;
total_data[i] = data[i].total;
}
var popup;
if (feature.properties.Area == 'A') {
popup = area_data[0] + ':' + total_data[0];
} else if (feature.properties.Area == 'B') {
popup = area_data[1] + ':' + total_data[1];
} else {
popup = area_data[2] + ':' + total_data[2];
}
layer.bindPopup(popup);
})
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!
I'm trying to manipulate my HTML table using datavalues from an SQL database that I'm extracting using PHP.
I've tried a tonne of different ways but I think the best way would be how I am approaching it now, by using a loop to assign an ID tag number corresponding to the Matrix Value of that array.
(EXAMPLE: 11, 12, 13, 21, 22, 23 etc..)
I am then calling a JavaScript function to find the element with that particular ID and replace the value with the SQL Data taken out by the PHP code.
I've inspected the elements on Chrome and can see the data going into the function but the values within the table are staying blank and not being set to the values from the mySQL.
Any help or suggestions will be greatly appreciated.
<?php
$sql = "SELECT * FROM `stock` WHERE 1";
$tableHeader = "<body><center><div><table id=\"infoTable\" class=\"myTable \"><tr><th></th><th> 1 </th><th> 2 </th><th> 3 </th></tr>";
$r_query = mysql_query($sql);
//To Table Details
//prints StackerReclaimer_StatusTable;
include("SR_TableStatus.php");
// output data of each row
echo $tableHeader;
for ($i=1;$i<5;$i++){ //Rows
$row = mysql_fetch_array($r_query);
if($i == 2 || $i==4)
echo"<tr><td> </td></tr>";
echo"<tr><td class = \"leftCol\"> Bed ".($i)."</td>";
for ($j=1;$j<4;$j++){ //Cols
echo"<td bgcolor=\"#E9E6E5\" id =\"$i$j\"></td>";
/***************************************/
$data = strtoupper($row["sortcode"])." (".(($row["stock"])/1000)."k)";
if( $row["bednumber"] == $i && $row["pilenumber"] == $j ){
// echo"<td bgcolor=\"#E9E6E5\" id = $i$j>".strtoupper($row["sortcode"])." (".(($row["stock"])/1000)."k)</td>";
echo "<script>swapValue($i$j, ".$data.");</script>";
}
/***************************************/
}
echo"</tr>";
}
echo "</table></div></body></center>";
?>
<!-- This script allows user to click on table rows to direct user to More info for that Coal -->
<script>
function swapValue(var location, var data){
var s = document.getElementById(location);
s.value = data;
}
var table = document.getElementById("infoTable");
if (table != null) {
for (var i = 1; i < table.rows.length; i++) {
for (var j = 1; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
myFunc();
};
}
}
function tableText(tableCell) {
//alert(tableCell.innerHTML);
var Val = tableCell.innerHTML;
Val = Val.substring(0,7);
document.getElementById("searchBox").value = Val;
document.getElementById("searchButton").click();
}
</script>
echo "</table></div></body></center>"
first you did not end the tag properly. you placed out of body
second your block is not even inside body block
so i suggest you rewrite like this
<body>
<div>
<table id="infoTable" class="myTable">
<tr><th></th><th> 1 </th><th> 2 </th><th> 3 </th></tr>
<?php
$sql = "SELECT * FROM `stock` WHERE 1";
$r_query = mysql_query($sql);
//To Table Details
//prints StackerReclaimer_StatusTable;
include("SR_TableStatus.php");
// output data of each row
for ($i=1;$i<5;$i++){ //Rows
$row = mysql_fetch_array($r_query);
if($i == 2 || $i==4)
echo"<tr><td> </td></tr>";
echo"<tr><td class = \"leftCol\"> Bed ".($i)."</td>";
for ($j=1;$j<4;$j++){ //Cols
echo"<td bgcolor=\"#E9E6E5\" id =\"$i$j\"></td>";
/***************************************/
$data = strtoupper($row["sortcode"])." (".(($row["stock"])/1000)."k)";
if( $row["bednumber"] == $i && $row["pilenumber"] == $j ){
// echo"<td bgcolor=\"#E9E6E5\" id = $i$j>".strtoupper($row["sortcode"])." (".(($row["stock"])/1000)."k)</td>";
echo "<script>swapValue($i$j, ".$data.");</script>";
}
/***************************************/
}
echo"</tr>";
}
?>
</table>
</div>
<!-- This script allows user to click on table rows to direct user to More info for that Coal -->
<script>
function swapValue(var location, var data){
var s = document.getElementById(location);
s.value = data;
}
var table = document.getElementById("infoTable");
if (table != null) {
for (var i = 1; i < table.rows.length; i++) {
for (var j = 1; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
myFunc();
};
}
}
function tableText(tableCell) {
//alert(tableCell.innerHTML);
var Val = tableCell.innerHTML;
Val = Val.substring(0,7);
document.getElementById("searchBox").value = Val;
document.getElementById("searchButton").click();
}
</script>
</body>
I've found a way to get the outcome needed.
After standing back and taking a break to rest the mind & Eyes, I've came back with fresh eyes and have now solved the issue, i was cluttering up the code by using javascript into the php which just adds to a mess if anyone was to decode or read.
so what the code does is reads values from an SQL database using PHP, reads the bednumber(Location(y)) and pileNumber(location(x))
it then makes the table using the for loops I for Rows and J for Columns,
then each column increment you need to update the SQL Query being sent back with the new cell location $i & $j which are held in the bed and pile number values.
i will post the code that now works, but any suggestions or corrections are gratefully appreciated.
<?php
$tableHeader = "<body><center><div><table id=\"infoTable\" class=\"myTable \"><tr><th></th><th> 1 </th><th> 2 </th><th> 3 </th></tr>";
//prints StackerReclaimer_StatusTable;
include("SR_TableStatus.php");
// output data of each row
echo $tableHeader;
/*####################################*/
for ($i=1;$i<5;$i++){
//$row = mysql_fetch_array($r_query);
if($i == 2 || $i==4)
echo"<tr><td> </td></tr>";
echo"<tr><td class = \"leftCol\"> Bed ".($i)."</td>";
for ($j=1;$j<4;$j++){
$sql = "SELECT * FROM `stock` WHERE `bednumber` = $i AND `pilenumber` = $j";
$r_query = mysql_query($sql);
$row = mysql_fetch_array($r_query); //Creates a loop to loop through results
if( $row["bednumber"] == $i && $row["pilenumber"] == $j ){
echo"<td bgcolor=\"#E9E6E5\">".strtoupper($row["sortcode"])." (".(($row["stock"])/1000)."k)</td>";
}
else
echo"<td bgcolor=\"#E9E6E5\"> --- </td>";
}
echo"</tr>";
} /*################################*/
echo "</table></div></center></body>";
?>
<!-- This script allows user to click on table rows to direct user to More info for that Coal -->
<script>
var table = document.getElementById("infoTable");
if (table != null) {
for (var i = 1; i < table.rows.length; i++) {
for (var j = 1; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
};
}
}
function tableText(tableCell) {
//alert(tableCell.innerHTML);
var Val = tableCell.innerHTML;
Val = Val.substring(0,7);
document.getElementById("searchBox").value = Val;
document.getElementById("searchButton").click();
}
</script>
I have the following code:
while ($row = $result->fetch_assoc()) {
echo "<div class='competitor' style='background: ".$row['Colour'].";'>";
echo "<div class='competitorname'>".$row['CompetitorName']."</div><br>";
echo "<div class='competitorscore' id='".$row['CompetitorID']."'>";
echo"<label id='".$row['CompetitorName']."'></label></div>";
echo "<input type='button' value='Increase' id='inc' onclick='incNumber()'/>";
echo "<input type='button' value='Decrease' id='dec' onclick='decNumber()'/>";
}
The code is linked to the following script:
var i = 0;
function incNumber() {
if (i < 10) {
i++;
} else if (i = 10) {
i = 0;
}
document.getElementById('display').innerHTML = i;
}
function decNumber() {
if (i > 0) {
--i;
} else if (i = 0) {
i = 10;
}
document.getElementById('display').innerHTML = i;
}
The code creates a scoreboard. It creates a div for each team with a score for that team.
The problem I'm having is that the "Increase" and "Decrease" buttons are increasing and decreasing the score on only one team (the first one). This is because the script is looking for the label with the id='display' and linking every button to that one.
My question is, how can I create a different ID for each team that works with the script so that each increase/decrease button is linked to a different team?
Use the CompetitorID as a parameter to the increment and decrement functions to tell it which row to affect. Your label:
<label id='display".$row['CompetitorID']."'></label>
Your button onclick event:
onclick='incNumber(".$row['CompetitorID'].")'
Then your JavaScript:
function incNumber(id) {
if (i < 10) {
i++;
} else if (i = 10) {
i = 0;
}
document.getElementById('display' + id).innerHTML = i;
}
Edit
For the issue in the comments, echo a hidden field which stores the value for each team:
<input type='hidden' id='score".$row['CompetitorID']."' value='0'/>
Then remove the global var i = 0; and modify your functions similar to this:
function incNumber(id) {
// Get the score input
var scoreField = document.getElementById('score' + id);
// Get the value
var i = parseInt(scoreField.value);
if (i < 10) {
i++;
} else if (i = 10) {
i = 0;
}
// Set the visual score
document.getElementById('display' + id).innerHTML = i;
// Set the score input to the new score
scoreField.value = i;
}
You have a $row['CompetitorID'] value which is, presumably, unique. Append that to the IDs you are using.
In android phonegap application, I created 5 or more question with respective option (checkboxes) in div dynamically. Each question and respective option have same id. Now I want to know how many question are answered/how many questions are not answered while clicking submit button.
please guide me. Thanks in advance.
My code is:
for dynamic div: retrive value from local database
function list(results){
for (i = 0; i < results.rows.length; i++) {
$("#poll").append("<li id='"+i+"'>"+results.rows.item(i).ques+"</li>"+"<br/>" );
var optiontypearray = new Array();
var arr = results.rows.item(i).option;
var optiontypearray=arr.split(" ");
for(var j=0; j<optiontypearray.length; j++) {
$("#poll").append("<input id='"+i+"' name='ckbox' value='"+optiontypearray[j]+"' type='checkbox'/>"+optiontypearray[j]+"<br/>");
}
}
}
for submit button:get question with respective answer
function submit(){
$answers = $(':checked');
var $questions=$('li');
$answers.each(function(index,el) {
var list1=$(this).attr("id");
alert("list1:"+list1);
var val=$('#'+list1).val();
alert($questions.eq(list1).html() + ' : ' + $(el).val());
});
}
HTML:
<div id="poll">
This is what happens when you click submit button.
$('#submit').click(function () {
var questionsAnswered = questionsNotAnswered = 0
var arrQuestions = new Array();
$('li').removeAttr('style').each (function (i) {
if ($(this).children('input:checked').length > 0) {
var ans = '';
$(this).children('input:checked').each(function () {
ans+= $(this).val() + ', ';
});
arrQuestions[questionsAnswered] = new Array($(this).attr('id'), ans);
questionsAnswered++;
} else if ($(this).attr('class') == 'required' && $(this).children('input:checked').length == 0) {
$(this).css({border : '1px solid red'});
questionsNotAnswered++;
alert($(this).clone().children('span').remove().end().text());
}
});
$('div#finalResults').html("Questions Answered : " + questionsAnswered + "<br /> Questions Not Answered : " + questionsNotAnswered);
});
$.each (arrQuestions, function () {
$('div#finalResults').append("<br /> Q: " + this[0] + " A: " + this[1]);
});
Demo. http://jsfiddle.net/tmM76/9/
Please note that the code in list() function might change as per your existing code which you did not share ;-).
u can do something like..
var qanswered;
for( j = 0; j < numberofQuestions; j++){
qanswered = false;
ques = questions[j];
for( k = 0; k < ques.choices.length; k++){
btn = $('.ui-page-active input#'+k); // k is your choice id whatever way u define it
if(btn[0].checked){
qanswered = true;
}
}
if(!qanswered){
//this question is not answered, do something
}
}
btn gets the jquery object of the inputs one by one, of the ques