I am trying to obtain the values of dynamically created select dropdowns from my php page. The dropdowns were added via javascript to the page.
The error that I get is Notice: Undefined index: daySelect in C:\wamp\www\responsive2\select.php on line 7
I would like to know how to access posted select dropdowns values with php.
Thanks in advance.
Code follows
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST"){
echo "We have something";
echo ($_POST['daySelect']); // error here
}
else
{
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dynamic Select</title>
</head>
<body>
<form id="theform" style="display: none" method="POST" name="theform" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="placeHere"></div>
<button type="submit">Submit</button>
</form>
<button onclick="createSelect()">Create</button>
<script>
var elem = document.getElementById('placeHere');
var daySelect = new Array();
var theForm = document.getElementById('theform');
var numSelects = 0;
var days = ['01','02','03','04','05','06','07','08','09','10',
'11','12','13','14','15','16','17','18','19','20',
'21','22','23','24','25','26','27','28','29','30',
'31'];
function createSelect()
{
numSelects++;
daySelect.push(document.createElement('select'));
daySelect[daySelect.length -1].setAttribute('id',
daySelect[daySelect.length -1]);
daySelect[daySelect.length -1].name = daySelect[daySelect.length -1];
var opt = document.createElement('option');
opt.text = "Select";
opt.value = "";
//myArray[myArray.length - 1];
daySelect[daySelect.length -1].appendChild(opt);
for (var i = 0; i < 31; i++)
{
var opt = document.createElement("option");
opt.text = days[i];
opt.value = days[i];
//opt.className = i;
//optarr.push(opt[i]);
daySelect[daySelect.length -1].appendChild(opt);
}
elem.appendChild(daySelect[daySelect.length -1]);
theForm.style.display = "block";
//alert("HI");
}
</script>
</body>
</html>
<?php
}
?>
You need to set your select "name" and "id" to a string name. Right now you are setting those 2 attributes to the daySelect object value, which is getting interpreted as a string, so you have:
<select id="[object HTMLSelectElement]" name="[object HTMLSelectElement]">
Update the the .setAttribute and .name lines to:
daySelect[daySelect.length - 1].setAttribute('id',
'daySelect' + (daySelect.length - 1));
daySelect[daySelect.length - 1].name = 'daySelect[]';
The name is set to an array because of the [], so you could just loop through $_POST['daySelect'], with PHP, using a foreach.
Change the echo to print_r to view array values in the browser.
Hope that helps.
Related
I have a form which takes a student name, subject and age. When submitted, it saves the data as an array in txt file. Next time, when I put new data and submit it, it creates a new array in that txt file instead of appending it to the previous array.
<?php
if(!empty($_GET)){
$student = [];
$student['name'] = $_GET['name'];
$student['subject'] = $_GET['subject'];
$student['age'] = $_GET['age'];
$studentArray = [];
array_push($studentArray, $student);
$str = print_r($studentArray, true);
file_put_contents('student.txt', $str, FILE_APPEND);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="" method="GET">
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<label for="name">Subject:</label>
<input type="text" name="subject" id="subject">
<label for="name">Age:</label>
<input type="number" name="age" id="age">
<input type="submit" name="submitButton">
</form>
</body>
</html>
output looks like this:
however I want to save it like below:
How could I do that?
If you really have to see your nice array in text use this:
if(!empty($_GET)){
$student = array();
$int = 0;
$txtfile = "student.txt";
if (file_exists($txtfile)) {
$fgc = file_get_contents($txtfile);
$expl = explode("[".$int."] => Array", $fgc);
while (count($expl) > 1) {
$expl2 = (count($expl) > 1) ? explode("[".($int+1)."] => Array", $expl[1])[0] : $expl[1];
$m = preg_match_all("#\\[([\d\w]+)\\] => ([^\n]*)#imus", $expl2, $matches);
if ($m == 0) { break; }
foreach ($matches[1] as $key => $val) {
$student[$int][$val] = $matches[2][$key];
}
$int++;
$expl = explode("[".$int."] => Array", $fgc);
}
}
$student[$int]['name'] = $_GET['name'];
$student[$int]['subject'] = $_GET['subject'];
$student[$int]['age'] = $_GET['age'];
$str = print_r($student, true);
file_put_contents('student.txt', $str);
print_r($student);
}
But please use a serialized version like this:
if(!empty($_GET)){
$student = array();
$int = 0;
$txtfile = "student.txt";
if (file_exists($txtfile)) {
$fgc = file_get_contents($txtfile);
$student = unserialize($fgc);
$int = count($student);
}
$student[$int]['name'] = $_GET['name'];
$student[$int]['subject'] = $_GET['subject'];
$student[$int]['age'] = $_GET['age'];
file_put_contents('student.txt', serialize($student));
print_r($student);
}
print_r for debug only.
Have fun ;)
You have to use JSON in order to update your array constantly.
the important point is you have to load your students in a variable and then push the new student to that variable so, in the end, you can save your students variable which contains all students in one array like you want.
Requirements to make this code works:
Create a file named student.json and put [] inside the file
Also, I highly suggest go and learn about JSON in PHP so you can have a better understanding of how this code is working now
if(!empty($_GET)){
$student = [];
$student['name'] = $_GET['name'];
$student['subject'] = $_GET['subject'];
$student['age'] = $_GET['age'];
$studentArray = json_decode( file_get_contents('student.json'), true);
array_push($studentArray, $student);
$str = print_r($studentArray, true);
file_put_contents('student.json', json_encode($studentArray));
}
UPDATED:
I am using RecursiveIteratorIterator to scan the directories to read index.html file.
Now, based on the Pubname and Pubversion, i am trying to read the corresponding index.html file, to get the values of Readability Grade, Readability Score etc. (by storing the values in local storage)
The values are fetched from local storage if i use the html and JS code separately, but after i integrate into php, it is not working.
Code:
<?php
//error_reporting(0);
//Get Pub version
function get_version($path){
$needle = "=";
if(($pos = strpos($path, $needle)) != 0){
$bits = str_split($path, $pos + strlen($needle));
$integer_count = 0;
for($x = 0; $x < strlen($bits[1]); $x++){
if(is_numeric($bits[1][$x])){
$integer_count++;
}else{
break;
}
}
if($integer_count > 0){
$bits = str_split($bits[1], $integer_count);
return $bits[0];
}
}
return -1;
}
$it = new RecursiveDirectoryIterator("C:\Users\Sachin_S2\Desktop\Script");
foreach(new RecursiveIteratorIterator($it,RecursiveIteratorIterator::SELF_FIRST) as $file) {
//IGNORE FILE TYPES
//$filetypes = array("jpg", "png", "pdf", "css", "csv","log","txt");
$htmlfiles = array("html");
$filetype = pathinfo($file, PATHINFO_EXTENSION);
if (in_array(strtolower($filetype), $htmlfiles)) {
// skip dot files while iterating
$it->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
$files = array($file);
$pathname = $file->getPathname();
print_r($pathname);
$version = get_version($pathname);
if($version > 0){
// use $version to read correct file
include 'html/home.html';
}
echo '*********************************************************************************'.'<br/><br/>';
}
}
html/home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>SEO Metrics</title>
</head>
<body>
<!--Begin script code-->
<form name="myform3">
<!--
<input type="hidden" name="formvar" value="">
<input type="file" name="file" id="file">
<p id="demo"></p><br/><br/>
-->
<div class="form-group">
<label>Readability Grade:</label>
<input type="text" class="form-control" id="grade">
</div>
<div class="form-group">
<label>Readability Score:</label>
<input type="text" class="form-control" id="score">
</div>
<div class="form-group">
<label>Total Word Count:</label>
<input type="text" class="form-control" id="words">
</div>
</form>
<!--END script code-->
<!--Custom JS code-->
<script src="js/home.js"></script>
</body>
</html>
js/home.js
$(document).ready(function() {
document.getElementById('file').onchange = function() {
const file = this.files[0];
const reader = new FileReader();
reader.onload = (event) => {
const file = event.target.result;
const allLines = file.split(/\r\n|\n/);
let arr = allLines;
arr.forEach((kv) => {
if (kv.includes("Flesh-Kincaid Grade Level")) {
var fetch_grade = kv.replace(/<\/?[^>]+(>|$)/g, "");
var formated_grade = fetch_grade.split(":").pop(); //Remove part of the string before ":"
localStorage.setItem("Readability_Grade", formated_grade);
document.getElementById('grade').value = localStorage.getItem("Readability_Grade").replace(/\s/g, ""); //Assign localStorage to text box
localStorage["Readability_Grade"] = grade.value;
//alert(formatedgrade);
}
if (kv.includes("Flesh Reading Ease Score")) {
var fetch_score = kv.replace(/<\/?[^>]+(>|$)/g, "");
var formated_score = fetch_score.split(":").pop();
localStorage.setItem('Readability_Score', formated_score);
document.getElementById('score').value = localStorage.getItem("Readability_Score").replace(/\s/g, "");
//alert(formatedscore);
}
if (kv.includes("Reuse Metrics Score")) {
var metricscore = kv;
//alert(metricscore);
}
if (kv.includes("Total words")) {
var totalwords = kv.replace(/<\/?[^>]+(>|$)/g, "");
var total_words_formated = totalwords.split(":").pop();
localStorage.setItem('Word_Count', total_words_formated);
document.getElementById('words').value = localStorage.getItem("Word_Count").replace(/\s/g, "");
//alert(totalwords);
}
});
};
reader.onerror = (event) => {
alert(event.target.error.name);
};
reader.readAsText(file);
};
});
Output:
On reading this php script, i should be able to read index html (for each file paths - based on pubname and version), and get the values of Readability_Grade and score etc., which i am not able to get.
Firstly get the version number from the string, below is a method to do just that.
function get_version($path){
$needle = "Pub=";
if(($pos = strpos($path, $needle)) != 0){
$bits = str_split($path, $pos + strlen($needle));
$integer_count = 0;
for($x = 0; $x < strlen($bits[1]); $x++){
if(is_numeric($bits[1][$x])){
$integer_count++;
}else{
break;
}
}
if($integer_count > 0){
$bits = str_split($bits[1], $integer_count);
return $bits[0];
}
}
return -1;
}
And then you can use it like this.
foreach ($paths as $path){
$version = get_version($path);
if($version > 0){
// use $version to read correct file
}
}
Thats if I undertoood your question.
Disclaimer: Quickly typed up but should work.
I am trying to create forms dynamically using javascript, but I struggled with creating radio buttons in the form properly. The problem is I can't display a label beside each radio button
here is the index.html file
<!DOCTYPE html>
<html>
<head>
<title>Javascript</title>
</head>
<body>
<form id="myform">
</form>
<script type="text/javascript" src="custom.js"></script>
</body>
</html>
and the custom.js file
document.body.onload = newElement;
function newElement() {
var form = document.getElementById("myform");
var questions = {
name : "q1",
qType : "radio",
qLabel : "Is your system is automated online advising?",
options : ["Yes", "No"]
}
var label = document.createElement("label");
var lblContent = document.createTextNode(questions["qLabel"]);
label.appendChild(lblContent);
form.appendChild(label);
switch(questions["qType"]) {
case "radio":
var input = [];
var option;
var optionContent;
for(var i = 0; i < questions["options"].length; i++) {
input[i] = document.createElement("input");
input[i].setAttribute("type", questions["qType"]);
input[i].setAttribute("name", questions["name"]);
option = document.createElement("label");
optionContent = document.createTextNode(questions["options"][i]);
option.appendChild(optionContent);
input[i].appendChild(option);
form.appendChild(input[i]);
}
break;
}
}
Replace the last two lines of the for loop with
form.appendChild(input[i]);
form.appendChild(option);
I'm using google sheets and I'm creating a document that will pull through employees that are out of the office. I have a menu option to remove employee data, and it opens the sidebar where I have an HTML form (Image of my project). I'm trying to have it generate a dropdown list of current employees on the list.
I've developed the code to pull through the data I need:
function removeAnyone() {
var html = HtmlService.createHtmlOutputFromFile('RemoveAnyone');
SpreadsheetApp.getUi()
.showSidebar(html);
}
function getList() {
var headerRows = 1;
var sheet = SpreadsheetApp.getActive().getSheetByName("Data");
var range = sheet.getRange(headerRows + 1, 1, sheet.getMaxRows() - headerRows, 1);
var arrayValues = range.getValues();
return arrayValues;
}
Now we move over to my html, where I am simply trying to load the dropdown list using a for loop in the header:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function addOption_list() {
document.getElementById("output").innerHTML = "test";
var options = google.script.run.getList();
for (var i = 0; i < options.length; ++i;) {
var optn = document.createElement("OPTION");
optn.text = options[i];
optn.value = options[i];
document.myForm.selectEmployee.options.add(optn);
}
}
</script>
</head>
<body onload="addOption_list()">
<form id="myForm" onsubmit="submitForm(this)">
<select id="selectEmployee">
<option>Choose an employee</option>
</select>
</form>
<div id="output"></div>
</body>
</html>
I threw a div in the body and have the function changing the value to "test" at the start, this was just to check and see if the function was even being called, which it doesn't seem like it is.
I also tried using window.onload (as shown below), but that didn't get me anywhere either.:
window.onload = function {
document.getElementById("output").innerHTML = "test";
var options = google.script.run.getList();
for (var i = 0; i < options.length; ++i;) {
var optn = document.createElement("OPTION");
optn.text = options[i];
optn.value = options[i];
document.myForm.selectEmployee.options.add(optn);
}
}
Any guidance you can give me would be really appreciated!
google.script.run doesn't return values. When you want to return values from GAS, please use withSuccessHandler. And the data retrieved by getValues() is 2 dimensional array. So how about this modification?
Modified script :
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
window.onload = function() {
google.script.run.withSuccessHandler(addOption_list).getList();
}
function addOption_list(options) {
document.getElementById("output").innerHTML = "test";
var select = document.getElementById('selectEmployee');
for ( var i in options) {
var optn = document.createElement('option');
optn.value = options[i][0];
optn.text = options[i][0];
select.appendChild(optn);
}
}
</script>
</head>
<body>
<form id="myForm" onsubmit="submitForm(this)">
<select id="selectEmployee">
<option>Choose an employee</option>
</select>
</form>
<div id="output"></div>
</body>
</html>
Reference :
google.script.run
getValues()
If I misunderstand your question, I'm sorry.
I have 3 checkboxes and 1 textbox
i use only these controls mentioned above ..
I want ---- when i check checkbox1 and checkbox2 then it will display in textbox1 as 1,2 as it is as the same ascending order not 1,2, or 2,1,
I use this type of coding in asp.net (VB) , i wanna use this coding for 45 checkboxes........
Can anybody solve this problem in asp.net (vb)
JS solution (needs adaptation to your markup) as question is tagged with javascript
<html>
<head>
<title>S.O. 4121588</title>
<script type="text/javascript">
var gMax = 45;
function $(aId) {
return document.getElementById(aId);
}
// generates gMax checkboxes with value from 1 to gMax
function onload() {
var form = $('theForm');
for (var i = 1; i != gMax; i++) {
var cb = document.createElement('input');
cb.setAttribute('type', 'checkbox');
cb.setAttribute('id', 'checkbox-' + i);
cb.setAttribute('value', i);
form.appendChild(cb);
}
}
// update the result textarea
function updateResult() {
var num = [ ];
for (var i = 1; i != gMax; i++) {
var cb = $('checkbox-' + i);
if (cb.checked) {
num.push(cb.getAttribute('value'));
}
}
$('result').innerHTML = num.join(", ");
}
</script>
</head>
<body onload='onload()'>
<form id="theForm"></form>
<input type="button" id="resultBtn" value="Result"
onclick="updateResult()" />
<br/>
<textarea id="result"></textarea>
</body>
</html>
Tested under Chrome 9.0.570.1 dev