Adding array of textbox using javascript into html - php

Is something wrong with my code?
<script>
function add(){
/* Get your form */
form = document.getElementById("test");
/* Create your input element */
input = document.createElement("input");
input.type="text";
input.name="array['artists']";
/* Append to form */
form.appendChild(input);
alert("done");
}
</script>
<table>
<tr>
<td align="right">Artist/s:</td>
<td><form id="test" enctype="multipart/data-form" method="post">
<input type="text" name="artists"/>
<input type="button" onclick='javascript: add()'/></form></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"></td>
</tr>
</table>
Im trying to add another textbox below another but nothing happened. What should i do?

Seems to be working for me too.
When I first put it into an html file, Internet Explorer wouldn't let me run the javascript because the html file was local to my computer. Try another browser if that's what you're using. Or just click yest to allow it in IE if that's the case.

Seems to be working - fiddle
I just put a call to add() inside a setTimeout so it would execute a second after the page loads.
Are you just missing the call to add()?
edit: I didnt originally see the onclick bound. new working fiddle2

Works for me as well. Try testing in another browser..

Your HTML-formatting is not right. This is why the input-box (TextBox) is added after the 'add'-button and not underneath it as you would like.
You can try the following code:
var table = document.getElementById("tableAddRows");
var row = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
td2.appendChild(input);
row.appendChild(td1);
row.appendChild(td2);
table.appendChild(row);
Add an id to the table (in the sample "tableAddRows").
Also, I added the Submit-button in a different table, like so (there are neater solutions):
<table>
<tr>
<td colspan="2"><input type="submit" value="Submit"></td>
</tr>
</table>
Also place the form-element around both tables.
I would also suggest to use JSRender or jQuery Templates to achieve your purpose.
Here's the sample code, if your still trying to figure it out.

Related

Column 'post' cannot be null [duplicate]

