Set input field value in Javascript value store in PHP variable - javascript

I'm creating a dynamic text field for the answer of a question, which the user selects from the answer field display. When the user enters the answer and submits the form, the php code stores the user's answer in php variable named $ans1. When the form reloads after submitting, the answer doesn't show. I want to show that answer in the field note that I'm creating dynamically. The code is given below:
<?php
$ques1Err = $ans1Err = '' ;//variable to display error like field required
$ques1 = $ans1 = '' ;// variable to store value what user enter or select
$qans1 = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST['q1'])){
$ques1Err = 'Security Question Required' ;
}
else{
$ques1 = $_POST['q1'];
$qans1 = 1;
}
if(empty($_POST['ans1'])){
$ans1Err = 'Answer Required' ;
}
else{
$ans1 = check_input($_POST['ans1']);
if(!preg_match("/^[a-zA-Z ]*$/",$ans1)){
$ans1Err = "Only letters and white space allowed";
}
}
}
?>
<html>
<head>
<script>
// dynamically add input field for the user to enter the answer of question
function add_txt_field(){
var inpdiv = document.createElement("DIV");
inpdiv.setAttribute("class","input-txt");
var input = document.getElementById("ans1_txt-input");
input.appendChild(inpdiv);
var inp = document.createElement("INPUT");
inp.setAttribute("type","text");
inp.setAttribute("id","ans1");
inp.setAttribute("class","txt-box");
inp.setAttribute("name","ans1");
inp.setAttribute("value","");
inpdiv.appendChild(inp);
}
</script>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
Security Question<select class="txt-box" onchange="add_txt_field()" id="q1" name="q1">
<option value="<?php echo $ques1 ?>"><?php echo $ques1 ?></option>
<option value="What was your childhood nickname?">What was your childhood nickname?</option>
<option value="What is your grandmother's first name?">What is your grandmother's first name?</option>
<option value="What school did you attend for sixth grade?">What school did you attend for sixth grade?</option>
</select><span class="error"> <?php echo $ques1Err;?></span></div>
<div id="ans1_txt-input"></div>
<?php
if($qans1 == 1){
echo '<script type="text/javascript"> add_txt_field() </script>';
***// here's the problem***
echo '<script> oFormObject.elements["ans1"].value = "$ans1" </script>' ;
}
?>
<button id="create" name="create" type="submit">Create</button>
</form>
</body
</html>

You have a problem in your javascript:
echo '<script> oFormObject.elements["ans1"].value = "$ans1" </script>' ;
Change it to this
echo '<script> document.getElementById("ans1").value = "'.$ans1.'"; </script>' ;
But you can also do something from php inside the form like:
<?php
if (isset($ans1)) {
echo '<input type="text" name="ans1" id="ans1" value="'.$ans1.'"/>';
}
?>
Instead of using javascript

Related

Genereting 'n' html inputs based on database variable

