PHP To Create Add Another Button - javascript

I am creating a php page for camp registration, very basic and I do not want to plaster the page with multiple Name label/textbox. What I was thinking was to by default have one textbox and one label, and possibly blue text that says add another (or even a button) that when pressed the page will keep the current data but add an additional label and textbox so that more info can be added in. This is how I am capturing the data for 1, could this easily be modified in order to achieve my above outcome?
<td><label for="lblName">Campers Name:</label></td>
<td class="style1"><input type="text" name="txtName"
maxlength="100" size="30"></td>
EDIT
The link ad does nothing when I click it, I am sure it is I am missing the obvious but here is full syntax, what should I alter to make it work?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script type="text/javascript">
$("#newCamper").on('click', function() {
$('#Campers').after(
'<div id="Campers">' +
'<td><label for="lblName">Campers Name: </label></td>' +
'<td class="style1"><input type="text" name="txtName" maxlength="100" size="30"></td>' +
' remove this' +
'</div>'
);
});
$(document).on('click', '#rmCamper', function() {
$(this).closest('#Campers').remove();
});
</script>
</head>
<body>
<div id="Campers">
<td><label for="lblName">Campers Name:</label></td>
<td class="style1"><input type="text" name="txtName" maxlength="100" size="30"></td>
Add another
</div>
</body>
</html>
EDIT #2
when I go to localhost on my machine and push the Add button it changes the URL to localhost# but no additional fields are added to the page?

i think you can use a little of jquery code to do this job ;) all you have to do is include https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js
in your page.
<div id="Campers">
<td><label for="lblName">Campers Name:</label></td>
<td class="style1"><input type="text" name="txtName" maxlength="100" size="30"></td>
Add another
</div>
// jquery code below:
$("#newCamper").on('click', function() {
$('#Campers').after(
'<div id="Campers">' +
'<td><label for="lblName">Campers Name: </label></td>' +
'<td class="style1"><input type="text" name="txtName" maxlength="100" size="30"></td>' +
' remove this' +
'</div>'
);
});
$(document).on('click', '#rmCamper', function() {
$(this).closest('#Campers').remove();
});
https://jsfiddle.net/yb88s47s/

In real life one would probably be best of using javascript for this indeed. It is perfectly possible with just php however. Have a look at the following example:
<?php
$names = isset($_GET['txt']) ? $_GET['txt'] : [];
$i = 0;
?>
<form method="get">
<?php foreach ($names as $name) : ?>
<label for="txt<?= $i ?>">member</label>
<input name="txt[]" id="xt<?= $i ?>" value="<?= $name ?>">
<br>
<?php $i++ ?>
<?php endforeach; ?>
<label for="txt<?= $i ?>">member</label>
<input name="txt[]" id="xt<?= $i ?>">
<button type='submit'>
add
</button>
</form>
This form will submit to itself. It starts by getting the array of names (note the [] on the txt[] field). It then iterates over them and displays each of them as an input. After the loop you just add 1 extra, empty field.
This is obviously a very basic example, you'll probably want some validation, and a name on that add button to be able to distinguish it from the actual final submit. It is just a proof of concept.
Have a look at the code in action here. Feel free to ask if anything is unclear.

I know that you're looking for an answer in PHP, but for what you need to do (DOM manipulation), you'd be better off using JavaScript. You can create another input field and increment a variable to append to the ID field of same. See this question. If you keep track of the total number of input fields that have been created in this fashion, you could iterate over those on form submission to capture all of the data.

Related

How to create auto calculate value from database and new value using javascript