So I have a bunch of paragraph elements which are dynamically populated from a db. I have made the elements contenteditable. I now want to submit edits back the the db via a standard form submission. Is there a way to post the contenteditable elements back?
You have to use javascript one way or the other, it won't work as a "standard" form element as it would with a textarea or the like. If you like, you could make a hidden textarea within your form, and in the form's onsubmit function copy the innerHTML of the contenteditable to the textarea's value. Alternatively you could use ajax/xmlHttpRqeuest to submit the stuff a bit more manually.
function copyContent () {
document.getElementById("hiddenTextarea").value =
document.getElementById("myContentEditable").innerHTML;
return true;
}
<form action='whatever' onsubmit='return copyContent()'>...
If anyone is interested I patched up a solution with VueJS for a similar problem. In my case I have:
<h2 #focusout="updateMainMessage" v-html="mainMessage" contenteditable="true"></h2>
<textarea class="d-none" name="gift[main_message]" :value="mainMessage"></textarea>
In "data" you can set a default value for mainMessage, and in methods I have:
methods: {
updateMainMessage: function(e) {
this.mainMessage = e.target.innerText;
}
}
"d-none" is a Boostrap 4 class for display none.
Simple as that, and then you can get the value of the contenteditable field inside "gift[main_message]" during a normal form submit for example, no AJAX required. I'm not interested in formatting, therefore "innerText" works better than "innerHTML" for me.
Does it NEED to be standard form submission? If you cannot or do not want use a form with inputs, you may try AJAX (XMLHttpRequest + FormData), through which you could perform asynchronous requests and control better how response shows up.
If you want it even simpler, try jQuery's $.ajax function (also $.get and $.post). It sends data using simple JS objects.
Made a fully working example based on Rob's idea:
After hitting submit, the (hidden) textarea is updated with the table-data, in JSON-format.
(return true to submit)
function copyContent() {
const table = [];
$("tr").each(function() {
const row = [];
$("th, td", this).each(function() {
row.push($(this).text());
});
table.push(row);
});
$("#rows").val(JSON.stringify(table));
// return true to submit
return false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit='return copyContent()'>
<textarea name="rows" id="rows" rows="4"></textarea>
<button type="submit">Submit</button>
</form>
<table class="table table-striped">
<thead>
<tr>
<th>Head 1</th>
<th>Head 2</th>
</tr>
</thead>
<tbody>
<tr>
<td contenteditable="true">edit </td>
<td contenteditable="true">me</td>
</tr>
<tr>
<td contenteditable="true">please</td>
<td contenteditable="true">😊</td>
</tr>
</tbody>
</table>

How can I add more textboxs to page with php?

So I have this snippet of code that i want to insert into my site.
<table border="1">
<col width="130">
<col width="80">
<tr>
<td align = "right">Steps:</td><td align="center">Add as many steps as you need</td>
</tr>
<tr>
<td align = "right">Step 1:</td> <td><textarea style="width: 300px" class="form-control" name="steps[]" rows="3"></textarea></td>
</tr>
<tr>
<td align = "right">Step 2:</td> <td><textarea style="width: 300px" class="form-control" name="steps[]" rows="3"></textarea></td>
</tr>
<!--<tr>
<td align = "right">Step 3:</td> <td><textarea style="width: 300px" class="form-control" name="steps[]" rows="3"></textarea></td>
</tr>
<tr>
<td align = "right">Step 4:</td> <td><textarea style="width: 300px" class="form-control" name="steps[]" rows="3"></textarea></td>
</tr>
-->
</table>
For the most part, I have some commented out since I am testing to make sure that my site can handle multiple text boxs but the problem that I have is how can I insert steps into my site using php? I have these all on .php files in case you are wondering but I would like to insert more boxes with a button that is just under the current boxes. Every time the user clicks it, it should insert another box underneath the current boxes and update the number accordingly. I just am not sure where to start and how to get them in. Any ideas?
You would create new elements in JS and jQuery using the following code:
HTML
<button id="addButton">Add me!</button>
JS
var stepCounter = 3; //Number of the first step to be added
$('#addButton').click(function () {
var tr = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var textarea = document.createElement("textarea");
$(textarea).attr("name", "steps[]");
$(td1).innerHTML("Step " + stepCounter);
stepCounter++;
$(tr).append(td1);
$(tr).append(td2);
$(td2).append(textarea);
$('#giveTheColAnId').append(tr);
});
Remember to include jQuery for this solution
Note that this code might not be perfect, but it should give you a very good start.
You can add these new Boxes with JavaScript/JQuery, if you dont want to reload the page after adding a new box. I would really recommend to have a look at this, instead of trying to do it with PH.
If you really want to do it just with php, you have to have a submit-button in a form
so add something like
<form method="post" action="?">
<input type="submit" name="submit" value="add row">
</form>
Now the PHP-part:
if(isset($_POST['submit'])) {
echo " [your usual tr-td-structure] ";
}
Keep in mind, that after reloading the page, a variable will lose its value.
So if you want to count up, you have to do it with javascript (or determine somehow which Step is the current and insert it in the echo). Of course set the last step in a hidden field inside the form (or append it as a get-param).
Can you use Jquery, Can't you do something like this ?
$(document).ready(function(){
$('#myButton').click(function(){
$(':input').append('<input type="textbox">');
});
});

While loop form to delete mysql_entry

I have this chunk of code, which is displayed on a user's journal page. They can add an entry and they have the option to delete an entry once it's on the page.
Ill show the code with some comments and then explain the problem.
// Figures out how many recent posts to display
$posts = $config_journalposts + 1;
if($noposts!=1) {
// Gets the data from the query
while(($row = mysql_fetch_array($journalquery)) && ($posts > 1)) {
// For each of the posts that were gathered, display the following:
echo '<table border="0" width="100%">
<tr>
<td colspan="2" style="vertical-align:bottom;">
// Display the title as a link to be used as a permalink
<p class="fontheader">'.$row['title'].'</p>
</td>
</tr>
<tr>
// Show the o-so-important content
<td width="100%" style="vertical-align:top;padding-left:10px;">
'.$row['content'].'
</td>
</tr>
<tr>
// Show the date
<td style="font-size:8pt;padding-top:10px;">'.$row['date_day'].'/'.$row['date_month'].'/'.$row['date_year'].'</td>';
// Checks if the current user is the owner of the journal or an admin
if($_SESSION['user']==$pageowner || $_SESSION['user_rank']=='Admin') {
echo '<td align="right">
// FOCUS POINT
<form method="POST" id="deljournal">
<input type=\'hidden\' name=\'delete_id\' value=\''.$row['id'].'\' />
// A delete button that executes a bit of Javascript
<button type="button" class="button" name="delete" value="Delete" onClick="delete_journal()" />Delete</button>
</form>
// END FOCUS POINT
</td>';
}
echo '</tr>
</table>
<hr>
';
$posts --;
}
Here is the Javascript that gets triggered on the button press
function delete_journal() {
var answer = confirm("Are you sure you want to delete this journal entry?")
if (answer){
// Submits the form
$("#deljournal").submit()
}
}
This javascript triggers the forum in the PHP code above which reloads the page and triggers this at the very top of the page, before the tag
if(($_POST['delete_id'])) {
// Gets the post ID from the hidden forum tag
$deleteid = addslashes(strip_tags($_POST['delete_id']));
// Deletes the row that has the ID of the hidden form
mysql_query("DELETE FROM `gamezoid_accounts`.`journal_$pageowner` WHERE `id`='$deleteid'");
}
Now, for the problem. In the while loop, this form gets repeated over and over. What happens is that upon pressing the delete button, it triggers the form that has the ID "deljournal". Since all of them have the ID "deljournal" it does the one at the top of the page. Trying to embed the post ID into the form ID breaks the code because the mysql_query doesn't know that the delete function has been triggered in the first place.
Any way around this?
Reason why I'm using Javascript as a trigger is for the confirmation popup in case anyone askes.
Anyways, thanks heaps for reading this far!
<input type=\'hidden\' name=\'delete_id[]\' value=\''.$row['id'].'\' />
then only u will get all the values as array when posted.
<input type=\'hidden\' name=\'delete_id[]\' value=\''.$row['id'].'\' />
then only u will get all the values as array when posted.
and on server side u should use
$delete_values= implode (',',$_POST['delete_id']);
Found a solution.
I have changed the form to be
<form method="POST" id="deljournal_'.$row['id'].'">
<input type=\'hidden\' name=\'delete_id\' value=\''.$row['id'].'\' />
</form>
<button type="button" class="button" name="delete" value="Delete" onClick="delete_journal_'.$row['id'].'()" />Delete</button>
by adding the journal entry ID into the ID of the form and the onClick function. The javascript is just below it outside the table cell and looks like:
<script type="text/javascript">
function delete_journal_'.$row['id'].'() {
var answer = confirm("Are you sure you want to delete this journal entry?")
if (answer){
$("#deljournal_'.$row['id'].'").submit()
}
}
</script>
where the entry ID has been added to the function name and form ID tag. By putting the Javascript into a while loop and not into an external file, it can be manipulated with the loop to have the same values.
It is a bit messy and will slightly increase load times + execution times but it was the quickest way that I could find.
Hope this helps anyone else who has been having a similar problem.

How to generate a json array from a table data inside a <td> tag

I am trying to get those data in the JSON format. Would you please help me to generate that? Please help I am not very familiar with jquery and php.
html code looks like this
<form>
<table>
<tr>
<td>//some code for other table elements</td><tr>
<tr>
<td>Critical Times (Coverage): </td>
<td rowspan="3" colspan="2">
<div>
<table width="100%" bgcolor="white" border="0px" name="criticalTime" id="criticalTime">
</table>
</div>
</td>
<td>
<input type="button" id="timeAdd" value="+"/><br>
<input type="button" id="timeRemove" value="-"/>
</td>
</tr>
<tr>
<td>//some code for other table elements</td>
</tr>
</table>
</form>
my .js file has the following to handle the addition of rows to the table when click the + button.
var rowCountr = 0;
var timeTable="<thead><tr bgcolor='E1ECFF'><th></th><th align='left'>Start Time</th><th align='left'>End Time</th></tr></thead>";
/* insert the html string*/
$("#criticalTime").html( timeTable );
/*Event for the +(Add) button in critical time table*/
var timeRwcntr=0;
timeRow="<tr><td><input type='checkbox' id='row'</td><td><input type='text' id='start' /></td><td><input type='text' id='end'/></td></tr>";
$('#timeAdd').click(function(){
$('#criticalTime').append(timeRow);
rowCountr++;
timeRwcntr++;
});
$('#timeRemove').click(function(){
$('#criticalTime tr:last-child').remove();
});
When I click the submit button from main form I need to get those values entered in the input fields and generate an JSON array to store those in database. Please help.
For this problem, I think that JSON may be overkill. You're just trying to send your table's input fields back to the server on a postback right? When you create your table rows, add a uniquely identifying number in the "name" attribute of your form controls <input name="'.$id.'_field" /> for example if you are rendering the table server-side; the code would be similar for javascript. Then, when you post back, you can loop through each row by counting and then access the POST variable you got back by referencing the name. Example:
for ($i = 0; $i < $rowcount; $i++) {
$field_value = $_POST[$i.'_field'];
...
}
JSON is great for more complex data sets, but in your case it sounds like you have structured two-dimensional rows and columns.

How to resolve strange conflict between form post and ajax post?

On the one page, I am trying to use ajax to edit existing values. I am doing this by using jQuery Inline Edit and posting away the new data, updating the record and returning with success.
This is working fine.
Next I have implemented the ability to add new records, to do this I have a form at the end of the table, which submits post data then redirects back to the original page.
Each of them work individually, but after I have used the form to add a new record, the inline editing stops to work. If I close the webpage and reopen it, it works fine again until I have used the form and it goes of the rails again.
I have tried a number of solutions, clearing session data, giving the form a separate name, redirecting to an alternative page (which does work, but is not ideal as I want the form to redirect back to the original location ).
Here is a sample of the view form data:
<?php foreach($week->incomes as $income):?>
<tr>
<td><?php echo $income->name;?></td>
<td width="70" style="text-align:right;" class="editableSingle income id<?php echo $income->id;?>">$<?php echo $income->cost;?></td>
</tr>
<?php endforeach;?>
<?php echo form_open('budget/add/'.$week->id.'/income/index', 'class="form-vertical" id="add_income"'); ?>
<tr>
<td>
<input type="text" name="name" class="input-small" placeholder="Name">
<input type="text" name="cost" class="input-small" placeholder="Cost">
</td>
<td>
<button type="submit" class="btn btn-small pull-right"><i class="icon-plus "></i></button>
</td>
</tr>
<?php echo form_close(); ?>
This is the javascript initialisation code:
$(function(){
$.inlineEdit({
income: 'budget/update_income/',
expense: 'budget/update_expense/'
},
{
animate: false,
filterElementValue: function($o){
if ($o.hasClass('income')) {
return $o.html().match(/\$(.+)/)[1];
}
else if ($o.hasClass('expense')) {
return $o.html().match(/\$(.+)/)[1];
}
else {
return $o.html();
}
},
afterSave: function(o){
if (o.type == 'income') {
$('.income.id' + o.id).prepend('$');
}
if (o.type == 'expense') {
$('.expense.id' + o.id).prepend('$');
}
},
colors: { error:'green' }
});
});
If I can provide any more information to clarify what I have attempted etc, let me know.
Temporary Fix
It seems I have come up with a work around, not ideal as I still am not sure what is causing the issue.
I have created a method called redirect.
public function redirect(){
redirect('');
}
am now calling that after the form submit which has temporarily allows my multiple post submits to work.
please try and see by replacing the jquery sign.
$ should be replaced by jQuery then it will create new instance to work fine
I heard somewhere that jquery wont work if you put the form inside the table tag.
It need to be outside the table as in:
<form>
<table>
...
</table>
</form>
jQuery does not bring the contents of a form element if inside a table element on an ajax load
After testing it, i've discover that it is partialy true, (aka un-reliable)... It's the reason why i stopped using tables.

Categories