I've got an HTML form that has some static fields and some fields that are dynamically added with javascript. It looks sort of like this
<html>
<script type="text/javascript">
window.onload = function()
{
var select = document.getElementById("select");
var texts = document.getElementById("texts");
select.onchange = function()
{
var val = select.options[select.selectedIndex].value;
texts.innerHTML = "";
for(i=0; i < val; i++)
{
//texts.innerHTML += '<div><input type="text" name="t_' + i + '" value="select_' + i + '" /></div>';
texts.innerHTML += i + '<div><input type="text" name="t_' + i + '" /></div>';
}
}
}
</script>
<body>
<form method="POST" action="connection.php">
Question:<br>
<textarea name="question" cols="35" rows="5"></textarea><br>
<select id="select" size="1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
<div id="texts"></div>
<input type="submit" name="Submit" value="Submit" >
</form>
</body>
</html>
when the user clicks it adds a text box field. How does the data stored into the database.Kindly suggest me an idea what are the resources used to do this .Thanks in advance
Good day Shashak
In order to submit the data of your form into the database, regardless of the javascript of the form the data should be passed using in your case the POST method to a script 'connection.php' in your case.
This script should contain a way to connect to your database followed by the logic that will validate your data and then at the end if the validation is successful a database query that will INSERT the data into your database.
Which is your level of understanding when it comes to PHP or any other server-side scripting language and databases? - I will be able to give you more information if I know what you know.
I think instead of giving the textbox the name format t_1 , t_2 you can give it as an array like below
<html>
<script type="text/javascript">
window.onload = function()
{
var select = document.getElementById("select");
var texts = document.getElementById("texts");
select.onchange = function()
{
var val = select.options[select.selectedIndex].value;
texts.innerHTML = "";
for(i=0; i < val; i++)
{
//texts.innerHTML += '<div><input type="text" name="t_' + i + '" value="select_' + i + '" /></div>';
texts.innerHTML += i + '<div><input type="text" name="txt_name[]" /></div>';
}
}
}
</script>
<body>
<form method="POST" action="connection.php">
Question:<br>
<textarea name="question" cols="35" rows="5"></textarea><br>
<select id="select" size="1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
<div id="texts"></div>
<input type="submit" name="Submit" value="Submit" >
</form>
</body>
</html>
PHP
It will post data like this:
Suppose you select option 2.
$inputs = $_REQUEST['t']; // change the name like this name[]
$textarea = $_REQUEST['textarea'];
$selectbox = $_REQUEST['select']; // you should define the name of the select box as i used 'select'
insert into mysql
$conn = mysql_connect('localhost', 'db user', 'db password');
mysql_select_db('database name');
for($i=0; i<count($inputs); $i++) {
$sql = "insert into <table name> (textarea, inputs) values ($inputs[$i], $textarea)";
mysql_query($sql);
}
it will store each row as per your selection of input text boxes.
Note: Modify the query as per your requirement.
Related
This code somehow stores only the value of last textbox. When we generate 3 textboxes, only the value of 3rd is stored in database instead of all. I want to store all the generated textbox values in the database
<?php if(isset($_POST['submit'])){
$num_cat = $_POST['num_cat'];
$text = $_POST['category'];
foreach ($text as $key) {
// echo $key."\n";
}
$insertquery = mysqli_query($con, "INSERT INTO accounts (accountusername, accountemail) VALUES('".$num_cat."', '".$key."')");
if(!$insertquery){
echo "Error".mysqli_error($con);
}
} ?>
<script type="text/javascript">
//when the webpage has loaded do this
$(document).ready(function() {
//if the value within the dropdown box has changed then run this code
$('#num_cat').change(function(){
//get the number of fields required from the dropdown box
var num = $('#num_cat').val();
var i = 0; //integer variable for 'for' loop
var textboxes = ''; //string variable for html code for fields
//loop through to add the number of fields specified
for (i=1;i<=num;i++) {
//concatinate number of fields to a variable
textboxes += 'Category'+i+': <input type="text" name="category[]' + i + '" placeholder = "category_' + i + '" /><br/>';
}
//insert this html code into the div with id catList
$('#catList').html(textboxes);
});
});
</script>
<form method="post" action="">
Number of fields required:
<select id="num_cat" name="num_cat">
<option value="0">- SELECT -</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<div id="catList"></div>
<input type="submit" name="submit" value="Submit"/>
</form>
If you update your javascript to write this (remove ' + i + ' from the name):
textboxes += 'Category'+i+': <input type="text" name="category[]" placeholder = "category_' + i + '" /><br/>';
then $_POST['category'] will be an array. It then depends how you want to store the values, but assuming you'll want three rows, you'll need to do this:
foreach ($_POST['category'] as $key) {
$insertquery = mysqli_query($con, "INSERT INTO accounts (accountusername, accountemail) VALUES('".$num_cat."', '".$key."')");
if(!$insertquery){
echo "Error".mysqli_error($con);
}
}
This is explained in the PHP manual.
Please have a look at how can I prevent SQL-injection in PHP? as well, because your current code is vulnerable to simple exploits.
I have been having problems returning results from my database using AJAX. I have tried to echo $diskspace and $price, both of which are returning undefined.
index.php
<form id="form" method="POST">
Diskspace:
<select id="Diskspace">
<option value="0 AND 1">$0 - 1GB</option>
<option value="1 AND 5">$1 - 5GB</option>
<option value="5 AND 10">$5 - 10GB</option>
</select></br></br>
Price:
<select id="Price">
<option value="0 AND 5">$0 - $5</option>
<option value="1 AND 5">$5 - $10</option>
<option value="10 AND 20">$10 - $20</option>
<option value="20 AND 40">$20 - $40</option>
<option value="40 and 500">>$40</option>
</select></br></br>
<input type="submit" id="submit" value="enter">
</form>
<div id="output"></div>
JS
$(document).ready(function(){
$("div#output").hide();
$("#submit").click(function(){
$.post('join.php', {
diskspace: $("#diskspace").val(),
price: $("#price").val()
},
function(data){
$("div#output").html(data);
$("div#output").show();
}
);
return false;
});
});
</script>
join.php
<?php
if (isset($_POST['diskspace'])){
mysql_connect("localhost","root","") or die('Could not connect');
mysql_select_db("webhost") or die ('Could not find DB');
$diskspace = $_POST['diskspace'];
$price =$_POST['price'];
$query = mysql_query("
SELECT * FROM data WHERE Diskspace BETWEEN $diskspace
AND Price BETWEEN $price
");
$count = mysql_num_rows($query);
if ($count == 0){
$output = "No such results, sorry.";
}else{
while($row = mysql_fetch_array($query)){
$diskspace = $row['Diskspace'];
$price = $row['Price'];
$host = $row['Provider'];
$output .= '<div>'.$host.' '.$diskspace.' '.$price.'</div>';
}
}
echo $output;
}
?>
Your HTML element has an id of Diskspace and you're looking for an element of diskspace.
Take the following for example:
<select id="Diskspace">
<option value="hello">hello</option>
</select>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
console.log( $('#diskspace').val() );
});
</script>
The result is undefined, and in new versions of jQuery, if the element cannot be found it will not pass the variable through ajax/post.
The same applies to your Price element.
Your select id is not same in your jquery. Change it like this:
<form id="form" method="POST">
Diskspace:
<select id="diskspace">
<option value="0 AND 1">$0 - 1GB</option>
<option value="1 AND 5">$1 - 5GB</option>
<option value="5 AND 10">$5 - 10GB</option>
</select></br></br>
Price:
<select id="price">
<option value="0 AND 5">$0 - $5</option>
<option value="1 AND 5">$5 - $10</option>
<option value="10 AND 20">$10 - $20</option>
<option value="20 AND 40">$20 - $40</option>
<option value="40 and 500">>$40</option>
</select></br></br>
<input type="submit" id="submit" value="enter">
</form>
<div id="output"></div>
replace:
diskspace: $("#diskspace").val(),
with
diskspace: $("#Diskspace").val(),
You didn't give your <select>s names:
<select id="Diskspace" name="Diskspace">
^^^^^^^^^^^^^^^^--- missing
No name, no form submission for that field. id does NOT count - it's used purely for DOM operations, and is not relevant for form submissions.
Beyond that, you're vulnerable to SQL injection attacks.
I have a form with 2 dropdowns, 'Type' and 'Level', eg
Type
-----
Hotel
Restaurant
Casino
Level
-----
1
2
3
And a submit button which shows the price based on whichever options are selected in the dropdown. The price is calculated by some basic maths on the fly.
How can I do this using jquery?
Is it using onchange() or something?
$("#button_id_here").val("$your_amount_here");
If you want it to update automatically, bind it to the change event in the select/dropdowns
$("#select_id_here").change(function(){
//"basic maths"
$("#button_id_here").val("$your_amount_here");
});
You want more help, we would need to see code.
HTML:
<form>
<fieldset>
<p>
<label for="selectType">Type:</label>
<select id="selectType" name="type">
<option value="Hotel" data-cost="40">Hotel</option>
<option value="Restaurant" data-cost="80">Restaurant</option>
<option value="Casino" data-cost="35">Casino</option>
</select>
</p>
<p>
<label for="selectLevel">Level:</label>
<select id="selectLevel" name="level">
<option value="1" data-cost="0">1</option>
<option value="2" data-cost="15">2</option>
<option value="3" data-cost="30">3</option>
</select>
</p>
<p>
Total Cost: $<span id="cost">0</span>
</p>
<p><input type="submit" value="Go!"></p>
</fieldset>
</form>
jQuery:
$(function() {
$("#selectType, #selectLevel").change(function() {
var type = $("#selectType"),
level = $("#selectLevel"),
cost = $("#cost"),
typeCost = type.find(":selected").data('cost'),
levelCost = level.find(":selected").data('cost'),
total = typeCost + levelCost;
cost.html(total);
}).change(); // invoke the .change() trigger
});
See it in action here
You might want to also set something like "data-multiplier" for the level... whereas level 2 may have a 1.5x multiplier, and level 3 may have a 2x multiplier. You'd have to adjust the jQuery accordingly as well (total = typeCost * levelCostMultiplier, for example).
You can check if a select list has changed via jQuery's change() function.
Here's a way to do it:
HTML:
Type
<select name="type" id="type">
<option value="hotel" selected>Hotel</option>
<option value="restaurant">Restaurant</option>
<option value="casino">Casino</option>
</select>Level
<select name="level" id="level">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="result"></div>
jQuery:
var result = 1;
$("#type").change(function () {
var val = $(this).val();
$("#result").html("Type is " + val + ", level is " + $("#level").val());
});
$("#level").change(function () {
var val = $(this).val();
// Some basic math
result = parseInt(val) * 5;
$("#result").html("Type is " + $("#type").val() + ", level is " + val + ", result: " + result);
});
And the relevant jsfiddle:
http://jsfiddle.net/y2s4v/1/
I want to display a number of textboxes in a form based on the selected option from a dropdown listbox.
For example, if user selects 1 then 1 textbox should be shown and if user selects 2 then 2 textboxes should be displayed. And I need to do it in PHP.
I found some answers using jQuery. Can we use jQuery inside PHP? If yes, then how?
Edit
#Edwin Alex
This is how my select option looks like.
<h2><u>DEPENDENT DETAILS</u></h2><br />
<table border="1" style="border-style:dotted" width="100%" id="dependenttable">
<tr><td>No of Dependent</td><td><select name="numDep" id="dropdown">
<option value="">Please Select</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option></select></td></tr>
<tr id="textboxDiv"></tr>
At the end of file inside <> these I have written your code.
You can use Jquery to get this. Try this,
HTML :
<tr><td>No of Dependent</td><td><select name="numDep" id="dropdown">
<option value="">Please Select</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option></select></td>
</tr>
<tr id="textboxDiv"></tr>
Jquery :
<script type="text/javascript">
$(document).ready(function() {
$("#dropdown").change(function() {
var selVal = $(this).val();
$("#textboxDiv").html('');
if(selVal > 0) {
for(var i = 1; i<= selVal; i++) {
$("#textboxDiv").append('<input type="text" name="textVal[]" value="" />');
}
}
});
});
</script>
Paste this code at the bottom of your page inside tag.
Your select box ID should be dropdown.
You need to have a div with an ID textboxDiv to place your generated textboxes.
I think you can do it easily with the help of JavaScript. Here is an example of it. Try it and modify it according to your requirement
<html>
<head>
<title>Select DIV to show</title>
<script type="text/javascript">
function show(obj) {
no = obj.options[obj.selectedIndex].value;
count = obj.options.length;
for(i=1;i<count;i++)
document.getElementById('myDiv'+i).style.display = 'none';
if(no>0)
document.getElementById('myDiv'+no).style.display = 'block';
}
</script>
</head>
<body>
<form name="myForm">
<select onChange="show(this)">
<option value="0">Select</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</form>
<div id="myDiv1" style="display:none"> <form>
<select>
<option value="0">Select</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</form></div>
<div id="myDiv2" style="display:none"><form><input type="text" ><br>
<input type="text"/><br>
<input type="submit"/></form></div>
<div id="myDiv3" style="display:none"><form><input type="text" ><br>
<input type="text"/><br>
<input type="submit"/></form></div>
</body>
</html>
In this example just change the code in "myDiv1", "myDiv2", "myDiv3". I think it will hep you.:)
What I want to do is to create a feature that creates fields based on what the user selects
For example;
<select name="ex">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
If the user selected 4, I want to be able to display 4 input fields
My question was, how would I construct a query that would do this?
I rattled my brain and all I could come up with was
if($ex='4') {
<input type="text" name="field4">
<input type="text" name="field4">
<input type="text" name="field4">
<input type="text" name="field4">
}
But there has to be an easier way of displaying them. Any ideas?
If would be easier if you use for loop , like as follows :
for($i=1;i<=$ex;$i++){
echo "<input type='text' name='field4[]'>";
}
I hope it helps.
You could even do it on the fly with javascript: http://jsfiddle.net/fudQF/
Javascript:
showFields(t) {
f = document.getElementById('fields');
while (f.childNodes.length >= 1)
f.removeChild(f.firstChild);
for(i = 0; i < t.value; i++) {
e = document.createElement('input');
e.setAttribute('type','text');
f.appendChild(e);
e = document.createElement('br');
f.appendChild(e);
}
}
HTML:
<select name="ex" onClick="showFields(this)">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<div id="fields">
</div>
for($i = 0; $ < 4; $i++)
{
echo "<input type=\"text\" name=\"field".($i + 1)."\">";
}
for ($i=1; $i<=$ex; $i++)
{
echo "<input type=\"text\" name=\"field".$i."\">";
}
It will give unique name to your fields
for($i=0;$i<$ex;$i++)
{echo '<input type="text" name="field'.$i.'">';}
Try this
You can do this using onchange function in javascript on select
function chang()
{
for(var i=1;i<document.getElementById("select_id").value;i++)
document.body.innerHTML+='<input type="text" name="field"'+i+'>';
}
That if statement seems to be PHP (dollar sign before the variable).. I guess you want to echo or save in a variable that output.
A way to to that would be to use a repetitive statement (for, while) to do that thing the number of times you need.
Another option that is based on the fact that you seem to use the exact same output would be to use the str_repeat() function.
That seems a bit strange.. maybe you want the name to be field4[] and not just field4
Suppose $ex=4
$ex=4;
for($C=1;$C<=$ex;$C++){ echo "<input type=\"text\" name=\"field".$C."\" />"; }
Building on an existing answer - jQuery could further bring down the amount of code needed -
HTML
<select name="ex" onClick="showFields(this)">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<div id="fields">
</div>
jQuery
$("select[name='ex']").on('change',function(){
var selectedVal = $(this).val();
$("#fields").html(''); // clear existing input fields (possibly from previous selection)
for (var i=1; i<=selectedVal; i++){
$("#fields").append('<input type="text" name="field'+i+'">');
}
});