i got problem here when i want to create auto calculate value of total for each row
example :
This is table data
id
Price
Quantity
Total
1
40
12
480
2
12
3
36
What i really want is create an update value form
<form action="" method="Post>
$que_= "SELECT * FROM data ;
$res_ = mysqli_query($db_conn_data,$que_);
while ($row_= mysqli_fetch_array($res_)){
<input type="text" name="price" id="price" class="form-line" style="width: 90px;" onchange="calculateAmount(this.value)" value="<? echo $row_["Price"]; ?>">
<input type="hidden" id="q" name="q" value="<? echo $row_["Quantity"]; ?>">
<input type="text" id="tot_amount" name="tot_amount" class="form-line" style="width: 90px;" value="<? echo $row_["Total"]; ?>" >
<script>
function calculateAmount(val) {
var price_ = val *document.getElementById("q").value;
/*display the result*/
var divobj = document.getElementById('tot_amount');
divobj.value = price_;}
</script>
}
</form>
So user will change the value in price input form and it will auto calculate the new Price * Quantity using javascript also replace the Total value in form
but what exactly happen right now when i change the price in the form it only calculate quantity for first row only and not by each row
#redstar-entertainment already gave a good answer using jQuery. Here is one using pure JavaScript.
Note that it is crucially important that you post your full and proper HTML if you want any JavaScript to operate on it properly. For instance, you say you have a form with rows, but I don't see any table or other block-level elements in your HTML for forming rows. Also, your method attribute is not closed which may cause errors, and you are using ID attributes that are not unique per row. You should make them unique or get rid of them, because you don't need them for the following.
Assuming you are using a table with TR elements, you can then use the following JavaScript. Note that you must also change onchange="calculateAmount(this.value)" to onchange="calculateAmount(this)" because the function needs a DOM element to know which row it is operating on.
function calculateAmount(e) {
var row = e.closest('tr')
tr.querySelector('[name=tot_amount]').value =
e.value * row.querySelector('[name=q]').value
}
jQuery alternative
$(".q").bind('keyup blur', function(){
var quantity = $(this).parent().find(".q").val();
var value = $(this).parent().find(".package").val();
var price = quantity*value;
$(this).parent().find(".tot_amount").html(price.toFixed(2));
});
In your HTML change ID to Class
<input type="text" name="price" class="price form-line" style="width: 90px;" onchange="calculateAmount(this.value)" value="<? echo $row_["Price"]; ?>">
<input type="hidden" class="q" name="q" value="<? echo $row_["Quantity"]; ?>">
<input type="text" name="tot_amount" class="tot_amount form-line" style="width: 90px;" value="<? echo $row_["Total"]; ?>" >
See if this works!

JavaScript only changes text of first iteration with thymeleaf

I hope you are all well.
I have a school assignment, and I want to dynamically be able to change the name of a 'project'. This assignment is about projects. The way I've done it right now works with the first 'project' from a list of 'projects' iterated through with thymeleaf. I'm aware that what I've done right now is absolutely bad code behavior, but we have had no teaching in JS yet. But I really wanted this feature.
I don't know how to make this work for each project preview, right now it works for the first preview, but for the rest it just erases the project name from database. (see picture)
<div class="projects" th:each="projectNames : ${listOfProjects}">
<form action="deleteProjectPost" method="post">
<input type="hidden" th:value="${projectNames.projectID}" name="deleteID">
<input type="image" src="delete.png" alt="Submit" align="right" class="deleteProject" onclick="return confirm('Are you sure that you want to delete this project?')">
</form>
<form action="/editProjName" method="post">
<input type="hidden" name="projectID" th:value="${projectNames.projectID}">
<input type="hidden" id="oldName" th:value="${projectNames.projectName}">
<input type="hidden" id="newName" name="projectName">
<input type="image" src="edit.png" alt="Submit" onclick="change_text()" align="right" class="editProject">
</form>
<form action="/projectPost" method="post">
<input class="projectInfo" name="projectID" type="text" th:value="'Project No.: ' + ${projectNames.projectID}" readonly="readonly">
<input class="projectInfo" type="text" th:value="'Project name: ' + ${projectNames.projectName}" readonly="readonly">
<input class="projectInfo" type="text" th:value="${projectNames.projectStartDate} + ' - ' + ${projectNames.projectEndDate}" readonly="readonly">
<input type="submit" value="OPEN" class="openProject">
</form>
</div>
<script>
function change_text() {
var changedText;
var projectName = prompt("Please enter name of project:");
var oldName = document.getElementById("oldName").value;
if (projectName === null || projectName === "") {
changedText = oldName;
} else {
changedText = projectName;
}
document.getElementById("newName").value = changedText;
}
</script>
First form in HTML is the red cross to delete an entire 'project'. Second form is what is intended to change the name displayed on the 'project preview', but only works on first preview and deletes project name from the rest. Last form is the actual preview. I couldn't find another way to have multiple forms and do different POSTS while working with Java Spring and Thymeleaf.
My wish is to make the change_text() function work for each 'project preview'
Best regards!
function change_text(imageInput) {
var changedText;
var projectName = prompt("Please enter name of project:");
var oldName = imageInput.parentNode.querySelector('.old-name').value;
if (projectName === null || projectName === "") {
changedText = oldName;
} else {
changedText = projectName;
}
imageInput.parentNode.querySelector('.new-name').value = changedText;
}
<form action="/editProjName" method="post">
<input type="hidden" name="projectID" th:value="${projectNames.projectID}">
<input type="hidden" class="old-name" id="oldName" th:value="${projectNames.projectName}">
<input type="hidden" class="new-name" id="newName" name="projectName">
<input type="image" src="edit.png" alt="Submit" onclick="change_text(this)" align="right" class="editProject">
</form>
Ok so I made a few changes. First, notice the inputs with oldName and newName now have classes on them. These can be repeated. If you are not using the ids for anything other than the script, you should remove them. Otherwise if you have styling rules for them you should consider changing those CSS rules to use the class instead so you can remove the invalid repeating ids.
Secondly, the onlick of the image now passes in this. What that does is it passes in the actual input that the user clicked, so you have some context into which form element the user is interacting with.
Then looking at the logic, the method now accepts in imageInput which is the this from the onclick.
Using imageInput.parentNode we go up the DOM Tree to the parent element of the input, which is the form in this case. We can then turn around and use querySelector to find the other element in the form we want to manipulate. And it will only find the element in our particular form because that is what we are selecting off of.

