I would like to show the value from textbox that user type in after the user click on submit.
In the page, I add one button "ADD TEXTBOX" which make the user can add the textbox by themselves for the maximum 10 textboxes.
Here is my current code
$(document).ready(function() {
var counter = 2;
$("#addButton").click(function() {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #' + counter + ' : </label>' + '<input type="text" name="textbox' + counter + '" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function() {
if (counter == 2) {
alert("System required at least one.");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form action="<?php $_PHP_SELF ?>" method="post">
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 :</label>
<input type='textbox' id='textbox1' name="textbox1">
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<br/>
<input type="submit" name="submit" id="submit">
</form>
Now, I would like to show all the value from the textbox when the user click on the submit button by using php.
This for loop does not show anything after I clicked submit
<?php
if(isset($_POST['submit'])) {
for($i = 1; $i< 10; $i++)
{
if(isset($_POST['textbox'+$i]))
{
$obj = $_POST['textbox'+$i];
echo $obj;
}
}
}
?>
Is there a way to let php check whether the textbox exist or check how many textbox exist in the current form?
To check with php if textbox exists use :
if(isset($_POST['textboxn']))
{
}
You can also check every textbox in one loop
for($i = 0; i< 10; i++)
{
if(isset($_POST['textbox'+i]))
{
}
}
Replace this with following form tag
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
For iterating text boxes use for loop
if ($_SERVER["REQUEST_METHOD"] == "POST") {
for($i = 1; $i <= 10; $i++)
{
if(isset($_POST['textbox'+$i]))
{
}
}
}
Related
I am confused how to populate my dropdown that adds on button click with database values . I used jQuery to do the adding function of dropdown on button click. but it seems like i cant populate the options of the select tag inside my jQuery with database values. Please help me out...
This is my php page
<?php include("connect.php");
$smt = $conn->prepare('select CompanyName From Company');
$smt->execute();
$data = $smt->fetchAll();
?>
<div class="form-group" id='TextBoxesGroup'>
<label for="layer" class="col-sm-3 control-label">Layer</label>
<div id="TextBoxDiv1" class="col-sm-6">
<select class="form-control" id='textbox1' name="company" placeholder="Company" >
<?php foreach ($data as $row): ?>
<option><?=$row["CompanyName"]?></option>
<?php endforeach ?>
</select>
</div><hr/>
</div>
<div class="form-group" >
<div class="col-md-9 text-right">
<input type='button' class="btn btn-default" value='Add +' id='addButton'>
</div>
</div>
The jQuery code used to add dropdown on button click is:
EDIT:
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>5){
alert("Only 5 Layers allowed");
return false;
}
var companies = [<?php echo "'".join("','",$data)."'";?>];
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<div class="form-group" id="TextBoxesGroup"><label class="col-sm-3 control-label">Layer '+ counter + ' : </label>' +' <div id="TextBoxDiv1" class="col-sm-6"><select class="form-control" name="textbox' + counter + '" id="textbox' + counter + '" name="company" placeholder="Company">');
$.each(companies, function(key, value){
newTextBoxDiv.append('<option>'+value+'</option>');
});
newTextBoxDiv.append('</select> </div></div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
});
</script>
But the output shows like this:
Thanks
Well, you need to echo out the value of $row['companyName'] (the one inside your foreach loop)
Another implementation would be... say you have an array of values in your PHP.
$data = array("company A", "company B", "company C");
And the javascript...
<script>
var companies = [ <?php echo "'". join("','", $data) . "'";?> ];
//This generates : ['company A', 'company B', 'company c'];
function insertOptions()
{
$.each(companies, function(key, value){
$("#IDofSelectTag").append("<option>"+value+"</option>");
});
}
</script>
HTML :
<table>
<tr>
<td>
<input type="text" name="name[]" value=" echo $ail">
<label >Address</label>
<input type="text" name="countryname[]" id='countryname_1' />
<button type="button" class='btn btn-danger delete'>- Delete</button>
<button type="button" class='btn btn-success addmore'>+ Add More</button>
</td>
</tr>
</table>
Js :
<script>
$(".delete").on('click', function() {
$('.case:checkbox:checked').parents("tr").remove();
$('.check_all').prop("checked", false); check();
});
var i = $('table tr').length;
$(".addmore").on('click', function(){
count = $('table tr').length;
var data = "<tr><td><input type='checkbox' class='case'/></td><td><span id='snum" + i + "'>" + count + ".</span></td>"; data += "<td><input class='form-control' type='text' id='countryname_" + i + "' name='countryname[]' required/></td> </tr>"; $('table').append(data); row = i;
});
</script>
I am getting multiple values in <? echo $ail;?>.
How to give add more button in front of every $ail value to give a row of a input box?
Because I have multiple values of $ail when I click on one value of Add button I get incremented on every field of $ail.
you can use this example for your problem.
js code :
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
Html code:
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
The question isn't very clear but presumably <? echo $ail;?> is displaying the content of a PHP array but you want to loop through the array and achieve something similar the functionality presented in the image.
PHP code:
<?php
// $options starts life as an empty string
$options = "";
// $options becomes a list of options for a <select> control
// it is populated with the values from the $ail array
foreach ($ail as $value) {
$options = "<option value='".$value."'>".$value."</option>";
}
?>
HTML code:
<table>
<tr>
<td>
Ailment:
<select id="ail_select" name="ail_select">
<option value="">--- Select ---</option>
<?php echo $options; ?>
</select>
<button type="button" class='btn btn-success addmore'>Add More</button>
</td>
</tr>
</table>
JS code:
$(document).ready(function(){
$(".delete").on("click", function() {
$(".case:checkbox:checked").parents("tr").remove();
$(".check_all").prop("checked", false);
check();
});
var counter = $("table tr").length - 1;
$(".addmore").on("click", function(){
// get the selected ailment
var ail = $("#ail_select").val();
// ail must have a value
if (ail.length > 0) {
counter++;
var data = "<tr><td><input type='checkbox' class='case'/></td><td><span id='snum" + counter + "'>" + ail + ".</span></td>";
data += "<td><input class='form-control' type='text' id='countryname_" + counter + "' name='countryname[]' required/></td>";
data += "</tr>";
$("table").append(data);
}
});
});
See JSFiddle for example in action.
I have made this JS script which creates forms properly.
<script>
var proizvodac = ["Acer", "Apple", "Asus", "Dell", "HP", "Lenovo", "Toshiba"]
document.write('<form method="post" action="proizvodi.php">')
document.write('<input hidden="hidden" type="text" name="sqca" value="Laptop" />')
document.write('<button class="button" type="submit" name="submit">Laptop</button>')
document.write('</form>')
for (i = 0; i < proizvodac.length; i++){
document.write('<div class="nav-bot">')
document.write('<form method="post" action="proizvodi.php">')
document.write('<input hidden="hidden" type="text" name="sqcp" value="Laptop" />')
document.write('<input hidden="hidden" type="text" name="sqp" value="' + proizvodac[i] + '" />')
document.write('<button type="submit" name="submit">' + proizvodac[i] + '</button>')
document.write('</div>')
}
</script>
And here I have PHP code that work with those forms:
elseif(!empty($_POST['sqcp']) && !empty($_POST['sqp'])){
$sqcp = mysqli_real_escape_string($conn, $_POST['sqcp']);
$sqp = mysqli_real_escape_string($conn, $_POST['sqp']);
$result = mysqli_query($conn, "SELECT Slika, Naziv, Opis, Cijena FROM Proizvodi WHERE Kategorija='$sqcp' AND Proizvodac='$sqp' ORDER BY Proizvodac");
}
Now my problem is that these two variables $sqcp and $sqp always return an empty string, even tho it should not.
Can someone tell me why?
Here's a debug part:
if (!empty($sqcp) && !empty($sqp)) echo $sqcp . ", " . $sqp;
else echo "Empty Variables";
}
The form tags are malformed. Remove this second <form> tag in the for:
document.write('<form method="post" action="proizvodi.php">')
Then move this line:
document.write('</form>')
to be after the for, outside of it.
I am working on a very simple php page. The user picks how many numbers they would like to be added up, then enters the numbers on the new page, clicks a button, and then the sum is displayed.
I cannot figure out how to add up the numbers though since I can't just assign variables to each number because of the loop. I've tried this not using loops, assigning variables to each one, and simply making the button add those variables, but that required making the code for the inputs many many times, and I want this to work with a loop in case I wanted to integrate the choice to pick hundreds of numbers or something. If php isn't the best thing for this, please let me know what would be better, but anyways... how do I add up the numbers that the user inputs?
Index page:
<p>How many number would you like to add?</p>
2<br>
3<br>
4<br>
5<br>
Calculator page:
<?php
$inputs = $_GET['inputs'];
?>
<div>Enter the numbers<br>
<?php
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number"><br>';
}
?>
</div>
<form action='' method='post'><input type='submit' value='Find value' name='findvalue'></form>
<?php
if (isset($_POST['findvalue'])) {
}
?>
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number"><br>';
}
You cant use input without any name. You can use dynamic name, for example:
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number" name="number_'.$x.'"><br>';
}
Or better way to use array names:
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number" name="number[]"><br>';
}
After that, var_dump your $_POST variable.
But, best way to create dynamic fields is creating one and clone it with javascript, when user want to add next value. Example with jQuery:
<div class="myInputs"><input type="number" name="numbers[]"></div>
Add input
<script>
$('#Add').click(function(){
$('.myInputs input:first').clone().appendTo(".myInputs");
return false;
});
Try this:
<?php
$inputs = $_GET['inputs'];
?>
<form action='' method='post'>
<div>Enter the numbers<br>
<?php
for ($x=0; $x < $inputs; $x++) {
echo '<input name="numbers[]" type="number"><br>';
}
?>
</div>
<input type='submit' value='Find value' name='findvalue'>
</form>
<?php
if (isset($_POST['findvalue'])) {
print_r($_POST["numbers"]);
}
?>
There is currently no JavaScript on your page. To interact with the client, JavaScript would be the best choice since there is no need to go to the backend to create input fields unless you need to save the number before interacting with the user
window.onload = function() {
document.getElementById("nums").onchange = function() {
var fields = document.getElementById("fields"),
numberOfField = parseInt(this.value, 10),
inputs = [];
for (var i = 0; i < numberOfField; i++) {
inputs.push('<input type="text" class="calcField" name="number' + i + '" />');
}
fields.innerHTML = inputs.length > 0 ? inputs.join("<br/>") : "";
}
document.getElementById("calc").onsubmit = function() {
var total = 0,
fields = document.querySelectorAll(".calcField");
for (var i = 0; i < fields.length; i++) {
var val = parseInt(fields[i].value, 10);
total += isNaN(val) ? 0 : val;
}
document.getElementById("total").value=total;
return false; // stop submission - remove to submit the form
}
}
<p>How many numbers would you like to add?</p>
<form id="calc">
<select id="nums">
<option value="0">Please select</option>
<option value="2">Two numbers</option>
<option value="3">Three numbers</option>
<option value="4">Four numbers</option>
</select>
<div id="fields"></div><hr/>
<input type="submit" value="Find value" /> <input type="text" id="total" />
</form>
try adding a hidden field for the number of inputs then use it to loop
<?php
$inputs = $_GET['inputs'];
?>
<form action='' method='post'><input type='submit' value='Find value' name='findvalue'>
<div>Enter the numbers<br>
<input type="hidden" name="numberofinputs" value="<?php echo $inputs;?>"/>
<?php
for ($x=0; $x < $inputs; $x++) {
//Please note the $x
echo '<input type="number'.$x.'"><br>';
}
?>
</div>
</form>
<?php
if (isset($_POST['findvalue'])) {
$numberOfinputs = $_POST['numberofinputs'];
for($i=0; $i<numberOfinputs; $i++){
//You can access it here
echo $_POST['number'.$i];
}
}
?>
i am creating a dynamic dropdowns based on a scenario i need to. i am wondering how it possible to keep the states of those added drop downs dynamically when a page is loading after submit button is clicked.
i am able to stote a variable in jquery and check whether form is submitted or not and if submitted to load back the previously dynamically added dropdowns (html select box) but even though i load them back still i have a problem of getting the previously selected values of those dynamic dropdowns.
I have created a fiddler. http://jsfiddle.net/jBJSw/8/
My form
<form>
<div id="TextBoxesGroup">
<div id="TextBoxDiv1">
<label>Textbox #1 :</label>
<input type="text" id="textbox1">
</div>
</div>
<input type="button" value="Add Button" id="addButton">
<input type="submit" value="submit Button" id="subButton">
</form>
Script
$(document).ready(function () {
var counter = 2;
$("#addButton").click(function () {
if (counter > 10) {
alert("Only 10 allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Select #' + counter + ' : </label>' +
'<select id="select' + counter + '" ><option value="' + "val" + ' ">"' + "desc2" + '"</option><option value="' + "val2" + ' ">"' + "desc" + '"</option><option value="' + "val3" + ' ">"' + "desc3" + '"</option>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
});
Appreciate if any help on finding a way to get the previously selected values after form submission. (this is needed because when a form is submitted with errors, these selected values should be same but now it refreshes and comes to default. also in a view scenario also this should be preloaded)
You will have to send back the selected value to the page from server side in the querystring or post header. then select the option accordingly in jquery on the base of the the value sent back.
Sorry for getting late have trouble in my work. Here's a possible solution for your problem.
DOM:
<form id="myform" method="post"> <!--adding id attribute-->
<div id="TextBoxesGroup">
<div id="TextBoxDiv1">
<label>Textbox #1 :</label>
<input type="text" id="textbox1">
</div>
<!--check if POST is established-->
<?php if($_POST): ?>
<?php if(count($_POST['mySelect']) < 0 ): ?>
<?php
//Recreate your select DOM
$arr = $_POST['mySelect'];
foreach($arr as $ind => $val){
echo '<select>';
echo '<option val="val" ' . ($val == "val" ? "selected" : "") . '>desc2</option>';
echo '<option val="val2" ' . ($val == "val2" ? "selected" : "") . '>desc</option>';
echo '<option val="val3" ' . ($val == "val3" ? "selected" : "") . '>desc3</option>';
echo '</select>';
}
?>
<?php endif; ?>
<?php endif; ?>
</div>
<input type="button" value="Add Button" id="addButton">
<input type="submit" value="submit Button" id="subButton">
</form>
SCRIPT:
$(document).ready(function () {
var counter = 2;
$("#addButton").click(function () {
if (counter > 10) {
alert("Only 10 allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Select #' + counter + ' : </label>' +
'<select id="select' + counter + '" ><option value="' + "val" + ' ">"' + "desc2" + '"</option><option value="' + "val2" + ' ">"' + "desc" + '"</option><option value="' + "val3" + ' ">"' + "desc3" + '"</option>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
//adding hidden inputs
$('#myFORM').on('submit', function(){
$('#myFORM select').each(function(){
slct = $('<input type="hidden" name="mySelect[]" value="' + $(this).val() +'">');
$('#myFORM').append(slct);
});
});
});