I have a form with input field and this input contain a drop down menu read information from database.
If the user enters value and when he arrives to the drop menu he doesn't find what he wants he go to another page to add this info to the drop down menu and then go to the first page to continue enter the information.
How can I keep this information if he goes to another page to add info to drop menu and how can after adding the info to drop menu find this info without refresh and without submit.
This is the first page with the form
<form name='' method='post' action='<?php $_PHP_SELF ?>'>
<input name='txt_name' id='' type='text'>
This drop menu read from database
<select id="groups" name="txt_label" class="form-control">
';?>
<?php
$sql=mysqli_query($conn,"select DISTINCT db_label from tbl_label")or die(mysqli_error($conn));
echo'<option value="">-- Select --</option>';
while($row=mysqli_fetch_array($sql)){
$label=$row['db_label'];
echo "<option value='$label'>$label</option>";
}echo'</select>';?><?php echo'
</div>
</form>
Second form in another page
<form class="form-inline" role="form" name="form" method="post" action="';?><?php $_PHP_SELF ?><?php echo'">
<div class="form-group">
<label for="pwd">Label</label>
<input id="txt_label" name="txt_label" type="text" placeholder="Label" class="form-control input-md">
</div>
<div class="form-group">
<label for="pwd">Sub Label</label>
<input id="txt_sublabel" name="txt_sublabel" type="text" placeholder="SubLabel" class="form-control input-md">
</div>
<input type="submit" name="addlabel" value="Add" class="btn btn-default">';
EDIT: Keep value of more inputs
HTML:
<input type="text" id="txt_1" onkeyup='saveValue(this);'/>
<input type="text" id="txt_2" onkeyup='saveValue(this);'/>
Javascript:
<script type="text/javascript">
document.getElementById("txt_1").value = getSavedValue("txt_1"); // set the value to this input
document.getElementById("txt_2").value = getSavedValue("txt_2"); // set the value to this input
/* Here you can add more inputs to set value. if it's saved */
//Save the value function - save it to localStorage as (ID, VALUE)
function saveValue(e){
var id = e.id; // get the sender's id to save it .
var val = e.value; // get the value.
localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override .
}
//get the saved value function - return the value of "v" from localStorage.
function getSavedValue (v){
if (!localStorage.getItem(v)) {
return "";// You can change this to your defualt value.
}
return localStorage.getItem(v);
}
</script>
if the above code did not work try this:
<input type="text" id="txt_1" onchange='saveValue(this);'/>
<input type="text" id="txt_2" onchange='saveValue(this);'/>
You can also use useContext() from react context() if you're using hooks.
In MVC/Razor,
first you should add a variable in your model class for
the textBox like this:
namespace MVCStepByStep.Models
{
public class CustomerClass
{
public string CustomerName { get; set; }
}
}
Then in Views --> Index.cshtml file make sure the Textbox
is created like this:
#Html.TextBoxFor(m => m.CustomerName)
For a complete example, please check out this site:
How to update a C# MVC TextBox By Clicking a Button using JQuery – C# MVC Step By STep[^]
Related
I am writing a code for billing, here inside it rather to enter every entry by typing i wanted to do something like if record already exist then, enter one field other corresponding fields will automatically be filled with corresponding data. For eg: inside my form there is a section to display customer info and that is done by entering customer_id then a PHP file fetches name address phone number and other data corresponding to the entered customer_id and auto fill other customer fields of form.
HTML form
<form action="./manipulate/invoice.php" method="post" accept-charset="UTF-8">
<div style="width:15%;float:left">
Customer #
<br>
<input id="searchbox" style="width:98%;margin-left:1%;margin:right:1%" name="cust_id" type="text" placeholder="Customer ID">
</div>
<div class="w3-container">
<div style="width:100%;">
<h4>Contact Info About Customer</h4>
</div>
<div style="width:30%;float:left" >
<input id="cust_address" style="width:98%;margin-left:1%;margin:right:1%" type="text" placeholder="Customer_Address" >
</div>
<div style="width:15%;float:left">
<input style="width:98%;margin-left:1%;margin:right:1%" type="text" placeholder="City" id="cust_city">
</div>
<div style="width:15%;float:left">
<input style="width:98%;margin-left:1%;margin:right:1%" type="text" placeholder="State" id="cust_state">
</div>
<div style="width:15%;float:left">
<input style="width:98%;margin-left:1%;margin:right:1%" type="number" placeholder="Pincode" id="cust_pincode">
</div>
<div style="width:25%;float:left">
<input style="width:98%;margin-left:1%;margin:right:1%" type="number" placeholder="Phone Number" id="cust_phone">
</div>
</div>
</form>
Javascript function:
<script>
$(document).ready(function () {
function trial(s){
$('#searchbox').val(s);
$.ajax({
url:'./manipulate/get_addre.php',
type:'POST',
data:'cust_id='+s,
dataType:'json',
success:function(e){
//$('#cust_add').append(e['address']);
$('#cust_Address').val(e['address']);
$('#cust_city').val(e['city']);
$('#cust_state').val(e['state']);
$('#cust_pincode').val(e['pincode']);
$('#cust_phone').val(e['phone']);
$('#cust_Name').val(e['name']);
}
});
}
});
$('#searchbox').change(function() {
trail($(this).val());
});
</script>
get_addre.php is
<?php
$mysqli = new mysqli("localhost","root","","tssolutions");
if($mysqli->connect_errno){
echo "connection failed : $mysqli->connect_errno";
exit();
}
$cust_id = $_POST['cust_name'];
$query = "SELECT * FROM customer WHERE customerid = '".$cust_id."' ";
//echo 'hi';
if($result = $mysqli->query($query)){
/* fetch details*/
while($row = $result->fetch_assoc()){
$json = json_encode($row);
//return $json;
echo $json;
//echo "<b>Address : </b>".$row['address'].", ".$row['city'].", ".$row['state'].", ".$row['pincode'].", contact no. ".$row['phone'];
}
$result->free();
}
$mysqli->close();
?>
And in invoice.php these fields + some more fields are being inserted into another table in database.
The problem i am facing is whenever i enter into customer_id field in form rest all fields remains blank which were supposed to auto fill..
Anyone can correct it ? Thanks in advance.
The first thing i have to say is: Your code is vulnerable to SQL Injection. You should change this line:
$cust_id = $_POST['cust_name'];
to this line:
$cust_id = $mysqli->real_escape_string($_POST['cust_name']);
On the first glance i do not see any error, but oddly there is no event handler, that will acutally call your JavaScript trial function. It seems like you are missing this part of the code:
$('#searchbox').change(function() {
trial($(this).val());
});
Edit
After rebuilding your application i have found your error. You are sending data with the name 'cust_id' but you are requesting data with the name 'cust_name'. Once you change your names to the correct one, this will work.
You can use the web developer consoles (F12 in Chrome and Firefox) to have a look at the server response to your ajax calls in the newtwork tab.
I have an issue with the code below where the floating label stops working when executing the php script via function "loadStaff". The floating label works prior to the execution of the php script. My limited knowledge suggests that the issue is caused by the option select value not being passed on to the angular model which in turn did not trigger the floating label since the option select retains the selected value ($('select#account_list').val('<?php echo $_POST['account_list'];?>') as I can see it showing up. However, the floating label is not executing even though I see the selected value in the option select field. How do we pass the selected value to the angular model for it to trigger the floating label? I could be wrong with my reasoning.
<div ng-app="myApp">
<form id="orderformstaff" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
<div class="field" style="width: 100%">
<label class="show-hide" ng-show="account">Account</label>
<div class="input-group mb-4">
<span class="input-group-addon gi gi-user-key"></span>
<select id="account_list" class="form-control custom-select" name="account_list" ng-model="account" onchange="loadStaff()" autocomplete="on" required/>
<?php
$a_list = $DB_CON_A->query("SELECT `id`, `email` FROM `staffs` ORDER BY `id` ASC");
$data_row = '<option value="" disabled>Choose an account</option>';
if($a_list !== false) {
foreach($a_list as $row){
$data_row .= '<option value="'.$row['email'].'">'.$row['email'].'</option>'."\n";
}
}
unset($row);
echo $data_row;
?>
</select>
</div>
</div>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-animate.js"></script>
<script> var myApp = angular.module('myApp', ['ngAnimate']);</script>
<script>
function loadStaff() {
var form =
document.getElementById('orderformstaff');
form.submit();
};
</script>
<script type="text/javascript"> <!--allows option select to retain value after executing loadStaff-->
$(document).ready(function(){
$('select#account_list').val('<?php echo $_POST['account_list'];?>');
});
</script>
Actualy you don't need using AngularJS because did all jobs with PHP.
However if you want to fix current code
REMOVE
$('select#account_list').val('<?php echo $_POST['account_list'];?>');
THEN set attribute on select element
<select id="account_list" class="form-control custom-select" ng-init="account = <?php echo $_POST['account_list'];?>" name="account_list" ng-model="account" onchange="loadStaff()" autocomplete="on" required/>
EDIT
If you want to use AngularJS you should bind data with angularjs not with PHP.
If there is no JQuery you cannot use $(document).ready etc...
If you want to start learn AngularJS, you can start from here http://www.journaldev.com/7750/angularjs-simple-forms-tutorial
It use PHP on back-end.
I'm trying to take some js that pulls data from another web application and populates a form by clicking "Populate Contact Info" and then click a "Submit" button to push the fields to a new php that then processes them. So basically how do I pass populated form field to a second form on the same page that I can then submit? Or is there a better way?
<form action="#" name="data" id="data">
<input type='button' value='Populate Contact Info' onclick='popAllContactFields()' />
Contact Info:
First Name: <input type='text' readonly="readonly" id='cfname' name='cfname' />
Last Name:<input type='text' readonly="readonly" id='clname' name='clname' />
Email: <input type='text' readonly="readonly" id='cemail' name='cemail' />
</form>
<script type="text/javascript">
/* popAllContactFields()
Populates all the contact fields from the current contact.
*/
function popAllContactFields()
{
var c = window.external.Contact;
{
// populate the contact info fields
popContact();
}
}
/* popContact()
Populates the contact info fields from the current contact.
*/
function popContact()
{
var c = window.external.Contact;
// set the contact fields
data.cfname.value = c.FirstName;
data.clname.value = c.LastName;
data.cemail.value = c.EmailAddr;
}
</script>
<form action="ordertest.php" method="post">
<input name="cfname" id="cfname" type="hidden" >
<input name="clname" id="clname" type="hidden" >
<input name="cemail" id="cemail" type="hidden" >
<input type="submit" value="Submit">
</form>
If you can manage to receive the data with an AJAX call as a JSON then it's vary easy. With using jQuery ($) and Lodash (_ but you can try Underscore as well):
$.get('an-url-that-returns-the-json', function(parsedData) {
_.forEach(_.keys(parsedData), function(key) {
console.log('key:', key);
$('#'+key).val(parsedData[key]);
});
});
If it's tough at first sight read some about jQuery selectors, AJAX ($.get()) and $(...).val().
You can also make a list about the keys that you want to copy, e.g. var keysToCopy = ['cfname', 'clname', 'cemail'] and then _.forEach(keysToCopy, function(key) {...}), this gives you more control with the copied data.
If you cannot use AJAX but can control the output of the source PHP, then I'd rather create the data as a raw JS object. If you cannot control the generated stuff then you must use something like you wrote, that also can be helped by some jQuery based magic, e.g.
_.forEach(keysToCopy, function(key) {
var prop = $('#source-form #'+key).val();
$('#target-form #'+key).val(prop)
});
Based on these you can think how you can solve if the source and target IDs are not the same.
Hi I have a form that has a button used to prefill my form with data from my database. Using Json It works fine to populate text inputs but how do I get it to select a radio button based on the value returned from my database?
FORM
<form action="#">
<select id="dropdown-select" name="dropdown-select">
<option value="">-- Select One --</option>
</select>
<button id="submit-id">Prefill Form</button>
<input id="txt1" name="txt1" type="text">
<input id="txt2" name="txt2" type="text">
<input type="radio" id="q1" name="q1" value="4.99" />
<input type="radio" id="q1" name="q1" value="7.99" />
<button id="submit-form" name="Submit-form" type="submit">Submit</button>
</form>
SCRIPT
<script>
$(function(){
$('#submit-id').on('click', function(e){ // Things to do when
.......
.done(function(data) {
data = JSON.parse(data);
$('#txt1').val(data.txt1);
$('#txt2').val(data.txt2);
$('#q1').val(data.q1);
});
});
});
</script>
/tst/orders2.php
<?php
// Create the connection to the database
$con=mysqli_connect("xxx","xxx","xxx","xxx");
........
while ($row = mysqli_fetch_assoc($result))
{
echo json_encode($row);
die(); // assuming there is just one row
}
}
?>
Don't use ID because you have same ID of both radio buttons
done(function(data) {
data = JSON.parse(data);
$('#txt1').val(data.txt1);
$('#txt2').val(data.txt2);
// Don't use ID because the name of id is same
// $('#q1').val(data.q1);
var $radios = $('input:radio[name=q1]');
if($radios.is(':checked') === false) {
$radios.filter('[value='+data.q1+']').prop('checked', true);
}
});
You currently have both radio buttons using the same ID. ID's should be unique.
You can use the [name] attribute to do this, or you can set a class on the element. Here is an example:
$('input[name=q1][value="'+ data.q1 +'"]').prop('checked', true);
You can do it based on the value of said input:
instead of
$('#q1').val(data.q1);
Try
$('input:radio[value="' + data.q1 + '"]').click();
On a side note, you have both radios with the same ID, the results of an id based selector are going to vary from browser to browser because an id should be UNIQUE
you can refer the following link to solve your problem. works fine for me
JQuery - how to select dropdown item based on value
The question look quite confusing but here is what i need, I use snipe IT ams application which is built on laravel framework.
I have a html page with a textbox and two radio button namely automatic and manual when user clicks on automatic button a php function is called and a random number is generated and the textbox field will become disabled on the other hand whenever a user clicks the manual button the textbox field must become enabled and the user can enter a value in the textbox field.
<script>
function CreateRandomNumber()
{
$('#asset_number').attr('value',("<?php CreateRandomNumber(); ?>"));
$('#asset_number').attr('disabled','disabled');
}
function EnableManualTextfield()
{
$('#asset_number').removeAttr('disabled');
$('#asset_number').val("");
}
</script>
<div class="form-group {{ $errors->has('asset_number') ? ' has-error' : '' }}">
<label for="asset_number" class="col-md-3 control-label">#lang('admin/assetdetails/form.number')</label>
<div class="controls col-md-7">
<input class="form-control assettext" type="text" name="asset_number" id="asset_number" value="{{ Input::old('asset_number', $assetdetail->asset_number) }}" />
{{ $errors->first('asset_number', '<span class="alert-msg"><i class="icon-remove-sign"></i> :message</span>') }}
<input class="radio-button" type="radio" id="automatic" name="asset" onclick="CreateRandomNumber()" value="{{ Input::old('automatic',$assetdetail->automatic) }}" class="align-check1">
<label for="automatic" class="control-label">#lang('admin/assetdetails/form.auto')</label>
<input class="radio-button align-check2 manualradio" type="radio" id="manual" name="asset" onclick="EnableManualTextfield()" checked="checked" value="{{ Input::old('manual',$assetdetail->manual) }}">
<label for="manual" class="manualtext">#lang('admin/assetdetails/form.manual')</label>
</div>
</div>
/* CreateRandomNumber Function */
/* This function is written seperately in a php file */
<?php
function CreateRandomNumber() {
$letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$numbers = rand(100, 999999);
$prefix = "SS-";
$randomNumber = $prefix . $numbers ;
echo $randomNumber;
}
?>
Now the problem is whenever a user clicks on automatic a number is getting generated and if returned back to manual the text field gets enabled as expected, but i need do design it in such a way that if the user return backs to automatic button the pre-generated number must be display in the textfield.
Please note that the form is not yet submitted i need to store the generated random number in a variable and get the same number back when gets backs to the automatic field i do know how to achieve this please help me i am new to php and laravel.
Value is not an attribute, so you have to change
$('#asset_number').attr('value',("<?php CreateRandomNumber(); ?>"));
into
$('#asset_number').val("<?php CreateRandomNumber(); ?>");