how to update a html-select without reload the page in php

I need to update one dropdwonlist without reload the page, I mean, I have a form where I add the elements that I need, then I have another form where I have the dropdownlist conected to my database but if I do not have the element I need to select, I have to add it from the other form, but the problem is that i need to reload the page in order to the dropdownlist show the new element then I loose the data I was typing.
I wish to know a way to update the dropdownlist without reload the page.
Im using php and mysqli my code is simple:
<form action="edit_col_exe.php" method="post">
<p><label>Add Element:</label>
<input autofocus type="text" name="elemnt" class="input" required />
</p>
<table>
<tr>
<td><input type="submit" name="Save" value="Save" /></td>
</tr>
</table>
</form>
Form2:
Select Element
query("select * from Elements order by Element asc") or die("fail");
echo "Select an option";
while($reg=$con ->fetch_assoc()){
echo "";
echo $reg['Element'];
}?>
I hope someone can help me!
regards!
Use Ajax (I prefer jQuery) and remove your form.
JS
function addElement(){
// get new name
var name = $("#newElementsName").val();
// create ajax call
$.ajax({
type: "POST",
url: "edit_col_exe.php", // URL to php script
data: { // post data for php script (I use the data from your form (including the typo))
elemnt: name,
save: 'Save'
},
success: function(data){
// this function will be called when php script run successful (HTTP-Status 2xx)
// Clear the input filed
$("#newElementsName").val('');
// Add new name to dropdown
$("#elements").append("<option>"+name+"</option>");
}
});
}
HTML
<div>
<p><label>Add Element:</label>
<input autofocus type="text" id="newElementsName" class="input" required />
</p>
<table>
<tr>
<td><button type="button" onclick="addElement()">Save</button></td>
</tr>
</table>
</div>
<div>
<select id="elements" size="1">
</select>
</div>
I solved my problem and I want to share with you my solution, its simple:
setInterval(function(){
$('#searchelement').load('addelements.php');
});
<p><label>Element</label>
<select id="searchelement" name="element" required />
</option>
</select></p>
So everytime I add an element at 'addelements.php', I can search the new element in the select list.

Access sibling variable of text-field