My intention is to create a form in HTML where the user could register some quality features of a product. The number of features to be registered varies according to the model, this info is registered on a table in SQL.
So far I manage to generate the inputs, but it is very fast, the user cannot fill all the inputs.
## query to get the product information from database ##
$query_list = "SELECT * FROM data_products";
$result_list = mysqli_query($conn, $query_list);
## get the number of rows
$query_data_rows = mysqli_query($conn, $query_list);
$data_rows = mysqli_fetch_array($query_data_rows);
?>
## here is the first form, where the user selects the product model,
## therefore it should query the number of raws (n) registered on the table
<div class="container">
<form action="" method="post" onsubmit="getdata()">
<select name="select1">
<option value=" "> </option>
<?php
while ($row = mysqli_fetch_array($result_list)) {
echo "<option value='" . $row['customer_Id'] . "'>" . $row['customer_Id'] . "</option>";
}
?>
</select>
<input type="submit" name="submit" value="Go"/>
</form>
</div>
## here my intention is to return the (n) number of input fields
## it correctly displays the number of input fields, but it is very fast
## I am missing something here
<?php
if(isset($_POST['select1'])){ ?>
<form id="form" action="" method="post">
<input type="submit">
</form>
<?php
}
?>
## I am almost zero skilled on Javascript,
## but browsing on the world web wide and reading the documentation of the language
## I got the code below.
<script>
function getdata() {
var no = <?php echo $data_rows['number'] ;?>;
for(var i=0;i<no;i++) {
var textfield = document.createElement("input");
textfield.type = "text";
textfield.value = "";
textfield.name = i+1 + "a"
textfield.placeholder = i+1
document.getElementById('form').appendChild(textfield);
}
}
</script> ```
Here what actually happening is that when you are submitting the form getdata() function is called till the it get submitted, after submission is done the content called by function disappears, in order to avoid this use return false statement at the end of the function.
<div class="container">
<form action="" id="form_id" method="post" onsubmit="return getdata()">
<select name="select1">
<option value=" "> </option>
<?php
//accesing the database table
$query_list = "SELECT * FROM `data_products`";
$result = mysqli_query($conn, $query_list);
//to get rows
$data_rows = mysqli_num_rows($result);
echo $data_rows;
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['srno'] . "'>" . $row['srno'] . "</option>";
}
?>
</select>
<input type="submit" name="submit" value="go"/>
</form></div>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST' ){
echo '<form id="form" action="" method="post">
<input type="submit">
</form>';
}
?>
<script>
function getdata() {
var no = <?php echo $data_rows;?>;
for(var i=0;i<no;i++) {
var btn = document.createElement("INPUT");
btn.type = "text";
btn.value = "";
btn.name = i+1 + "a"
btn.placeholder = i+1
document.getElementById('form').appendChild(btn);
}
return false;
}
</script>
This is working. Here I have made some changes in your code like replacing 'textfield' with 'btn', 'customerid' with 'srno' (for easy understanding) and avoid using php again and again.

Option Menu with 2 Values

I have the following option menu in a form that will insert the fields into a table:
<option value="">select staff</option>
<?php
do {
?>
<option value="<?php echo $row_Staff['Staff_Name']."||".$row_Staff['Email']?>">
<?php echo $row_Staff['Staff_Name']?></option>
<?php
} while ($row_Staff = mysql_fetch_assoc($Staff));
$rows = mysql_num_rows($Staff);
if($rows > 0) {
mysql_data_seek($Categories, 0);
$row_Staff = mysql_fetch_assoc($Staff);
}
?>
</select>
I have 2 fields from source table in value of option from technique explained in How to post two values in an option field?: Staff_Name and Email.
I am trying to insert both fields from the form into a table using:
<input type="hidden" name="Staff_Name" class="form-control" id="Staff_Name" value=<?php
$staff =$_POST['Staff_Data'];
$staff_name = explode("||", $staff);
echo $staff_Name[0];
?> />
and
<input type="hidden" name="Email" class="form-control" id="Email" value=<?php
$staff =$_POST['Staff_Data'];
$email = explode("||", $staff);
echo $email[1];
?> />
Unfortunately, I can see the 2 fields separated by "||" in the table if I insert the option menu value but cannot seem to insert Staff_Name or Email into individual fields. On insert both fields are blank. Any help would be appreciated.
Instead of combine staffname and staffemail in the dropdown value. Please staffname in dropdown value and staffemail in the property of dropdown and onchange of the dropdown set those values in the hidden inputs so you will easily get those values on the form submission.
Please go through below code and let me know if you have any query.
//Dropdown
<select id="ddStaff">
<option value="">select staff</option>
<?php
do { ?>
<option value="<?php echo $row_Staff['Staff_Name']; ?>" staff-email = "<?php echo $row_Staff['Email'];?>">
<?php echo $row_Staff['Staff_Name']?>
</option> <?php
} while ($row_Staff = mysql_fetch_assoc($Staff));
$rows = mysql_num_rows($Staff);
if($rows > 0) {
mysql_data_seek($Categories, 0);
$row_Staff = mysql_fetch_assoc($Staff);
}
?>
</select>
//Input hidden fields to store staff name and staff email
<input type="hidden" id="txtStaffName" name="txtStaffName">
<input type="hidden" id="txtStaffEmail" name="txtStaffEmail">
//Jquery code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#ddStaff").on('change',function(){
var staffName = $(this).val();
var staffEmail = $('option:selected', this).attr('staff-email');
$("#txtStaffName").val(staffName);
$("#txtStaffEmail").val(staffEmail);
});
});
</script>
Please check it on https://jsfiddle.net/z4a0fywp/
For testing purpose I have not made the inputs hidden in the fiddle.

php - select option value not passed to post

Im pretty stuck at this code, I really can't see why it should not work, i don't know if some javascript code im running beforehand is interfering?
Only showing relevant part of the code
The first section with javascript updates page when selecting another dropdown, and is placed before the code that im struggling with:
`
<script type="text/JavaScript">
function changeDropDown(){
var elLocation = document.getElementById('form_location_id');
var location = elLocation.options[elLocation.selectedIndex].value;
document.getElementById("form1").action = "choose.php?id=" + location;
document.getElementById("form1").submit();
}
</script>
<form id="form1" name="form1" method="post">
<select size="1" name="form_location_id" id="form_location_id" onchange='changeDropDown(this);'>
<?php
if ($chosen_id == "1") { ?>
<option value = "1" selected><?php echo "dropdown text" ?></option>
<? } else { ?>
<option value = "1"><?php echo "dropdown text" ?></option>
<?php } ?>
</select>
</form>
<form method="post" action="update.php">
<select size="1" id="choice" name="value">
<?php
while($row = mysqli_fetch_array($query)) {
$id = $row['id'];
$number = $row['number'];
>?
<option value = "<?php echo ($id) ?>"><?php echo "ID=" . ($id) . " - #" . ($number) . ""?></option>
<?php
}
mysqli_close($db_conn);
?>
</select>
<input name="submit" type="submit" value="Submit">
</form>
update.php:
<?php
if (isset($_POST['submit'])) {
$chosen_id = $_POST['id'];
}
?>
`
I've only posted the code handling the select option and the post part...
Why is the $chosen_id variable always 0 ?
The while loop works, and fill's the variable, as this is tested with echo command inside the option line
Any help is much appreciated...
$_POST['id'] and <select size="1" id="choice" name="value">
Use $_POST['value']
You are trying to print the wrong key
if you trying to get the value of form_location_id
$chosen_id = $_POST['form_location_id'];
And if you trying to get the value of choice
$chosen_id = $_POST['value'];
This is why when you post a form to php it use html name attribute as key to assign the value to $_POST Array
I'd change Update.php to
<?php
if (isset($_POST['value'])) {
$chosen_id = $_POST['value'];
}
?>
You need to use the form_location_id to get the required value. You are using the wrong key to access the data. You need to use the name of the input. In this case, the input is the select and the name of that is form_location_id. So, you need to do this.
$value = $_POST['form_location_id'];
Try it out and do let me know if it worked out for you.
Thanks for everyone posting idea's - i've actually got it working, the code was actually working, only error was a misplaced tag, which was placed inside a tag, when placed outside this tag it works ;)

How to make HTML form fields automatically change when an option selected on a select field

Let's say I have a form like this in my CodeIgniter project.
<?php echo form_open(); ?>
<select>
<?php foreach($status_list as $status): ?>
<option value="<?php echo $status->id; ?>"><?php echo $status->name; ?></option>
<?php endforeach; ?>
</select>
<!-- Show this only if status type is, let's say "E" -->
<input type="text" name="E_happened">
<!-- Show this only if status type is, let's say "S" -->
<input type="text" name="S_happened">
<?php echo form_close(); ?>
What I want to do is if an user select one status, according to the it's type, show a text field to get an input.
I've made a way to get a type of the status like this: http://localhost/myapp/index.php/status/type/{status_id} where users can pass status ID and it will "echo" the type of the status.
I want to receive it back to the HTML page via a JavaScript method and show those text input fields. How do I do that?
Thank you. :)
As you have jQuery tag, so i suggest you this:
$('select').change(function(){
var inp = this.value.trim();
$(this).parent().find('input[type="text"][name^="'+inp+'"]').show().siblings(':text').hide();
});
I have posted the sample flow as per you want to do. hope this will helpful for you.
PHP:
<?php echo form_open(); ?>
<select>
<?php foreach($status_list as $status): ?>
<option value="<?php echo $status->id; ?>"><?php echo $status->name; ?></option>
<?php endforeach; ?>
</select>
<!-- Show this only if status type is, let's say "E" -->
<input type="text" id="E_happened" name="E_happened">
<!-- Show this only if status type is, let's say "S" -->
<input type="text" id="S_happened" name="S_happened">
<?php echo form_close(); ?>
JAVASCRIPT :
$('select').change(function(){
var statusId = $(this).val();
var statusType = $.get("http://localhost/myapp/index.php/status/type/"+statusId);
if(statusType == 'E')
{
$('#E_happened').value("what do you want here");
}
if(statusType == 'S')
{
$('#S_happened').value("what do you want here");
}
});

error inserting php to database using a jquery function option textarea [duplicate]

This question already has answers here:
Cannot insert data in the database using option(textarea)
(2 answers)
Closed 8 years ago.
Hi guys you have some idea about this codes, textarea submitted to database. because i have a connection.php but it is not inserting to database please help me using option textarea. Can you help me also for the phpmyadmin SQL what name, type, etc should i put, thanks
select.html
<html lang="en">
<title>NTF Catering Service</title>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<script src="js/js.1.js" type="text/javascript"></script>
</head>
<body>
<form action="submit.php" method="post">
<select multiple="multiple" name="food" class="options" id="textarea">
<option name="foodA"value="foodA">foodA</option>
<option name="foodB" value="foodB">foodB</option>
<option name="foodC" value="foodC">foodC</option>
<option name="foodD" value="foodD">foodD</option>
<option name="foodE" value="foodE">foodE</option>
</select>
<button type="button" id="copy" onclick="yourFunction()">Copy</button>
<button type="button" id="remove" onclick="yourFunction()">Remove</button>
<select id="textarea2" multiple class="remove" name="food">
<input type="submit" name="submit" />
</form>
</select>
</html>
connection.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$db = "copy";
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($db);
?>
submit.php
<?php
include 'connection.php';
$foodA = $_POST['foodA'];
$foodB = $_POST['foodB'];
$foodC = $_POST['foodC'];
$foodD = $_POST['foodD'];
$foodE = $_POST['foodE'];
if(!$_POST['submit']) {
echo "please fill out the form";
header('Location: select.html');
} else {
$sql = "INSERT INTO remove(food1, food2, food3, food4, food5) VALUES ('".$food1."', '".$food2."', '".$food3."','".$food4."','".$food5."');";
mysql_query($link, $sql);
echo "User has been added!";
header('Location: select.html');
}
?>
Your missing the
<form action="submit.php" method="POST">
From the start of the form.
Also to debug SQL issues more in depth, id put:
if (mysql_errno()) {
echo "MySQL error ".mysql_errno().": ".mysql_error()."\n<br>When executing:<br>\n$query\n<br>";
exit;
}
right before the header() function after mysql_query(). Post the error if it occurs and we should be easily be able to debug what is wrong.
You're trying to use two selects, to send items from first to second, so the second will be posted to script.php, so first of all you need to name only the second selectas food[] since it's a multiple select, also the copy function must be changed to make sure goes through post correctly, close the select #textarea2 before form is closed for no side effects, form code will be changed to:
select.html
<form action="submit.php" method="post">
<select multiple="multiple" class="options" id="textarea">
<option value="foodA">foodA</option>
<option value="foodB">foodB</option>
<option value="foodC">foodC</option>
<option value="foodD">foodD</option>
<option value="foodE">foodE</option>
</select>
<button type="button" id="copy">Copy</button>
<button type="button" id="remove">Remove</button>
<!-- note how multiple select name must be set -->
<select id="textarea2" multiple class="remove" name="food[]">
</select>
<input type="submit" name="submit" />
</form>
and the script part added selected so it will be processed:
<script>
$(function(){
$("#copy").on("click", function(){
$(".options option:selected").each(function({
$("#textarea2").append('<option selected>'+$(this).text()+'</option>');
$('option:selected', "#textarea").remove();
});
});
$("#remove").on("click", function(){
$(".remove option:selected").each(function(){
$("#textarea").append('<option>'+$(this).text()+'</option>');
$('option:selected', "#textarea2").remove();
});
});
});
</script>
that being changed, php will treat textarea2 as an array of options, one way to retrieve them could be:
submit.php
foreach ($_POST['food'] as $food){
$food == "foodA" ? $foodA = $food : $foodA = '';
$food == "foodB" ? $foodB = $food : $foodB = '';
$food == "foodC" ? $foodC = $food : $foodC = '';
$food == "foodD" ? $foodD = $food : $foodD = '';
$food == "foodE" ? $foodE = $food : $foodE = '';
}
Make sure the data sent is the one your database expects, any doubts use Rehan's debug suggestions.

Categories