I am trying to build a way for a user to be able to create an article, if they want, with a button they can add an input for a text, a file input etc.
I want to send this form with JavaScript vanilla (training)
so what I do in my js is that I loop into my different added input then I append them to formData
and send this formData to my controller to treat it and add it to my database.
Problem is that by iterating my input when I append my input into formData I have to add the index
so when I send it and print_r my post
I get like:
text01
text02
text03 etc.
it would be fine if it was only these input that I wanted to send but in my post I have other inputs which are sent the same way so I get like
title01
paragraphe01
title02
paragprahe02
the problem will be when I want to query to add the data to my database I would have to bind all of these to my query, but of course I can't make 50 lines of
bind('text01', $text01)
I don't think it would be a nice way to do it
so I am looking for a way to be able to query all of these data I thought of maybe a way getting only the paragraphs indexes and putting them in an array containing only paragraphs then forEach() everything.
another array for another input etc. but I can't find a way to do it, is it even possible
so here is my code
<?php
include '../flash/Flash.php';
$pageTitle = "création d'article";
$css = "create_article";
include './assets/include/_header.php';
?>
<body>
<?php
include '../view/assets/include/_nav.php';
flash('createB');
?>
<main>
<form action="../controller/Crud_controller.php" method="post" class="form_container" enctype="multipart/form-data">
<input type="hidden" name="type" value="createB" id="type">
<h3 id="status"></h3>
<h5>titre du post</h5>
<input type="text" name="title" id="title">
<h5>Paragraphe</h5>
<textarea name="paragraphe" id="product_desc" cols="30" rows="10"></textarea>
<input type="file" id="img_livre" name="name" accept="image/png, image/jpeg">
<h5>Note 1</h5>
<input type="text" name="note" id="note">
<button type="button" data-prototype="" class="btn btn_primary btn-js">Ajouter un paragraphe ou une image ?</button>
<button type="button" class="btn btn_primary btn-js-ajax">envoyer</button>
</form>
</main>
</body>
<script>
const btnSubmit = document.querySelector('.btn-js-ajax');
btnSubmit.addEventListener('click', uploadFiles);
function uploadFiles() {
let formData = new FormData();
let images = document.getElementsByName('name');
let type = document.getElementById('type').value;
let paragraphe = document.getElementsByName('paragraphe');
let note = document.getElementsByName('note');
let title = document.getElementById('title').value;
for(i = 0; i <= images.length; i++) {
let uFiles = images[i];
if (uFiles) {
formData.append("name" + i, uFiles.files[0]);
}
}
for(let i = 0; i < paragraphe.length; i++) {
let paragraphes = paragraphe[i].value;
if (paragraphes) {
formData.append("paragraphe"+i,paragraphes);
}
}
for(let i = 0; i < note.length; i++) {
let notes = note[i].value;
if (notes) {
formData.append("note" + i, notes);
}
}
formData.append('title', title);
formData.append('type',type );
const ajax = new XMLHttpRequest();
fetch("../controller/Crud_controller.php", {method: "POST", body: formData}).then(res => res.text()).then(data => {console.log(data);})
ajax.upload.addEventListener("load", completeHandler, false);
}
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
var result = Object.keys(obj).map((key) => [Number(key)]);
console.log(result);
const form = document.querySelector('.form_container');
const addBtn = document.querySelector('.btn-js');
function addInput() {
const paragraphe = document.createElement('textarea');
paragraphe.name = 'paragraphe';
paragraphe.style = "margin-top:100px";
paragraphe.cols = "30";
paragraphe.rows = "10";
const file = document.createElement('input');
file.type = 'file';
file.style = "border: none";
file.name = 'name';
file.accept = "image/png, image/jpeg";
const note = document.createElement('input');
note.type = 'text';
note.name = 'note';
const btnRemove = document.createElement('a');
btnRemove.className = 'btn_primary btn';
btnRemove.innerHTML = 'supprimer';
form.insertBefore(btnRemove, addBtn);
form.insertBefore(note, btnRemove);
form.insertBefore(file, note);
form.insertBefore(paragraphe, file);
}
addBtn.addEventListener('click', addInput);
</script>
</html>
here the controller getting the post ajax element
<?php
include '../model/CrudModel.php';
include '../model/Blog.php';
require_once '../flash/Flash.php';
class Products
{
private $crudModel;
private $crudBlog;
public function __construct()
{
$this->crudModel = new Product;
$this->crudBlog = new Blog;
}
public function blog()
{
$data = $_POST;
echo "<pre>";
print_r($data);
echo "</pre>";
print_r($_FILES);
if (empty($data['title']) || empty($data['paragraphe'])) {
flash('createB', 'remplir au moins le titre et le paragraphe et ajouter une image');
// header('Location: ../view/crud_blog.php');
} else {
forEach($data as $k => $v)
{if ($this->crudBlog->setBlogPost($data)) {
foreach ($_FILES as $file) {
if ($this->crudBlog->setBlogImages($file)) {
flash('createB', "c'est bon");
// header('Location: ../view/create_blog_page.php ');
}
}
}}
}
}
}
$init = new Products;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
switch ($_POST['type']) {
case 'crud':
$init->produit();
break;
case 'createB':
$init->blog();
break;
default:
echo "je peux pas";
break;
}
}
here is my Model where I have all my queries
<?php
require_once '../dbb/Database.php';
class Blog {
private $con;
private $table_name = "blog_post";
public function __construct()
{
$this->con = new Database;
}
public function setBlogPost($array) {
$query = "INSERT INTO " . $this->table_name . " SET title = :title , paragraphe=:p1 , note = :note1";
$this->con->prepare($query);
$this->con->bind('title' , $array['title']);
$this->con->bind('p1' , $array['paragrape']);
$this->con->bind('note1' , $array['note']);
if($this->con->execute()){
return true;
}return false;
}
public function setBlogImages($file){
$table_name = "blog_image";
$query = "INSERT INTO " . $table_name . " SET name = :img , id = LAST_INSERT_ID()";
$this->con->prepare($query);
$this->con->bind('img',$file['name']);
move_uploaded_file($file['tmp_name'], "../view/assets/uploads/".$file['name']);
if ($this->con->execute()){
return true;
}return false;
}
and this is the response I get in my console.log maybe it will be more clear
thank you
Little edit so i managed to make an array for each of my input
array paragraphe for paragraphes
note for notes etc...
i changed this
for(i = 0; i <= images.length; i++) {
let uFiles = images[i];
if (uFiles) {
formData.append("name" + i, uFiles.files[0]);
}
}
for(let i = 0; i < paragraphe.length; i++) {
let paragraphes = paragraphe[i].value;
if (paragraphes) {
formData.append("paragraphe"+i,paragraphes);
}
}
for(let i = 0; i < note.length; i++) {
let notes = note[i].value;
if (notes) {
formData.append("note" + i, notes);
}
}
by this
for(i = 0; i <= images.length; i++) {
let uFiles = images[i];
if (uFiles) {
formData.append("name[]" + i, uFiles.files[0]);
}
}
for(let i = 0; i < paragraphe.length; i++) {
let paragraphes = paragraphe[i].value;
if (paragraphes) {
formData.append("paragraphe[]"+i,paragraphes);
}
}
for(let i = 0; i < note.length; i++) {
let notes = note[i].value;
if (notes) {
formData.append("note[]" + i, notes);
}
}
but here's the problem
i can't find a way to foreach multiple array in php to add them to my database
this is the response result i get in my console now
reponse2
Related
I made a selectBox which had its range of values from a Google Sheet Column. I also want to take an Integer input value from the user and then write this value in a specific cell according to option taken from selectBox. The html link does not show the integer response box. Is it possible to do the above plan in a while loop? Would appreciate any ideas and correction of code
function doGet() {
var ap = SpreadsheetApp.openByUrl("Gsheet URL here");
var ui = SpreadsheetApp.getUi();
var user = ui.prompt("Put down a number");
var result = result.getSelectedButton();
var sheet = ap.getSheetByName("lv");
var values = sheet.getRange("A2:A10").getValues();
var options = values.map(function(row)
{
#To show show the selected option??
var item = options.getSelecteditem();
if (item === A3)
{
var cell = SpreadsheetApp.getActiveSheet().getActiveCell();
var a1 = cell.getA3Notation();
var val = cell.getValue();
SpreadsheetApp.getUi().alert("Ur value is "+a1+" value is "+val);
}
{
return '<option value="' + row[0] + '">' + row[0] + '</option>';
});
var html = '<form onSubmit="handleSubmit(this)"> Type of Cuisine' + options.join('') + '</select></form>';
return HtmlService.createHtmlOutput(html);
}
Using an Html Dialog to Control User Inputs
Not sure what you wanted so here's a complete example I whipped up for you.
Code.gs:
function processInput(obj) {
Logger.log(JSON.stringify(obj));
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet0');
const [min,max,locs] = sh.getRange('B1:B3').getValues().flat();
Logger.log('min: %s max: %s locs: %s',min,max,locs)
const lA = locs.split(',');
if(obj.int > max) {
obj.msg = "Too High Try Again";
return obj;
} else if (obj.int < min) {
obj.msg = "To Low Try Again";
return obj;
} else if (!~lA.indexOf(obj.loc)) {
obj.msg = "Invalid Location";
return obj;
} else {
sh.getRange(obj.loc).setValue(obj.int);
obj.msg = "Complete";
return obj;
}
}
Following function Launches the dialog:
function launchInputDialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah1'),"Enter Input");
}
html:
<!DOCTYPE html>
<html>
<head>
</head>
<style>input {margin: 2px 5px 2px 0;}</style>
<body>
<form>
<input type="text" id="in1" placeholder="Enter an integer" />
<br /><input type="text" id="in2" placeholder="Enter a location" />
<br /><input type="button" value="Process" onClick="processinput();" />
</form>
<div id="msg"></div>
<script>
function processinput() {
document.getElementById("msg").innerHTML = '';
let v1 = parseInt(document.getElementById('in1').value);
let v2 = document.getElementById('in2').value;
let obj = {int:v1,loc:v2,msg:''};
google.script.run
.withSuccessHandler(robj => {
console.log(JSON.stringify(robj))
if(robj.msg == "Complete") {
document.getElementById("msg").innerHTML = `Value: ${robj.int} Location: ${robj.loc} Try Again`;
document.getElementById("in1").value = '';
document.getElementById("in2").value = '';
} else {
document.getElementById("msg").innerHTML = robj.msg;
}
})
.processInput(obj);
}
</script>
</body>
</html>
Short Demo:
This version uses a <select> tag to allow the user to determine where the data will be loaded
GS:
function doPost(e) {
Logger.log(e.postData.contents);
Logger.log(e.postData.type);
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet1");
let data = JSON.parse(e.postData.contents);
sh.getRange(data.loc).setValue(data.id)
}
function sendData(obj) {
const url = ScriptApp.getService().getUrl();
const params = { "contentType": "application/json", "payload": JSON.stringify(obj), "muteHttpExceptions": true, "method": "post", "headers": { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } };
UrlFetchApp.fetch(url, params);
}
function displayError(msg) {
SpreadsheetApp.getUi().alert(msg);
}
function launchMyDialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah1'), 'My Dialog');
}
function getSelectOptions() {
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName('Options');
var rg = sh.getDataRange();
var vA = rg.getValues();
var options = [];
for (var i = 0; i < vA.length; i++) {
options.push(vA[i][0]);
}
return vA;
}
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form>
<input type="text" id="txt1" name="id" placeholder="Enter Numbers only"/>
<select id="sel1" name="loc"></select>
<input type="button" value="submit" onClick="processForm(this.parentNode);" />
</form>
<script>
function processForm(obj) {
console.log(obj.id.value);
if(obj.id.value.match(/[A-Za-z]/)) {
google.script.run.displayError("Invalid Characters Found in id field");
} else {
google.script.run.sendData(obj);
}
}
window.onload = function() {
google.script.run
.withSuccessHandler(updateSelect)
.getSelectOptions();
}
function updateSelect(vA) {
var select = document.getElementById("sel1");
select.options.length = 0;
for(var i=0;i<vA.length;i++) {
select.options[i] = new Option(vA[i],vA[i]);
}
}
</script>
</body>
</html>
Demo:
Good evening. I am new to JavaScript and I need help with my mini-project and I have only one issue here and it is in the this.Add = function ().
It works properly when I enter a duplicate value from my list therefore it displays an alert that no dupes are allowed. But... when I enter a unique value, it only adds up the last element present (Wash the dishes) from myTasks list. instead of the one I recently entered and the list goes on adding the same ones. Did I just misplace something?
This is my final activity yet and I want to finish it to move to the next function. Thank you in advance.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tasks CRUD</title>
<style>
#tasks{
display: none;
}
</style>
</head>
<body>
<center>
<form action="javascript:void(0);" method="POST" onsubmit="app.Add()">
<input type="text" id="add-task" placeholder="Add another card">
<input type="submit" value="Add">
</form>
<div id="tasks" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-task">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Name</th>
</tr>
<tbody id="myTasks">
</tbody>
</table>
</center>
<script>
var app = new function() {
this.el = document.getElementById('myTasks');
this.myTasks = ['Clean the bathroom', 'Wash the dishes'];
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'task';
if (data) {
if (data > 1) {
name = 'Things To DO';
}
el.innerHTML = data + ' ' + name ;
} else {
el.innerHTML = 'No ' + name;
}
};
this.FetchAll = function() {
var data = '';
if (this.myTasks.length > 0) {
for (i = 0; i < this.myTasks.length; i++) {
data += '<tr>';
data += '<td>' + this.myTasks[i] + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(this.myTasks.length);
return this.el.innerHTML = data;
};
this.Add = function () {
el = document.getElementById('add-task');
// Get the value
var task = el.value;
if (task ) {
for(task of this.myTasks)
{
var ctr = 0;
if(document.getElementById("add-task").value == task){
ctr = 1;
break;
}
}
if(ctr == 1)
{
window.alert("Duplicates not allowed.");
}else{
// Add the new value
this.myTasks.push(task.trim());
// Reset input value
el.value = '';
// Dislay the new list
this.FetchAll();
}
}
};
this.Edit = function (item) {
var el = document.getElementById('edit-task');
// Display value in the field
el.value = this.myTasks[item];
// Display fields
document.getElementById('tasks').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
// Get value
var task = el.value;
if (task) {
// Edit value
self.myTasks.splice(item, 1, task.trim());
// Display the new list
self.FetchAll();
// Hide fields
CloseInput();
}
}
};
this.Delete = function (item) {
// Delete the current row
this.myTasks.splice(item, 1);
// Display the new list
this.FetchAll();
};
}
app.FetchAll();
function CloseInput() {
document.getElementById('tasks').style.display = 'none';
}
</script>
</body>
</html>
In your for loop:
for (task of this.myTask) {
}
You are not declaring a new task variable, but instead assigning to the outer task variable, hence the repeated addition of tasks already in your list.
You can declare a new variable in the for scope like so:
for (const task of this.myTask) {
}
Your HTML as it is.
And your Javascript goes like below. You have a bug while checking if the task already exists in the array. As you're comparing string value either use simple for loop with triple equals or do as i have attached below.
var app = new function() {
this.el = document.getElementById('myTasks');
this.myTasks = ['Clean the bathroom', 'Wash the dishes'];
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'task';
if (data) {
if (data > 1) {
name = 'Things To DO';
}
el.innerHTML = data + ' ' + name ;
} else {
el.innerHTML = 'No ' + name;
}
};
this.FetchAll = function() {
var data = '';
if (this.myTasks.length > 0) {
for (i = 0; i < this.myTasks.length; i++) {
data += '<tr>';
data += '<td>' + this.myTasks[i] + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(this.myTasks.length);
console.log(this.myTasks.length);
return this.el.innerHTML = data;
};
this.Add = function () {
el = document.getElementById('add-task');
// Get the value
var task = el.value;
console.log(task);
if (task ){
var arrayContainsTask = (this.myTasks.indexOf(task) > -1);
if(arrayContainsTask == true){
window.alert("Duplicates not allowed.");
}else{
// Add the new value
this.myTasks.push(task);
// Reset input value
el.value = '';
}
// Dislay the new list
this.FetchAll();
}
}
}
i create rand funtion for generating random value and concatenate with other value and show in the text field through ajax before insert this value. but here how can i check this random generating value is exists or not in database before inserting this value in database.if value is exists then again generate rand function value and again concatenate this and show the value in textbox. how can i do this? my code is below
index.php
<html>
<head>
<title>Untitled Document</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$( document ).ready(function() {});
function my_validate_func() {
var name = $('#name').val();
var year = $('#year').val();
var course = $('#course').val();
var branch_name = $('#branch_name').val();
if ($('#name').val() != "" && $('#year').val() != "" &&
$('#course').val() != "" && $('#branch_name').val() != "") {
$.ajax({
type: "POST",
url: 'roll.php',
data: { name: name, year: year, branch_name: branch_name, course: course },
success: function(response) {
$('#roll').val(response);
}
});
}
}
</script>
</head>
<body>
<form method="post" action="">
<input type="text" name="name" id="name" onChange="my_validate_func()">
<input type="text" name="phone" id="phone" onChange="my_validate_func()">
<input type="text" name="course" id="course" onChange="my_validate_func()">
<input type="text" name="center" id="center" onChange="my_validate_func()">
<input type="text" name="roll" id="roll" value="">
</form>
</body>
</html>
roll.php
<?php
function calculateRoll()
{
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = rand(100000,999999);
$roll =$branch_name.$name.$course.$year.$rand;
//return $roll;
echo $roll;
}
function isValidRoll($roll) {
mysql_connect("localhost","root","");
mysql_select_db("sigma");
$sql="SELECT count(*) as total FROM student WHERE roll = '$roll'";
$result = mysql_query($sql);
$data = mysql_fetch_assoc($result);
return $data['total'] == 0;
}
$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
if (isValidRoll($roll)) {
$validRoll = true;
} else {
$roll = calculateRoll();
}
}
?>
I suggest to use md5 function and/or time() function such as:
$rand = md5(time() + rand(100000,999999));
Your updated code should be:
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = md5(time() + rand(100000,999999));
$roll = $branch_name.$name.$course.$year.$rand;
echo $roll;
This solution provide unique value. You can use also uniqid() function. Also remember to set as unique the database field.
Another solution is to keep roll creation login in a function and create another function to check if the roll exists or not. Your responsibility to check if other rolls are store in the db or in a text file, ...
function calculateRoll()
{
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = rand(100000,999999);
return $branch_name.$name.$course.$year.$rand;
}
function isValidRoll($roll) {
$result = mysql_query("SELECT count(*) as total FROM student WHERE roll = '$roll'")
or die("Query not valid: " . mysql_error());
$data = mysql_fetch_assoc($result);
return $data['total'] == 0;
}
$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
if (isValidRoll($roll)) {
$validRoll = true;
} else {
$roll = calculateRoll();
}
}
when ever you save the data of the form store rand function value too means in second time you can retrieve the rand function value and compare with current rand function generating value.
The label that is beings created holds a guid that I need later. I need to grab that information after the list of labels are created. Here's my code:
<button onclick="getAllListings()">Get All Listings Information</button>
<br />
<div id="divDataInsert" name="divDataInsert">
#foreach (MVCTest1.Models.Listing foundListings in Model._listings)
{
string pk_listing_id = "listingsid_" + foundListings.PK_Listings_ID;
string addressPK = "address_" + foundListings.PK_Listings_ID;
string address = foundListings.Address.ToString();
string cityPK = "city_" + foundListings.PK_Listings_ID;
string city = foundListings.City.ToString();
string statePK = "state_" + foundListings.PK_Listings_ID;
string state = foundListings.State.ToString();
string zipcodePK = "zipcode_" + foundListings.PK_Listings_ID;
string zipcode = foundListings.ZipCode.ToString();
string fullAddress = address + ", " + city + " " + state;
if (foundListings.PK_Listings_ID != null)
{
<input type="text" id="lblListing_#pk_listing_id" value="#pk_listing_id" />
}
}
</div>
function getAllListings(){
//var listingArray = [document.getElementById("lblListing_")];
for (var i = 0; i < [document.getElementById("lblListing_")].length; i++) {
var listingString = document.getElementById("lblListing_").value;
var guid = listingString.split("_");
alert(guid[1]);
i++;
}
}
My code behind
public ActionResult Index()
{
string sql = "SELECT TOP 10 [PK_Listings_ID], [Address], [City], [State], [ZipCode] FROM dbo.Listings";
ListingCollection ListOfListings = new ListingCollection();
ListOfListings._listings = new List<Listing>();
using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["MVCInsertData"].ToString()))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = sql;
using(SqlDataReader reader = cmd.ExecuteReader())
{
if (reader != null)
{
while (reader.Read())
{
Listing listing = new Listing();
listing.PK_Listings_ID = Convert.ToInt32(reader["PK_Listings_ID"]);
listing.Address = reader["Address"].ToString();
listing.City = reader["City"].ToString();
listing.State = reader["State"].ToString();
listing.ZipCode = reader["ZipCode"].ToString();
ListOfListings._listings.Add(listing);
}
}
}
}
conn.Close();
}
return View(ListOfListings);
}
one of the answers involved adding a JS array in the code behind. How do you do that?
*****Update*****
I have changed my input to this:
<input type="text" class="lblListing_" value="#pk_listing_id" />
And I have adjusted my JS to this:
function getAllListings(){
var listingsArray = document.getElementsByClassName("lblListing_");
for (var i = 0; i < listingsArray.length; i++) {
var listingString = listingsArray.value;
var guid = listingString.split("_");
alert(guid[1]);
}
}
Keep in mind, my JS is NOT inside a document.ready(). Should it be?
One way would be to have your code behind emit a JavaScript array of all labels. A different--and this is the approach I would take--would be to use a class name as a "tag". Emit:
<input type="text" class="lblListing_" ...>
Then in your fixed (not dynamic) JavaScript, you can do:
function getAllListings(){
var listings = document.getElementsByClassName("lblListing_");
for (var i = 0; i < listings.length; i++) {
var listingString = listings[i].value;
var guid = listingString.split("_");
alert(guid[1]);
}
}
Update for the follow-on question:
The JavaScript can be placed anywhere but will not run on load. When and how to run the function depends on what you need it to do. (I assume the alert is just to test the logic.)
You can easily achieve that with jQuery
$('someSelector').each(function() {
// do something
});
$("input[id^='lblListing_']").each(function() {
console.log($(this).val().split("_")[1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="lblListing_g-u-i-d-1" value="value1_g-u-i-d-1" />
<input type="text" id="lblListing_g-u-i-d-2" value="value2_g-u-i-d-2" />
I'm using the following function to move data between two select fields:
<script language="javascript">
function move(tbFrom, tbTo)
{
var arrFrom = new Array(); var arrTo = new Array();
var arrLU = new Array();
var i;
for (i = 0; i < tbTo.options.length; i++)
{
arrLU[tbTo.options[i].text] = tbTo.options[i].value;
arrTo[i] = tbTo.options[i].text;
}
var fLength = 0;
var tLength = arrTo.length;
for(i = 0; i < tbFrom.options.length; i++)
{
arrLU[tbFrom.options[i].text] = tbFrom.options[i].value;
if (tbFrom.options[i].selected && tbFrom.options[i].value != "")
{
arrTo[tLength] = tbFrom.options[i].text;
tLength++;
}
else
{
arrFrom[fLength] = tbFrom.options[i].text;
fLength++;
}
}
tbFrom.length = 0;
tbTo.length = 0;
var ii;
for(ii = 0; ii < arrFrom.length; ii++)
{
var no = new Option();
no.value = arrLU[arrFrom[ii]];
no.text = arrFrom[ii];
tbFrom[ii] = no;
}
for(ii = 0; ii < arrTo.length; ii++)
{
var no = new Option();
no.value = arrLU[arrTo[ii]];
no.text = arrTo[ii];
tbTo[ii] = no;
}
}
</script>
main php page
<?php
mysql_select_db($database_UARData, $UARData);
$query_DistributionGroups = "SELECT distgrp.distgrpnme FROM distgrp";
$DistributionGroups = mysql_query($query_DistributionGroups, $UARData) or die(mysql_error());
$row_DistributionGroups = mysql_fetch_assoc($DistributionGroups);
$totalRows_DistributionGroups = mysql_num_rows($DistributionGroups);
?>
<select name="newusrdgavail" size="10" id="newusrdgavail" style="width:300px">
<?php
do {
?>
<option value="<?php echo $row_DistributionGroups['distgrpnme']?>"><?php echo $row_DistributionGroups['distgrpnme']?></option>
<?php
} while ($row_DistributionGroups = mysql_fetch_assoc($DistributionGroups));
$rows = mysql_num_rows($DistributionGroups);
if($rows > 0) {
mysql_data_seek($DistributionGroups, 0);
$row_DistributionGroups = mysql_fetch_assoc($DistributionGroups);
}
?>
</select>
</label></td>
<td align="center" bgcolor="#CCCCCC"><p>
<input type="button" name="newusrdgadd" id="newusrdgadd" value="Add" onclick="move(newusrdgavail,newusrdgreq)"/>
</p>
<p>
<input type="button" name="newusrdgremove" id="newusrdgremove" value="Remove" onclick="move(newusrdgreq,newusrdgavail)"/>
</p></td>
<td bgcolor="#CCCCCC"><label>
<select name="newusrdgreq" size="10" multiple="multiple" id="newusrdgreq" style="width:300px">
</select>
</label></td>
The move function works well and the moved values show in the correct field on the form. The problem is when I go to php submit:
$newusrdgreq = $_POST['newusrdgreq'];
$email_message .= "Required Email Distribution Groups: ".$newusrdgreq."\n";
I get the Notice: Undefined Index. On this field only. Everything else submits just fine. I know I can use the isset function to avoid empty or null values. However I think the great issue is that the "newusrdgreq" field is not getting the added and removed values properly attached to the field, but I cannot see why. Any help would be appreciated.
problem here that SELECT has only one value, even if you set it multiple - user must select all values manually, so basically all you items in select box - are not sending back to server
to fix this you can have 2 options:
create hidden field were you will duplicate data from select box
before submit - select all values in SELECT