I have a simple form, just a single text field containing a email from a MySQL database. The user has 2 buttons one can completely update the email with what they replace it with or they can choose to return the email to a default state i.e. the original email. It all works OK if you have the 2 buttons immediately 'in-situ' with the relevant text-field. But if you put the 'reset' button in a separate table cell, the 'onlick' set-email-back-to-default function stops working, and I don't understand how to fix it.
It will work like this because the reset button is slap-bang next to the text field:
<input name="cc_email" type="text" value="<?php echo !empty($_SESSION["cc-email"]) ? $_SESSION["cc-email"] : $_SESSION['admin_username'];?>" />
<input id="reset-cc" name="add" type="button" value="Set to default" />
Here's the JavaScript:
$(document).ready(function() {
$('#reset-cc').click(function() {
$(this).siblings('input[name="cc_email"]').val('<?php echo $_SESSION['admin_username'] ?>');
$('#update_cc').submit();
return false;
});
But if I place the reset button in a separate table cell as follows the function ceases to work as if it can no longer access the text field:
<td>
<input name="cc_email" type="text" value="<?php echo !empty($_SESSION["cc-email"]) ? $_SESSION["cc-email"] : $_SESSION['admin_username'];?>" />
</td>
<td>
<input id="reset-cc" name="add" type="button" value="Set to default" />
</td>
I assume I need to modify the JavaScript so it can still access the text field even though it is now separated by a table-cell but I don't know how to do it.
Your problem lies here:
$(this).siblings('input[name="cc_email"]')
By moving the input button into a different TD it is no longer a sibling (as the other answers have indicated). You may want to just give the button an ID and reference it that way:
//this bit |
// v
<input id="cc_email" name="cc_email" type="text" value="<?php echo !empty($_SESSION["cc-email"]) ? $_SESSION["cc-email"] : $_SESSION['admin_username'];?>" />
//...
$("#cc_email")...
Which will be easier than making convoluted parent/find calls. This button is unique, is it not?
The .siblings() function searches in a collection of siblings within the same parent. If you put them into different parents then they are not siblings. Try replacing it with something like:
$(this).parent().prev().find('input[name="cc_email"]').val('<?php echo $_SESSION['admin_username'] ?>');
If the input will always be in the same tr as the button, search for the input field within the row:
$('#reset-cc').click(function() {
$(this).closest('tr').find('input[name="cc_email"]').val('original#example.com');
$('#update_cc').submit();
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input name="cc_email" type="text" value="loaded#example.com" />
</td>
<td>
<input id="reset-cc" name="add" type="button" value="Set to default" />
</td>
</tr>
</table>

jQuery - the function doesn't get an ID/class

This function doesn't get the ID or class (first line), so the code is applied to all the fieldsets. For me that's not a big problem, but I would like to focuse the code on two specific IDs to make the code more compatible for plugins.
$('#feedburner_widget').ready(function() {
$('input').focus(
function(){
$(this).closest('fieldset').addClass('fieldset change-fieldset');
});
$('input').blur(
function(){
$(this).closest('fieldset').removeClass('change-fieldset');
});
});
Basically, this code adds a class to a fieldset when the user clicks on the input field. The ID is on the first line, but the code applies the effect to all the fieldsets. And it works exactly in the same way if I change '#feedburner_widget' to document. What I'm doing wrong? Thanks.
Edit: And this is the HTML code:
<form id="feedburner_widget" action="http://feedburner.google.com/fb/a/mailverify" method="post" target="popupwindow" onsubmit="window.open('http://feedburner.google.com/fb/a/mailverify?uri=<?php echo esc_attr($user); ?>', 'popupwindow', 'scrollbars=yes,width=550,height=520');return true">
<fieldset >
<input type="text" class="field" name="email" placeholder="<?php echo esc_attr($text); ?>" />
<input type="hidden" value="<?php echo esc_attr($user); ?>" name="uri" />
<input type="hidden" name="loc" value="<?php bloginfo('language'); ?>"/>
<span>
<input type="submit" value="" />
</span>
</fieldset>
</form>
When you do $('input'), you are asking jQuery to do a global search in the whole document. It does not 'remember' that you have just fetched the #feedburner element.
To search for only the elements in the #feedburner element, you could use the find() function on the jQuery object, like this:
$(document).ready(function() {
var $inputs = $('#feedburner_widget').find('input');
$inputs.focus(function(){
$(this).closest('fieldset').addClass('fieldset change-fieldset');
});
$inputs.blur(function(){
$(this).closest('fieldset').removeClass('change-fieldset');
});
});
In this particular case, you could also just alter the CSS selector to search directly for inputs inside the #feedburner_widget like this: $('#feeburner_widget input') If that element was already in a variable in your code, however, you should use the find method.

Categories