Onclick copy input text to another location - javascript

I am making a admin panel. When users input data into a text field i want to copy the data in the text field to another text field.
My problem is the code works until i added a insert into database function to the same button.
How do i get the button to perform both functions. is there a better way to do the onclick function. As i am using two text fields but i really want one to be the product title. Like in the image below:
Code is
<?php
$add_product_errors = array();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// price validate - must be decimal(float)
if (empty($_POST['price']) || !filter_var($_POST['price'], FILTER_VALIDATE_FLOAT) || ($_POST['price'] <= 0)) {
$add_product_errors['price'] = "Please enter a product price";
}
// item name validate
if (empty($_POST['item_name'])) {
$add_product_errors['item_name'] = "Please enter a name";
}
// item name description
if (empty($_POST['desc'])) {
$add_product_errors['desc'] = "Please enter a product description";
}
//add to database
//if (empty($add_product_errors)) {
$q = 'INSERT INTO Product (Product_Name,Product_Desc,Product_Price) VALUES (?,?,?)';
$stmt = mysqli_prepare($dbc, $q);
//debugging
$stmt = mysqli_prepare($dbc, $q) or die(mysqli_error($dbc));
mysqli_stmt_bind_param($stmt, 'sss', $item_name, $desc, $price);
$item_name = strip_tags($_POST['item_name']);
$desc = strip_tags($_POST['desc']);
//100 - changes the way the decimal displays in database
$price = strip_tags($_POST['price'] * 100);
//execute the query
mysqli_stmt_execute($stmt);
printf("%d Item Added.\ ", mysqli_stmt_affected_rows($stmt) === 1); {
mysqli_stmt_close($stmt);
}
}
?>
HTML
<form name="product_form" enctype="multipart/form-data" action="admin_p.php" method="post" accept-charset="utf-8" >
<input type="textfield" id="title" name="title" value="">
<input type="textfield" id="item_name" name="item_name" placeholder="item name" value="" <?php $add_product_errors ?>/><br>
<textarea id="desc" name="desc" value="" placeholder="Item description" rows="3" maxlength="200" required ><?php $add_product_errors ?></textarea><br>
<input type="textfield" id="price" name="price" value="" placeholder="£" maxlength="30" required <?php $add_product_errors ?>/><br>
<input type="submit" name="add" value="add" value="add" class="btn" onclick="myFunction()">
<!-- copy item_name to page title -->
<script>
function myFunction() {
document.getElementById("title").value = document.getElementById("item_name").value;
}
</script>

Consider changing the submit input to a regular button so that you can control the control flow entirely. It might also make the control flow clearer for you to understand.
<form name="product_form" enctype="multipart/form-data" action="admin_p.php" method="post" accept-charset="utf-8" onsubmit="myFunction()">
... your HTML here ...
<input type="button" name="add" value="add" value="add" class="btn" onclick="myFunction()">
</form>
<script>
function myFunction() {
// Update your field value
document.getElementById("title").value = document.getElementById("item_name").value;
// Submit your form.
document.forms["product_form"].submit();
}
</script>

You can bind the copying of the text on the onsubmit event like this:
<form name="product_form" enctype="multipart/form-data" action="admin_p.php" method="post" accept-charset="utf-8" onsubmit="myFunction()">

Related

How to POST a javascript generated result as input value on a form

This is probably something basic but I'm strugle with it.
I construct a binary string for the 12 mounths of the year, using 12 checkboxes as:
const checkboxes = [...document.querySelectorAll('input[type=checkbox]')];
function RegMD() {
document.getElementById("season").textContent =
checkboxes.reduce((a, b) => a + (b.checked ? 1 : 0), "");
}
and the html code for it:
<input type="checkbox" id="jan"><label>january</label><br>
<input type="checkbox" id="feb"><label>february</label><br>
<input type="checkbox" id="mar"><label>march</label><br>
...
<br>
<p id="season"></p>
<br>
<button type="button" onclick="RegMD()">Register My Data</button>
The above code generate for me the string and display it.
These checkboxes are inputs on a form where I have other input fields as well:
<form id="register_form" method="post" role="form" action="">
<input autofocus="" id="firstname" name"firstname" placeholder="First Name" type="text" required />
<textarea id="Address" name="Adress" placeholder="No Address" type="text" rows="3" cols="30"></textarea>
<select id="country" name="country" required>
<option selected>Choose</option>
<option value="10">Germany</option>
<option value="11">Poland</option>
<option value="12">United Kingdom</option>
</select>
<button type="submit">Submit My New Entry</button>
</form>
which I send through POST send to a database using:
<?php
if (isset($_POST["firstname"])){
try {
//open the database
$pdo = new PDO('sqlite:db/users.db');
$firstname = $_POST["firstname"];
$Address = $_POST["Address"];
$country = $_POST["country"];
$data = [
'firstname' => $firstname,
'Address' => $Address,
'country' => $country,
];
$sql="INSERT INTO details (firstname, Address, country) VALUES (:firstname, :Address, :country)";
$stmt= $pdo->prepare($sql);
$stmt->execute($data);
$pdo = NULL;
} catch(PDOException $e) {
print 'Exception : ' .$e->getMessage();
}}
?>
My request is, how can I get the generated string
<p id="season"></p>
and include it in the POST method to be sent into the database?
The string now is generated on a separate button click and how I need to declare it to be picked up and sent together with the other information through POST method. Thank you.
###############################
Edit.
###############################
by changing the textContent into value in my script:
document.getElementById("season").textContent = checkboxes.reduce((a, b) => a + (b.checked ? 1 : 0), "");
into
document.getElementById("season").value = checkboxes.reduce((a, b) => a + (b.checked ? 1 : 0), "");
and putting a input field for the result:
<input type="text" id="season" name="season" value="" required >
I managed using the button onclick event to display my generated string into a input field and than using SUBMIT to be sent into my database.
BUT I receive another issue as you can see it in my printscreen:
all recorded value goes as "value" and the firts 0's are trimmed from my string. Initial textContent are not worked.
I found few solutions to do something before on submit as it is: here and here but i can't make it work.
my full code is:
<!doctype html>
<html>
<head>
<script type='text/javascript' src="js/jquery.min.js"></script>
</head>
<body>
<form id="register_form" method="post" role="form" action="#">
<table border=0>
<tr><td>First Name: <td><input autofocus="" id="firstname" name="firstname" placeholder="First Name" type="text" required />
<tr><td>Address: <td><textarea id="Address" name="Address" placeholder="No Address" type="text" rows="3" cols="30"></textarea>
<tr><td>Country: <td><select id="country" name="country" required>
<option value="" selected >Choose</option>
<option value="10">Germany</option>
<option value="11">Poland</option>
<option value="12">United Kingdom</option>
</select>
<tr><td>Season: <td>
<input type="checkbox" id="jan"><label>january</label><br>
<input type="checkbox" id="feb"><label>february</label><br>
<input type="checkbox" id="mar"><label>march</label><br>
<button type="button" onclick="RegMD()">Generate season string</button>
<tr><td>Season: <td><input type="text" id="season" name="season" value="" required >
<tr><td><input type="submit" value="Add New Record" >
</table>
<script>
const checkboxes = [...document.querySelectorAll('input[type=checkbox]')];
function RegMD() {
document.getElementById("season").value = checkboxes.reduce((a, b) => a + (b.checked ? 1 : 0), "");
}
</script>
</form>
<?php
IF (isset($_POST['firstname'], $_POST['country'], $_POST['season']) // checking texfield and combobox if are empty
AND !empty($_POST['Address'])) // checking textarea if is empty
{
try {
$firstname = $_POST["firstname"];
$Address = $_POST["Address"];
$country = $_POST["country"];
$season = $_POST["season"];
$data = ['firstname' => $firstname,
'Address' => $Address,
'country' => $country,
'season' => $season,
];
$pdo = new PDO('sqlite:db/users.db');
$pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO details (firstname, Address, country, season)
VALUES (:firstname, :Address, :country, :season)";
$stmt = $pdo->prepare($sql);
$stmt -> execute($data);
$pdo = NULL;
} catch(PDOException $e) {print 'Exception : ' .$e->getMessage();}
}
?>
</body>
</html>
How can I make it work?
###########################
Second Edit.
###########################
the value from my database for the string insert was fixed by changing the column declararion of my database from INTEGER to VARCHAR as was proposed by ADyson.
How can i move the javascript to be generated and submited on SUBMIT?
Instead of having a p element <p id="season"></p>, you can use a readonly input field, inputs are picked up by the form and sent automatically: <input id="season" readonly>.
To have it calculated automatically you can instead of a click event handler add an submit event handler to the form element. Alternatively if you wish to display the the updates to the user you can use the change event on the checkboxes. And update the value of the input: document.getElementById("season").value = ...
P.S. It's better to register event handlers in JS rather than in the HTML: element.addEventListener('change', updateValue);
Thank you guys for all your advises, finally i solved it as you giuded me with: onsubmit="return RegMD();"
<form id="register_form" method="post" role="form" action="#" onsubmit="return RegMD();">
and
<input type="hidden" id="season" name="season" value="">

Ajax PHP not inserting into MySQL database

I'm using Ajax to get POST values from a form. However, when I try to insert the form values in a database on submit, it doesn't get inserted. I still have no idea why it does not work.
Here is my HTML
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input">
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input">
<br><font class="text-error" id="sign-up-error-text"></font><br>
<label><input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font></label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
My JS (the console.log does go through and work):
if (validForm)
{
console.log("valid form");
$.ajax(
{
type:'POST',
url:'form-submit.php',
data:$('#home-sign-up-form').serialize(),
success:function(response)
{
$suForm.hide();
$tosppText.hide();
$mailSentIcon.show();
$emailSentText.show();
$emailSentTextEmail.text($suEmail);
$suBox.css("padding-left", "10px");
$suBox.css("padding-right", "10px");
}
});
}
And my PHP/MySQL:
if (isset($_POST['signUp']))
{
echo "<script type='text/javascript'>alert('got');</script>";
$suFirstName = mysqli_real_escape_string($_POST['suFirstName']);
$suLastName = mysqli_real_escape_string($_POST['suLastName']);
$suEmail = mysqli_real_escape_string($_POST['suEmail']);
$suPassword = mysqli_real_escape_string($_POST['suPassword']);
$suDisplayName = mysqli_real_escape_string($_POST['suDisplayName']);
$code = substr(md5(mt_rand()),0,15);
$query = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName,confirmCode,verified)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}','{$confirmCode},'{$verified}')");
}
The alert in the PHP code so I would assume that it isn't getting the 'signUp' POST variable. Thanks so much! Any help is appreciated! :D
You get the signUp post variable when you click on the button. If you are posting via ajax call the button variable will not be available as $_POST variable. Please check any other input value.
Another options is have and hidden input set it to some value. And check it on server side. But it is better to check any normal required input of form instead of having extra input control.
$mysqli = new mysqli("localhost", "root", "", "test");
if (isset($_POST['signUp'])){
echo "<script type='text/javascript'>alert('got');</script>";
echo $suFirstName = mysqli_real_escape_string($mysqli,$_POST['suFirstName']);
echo $suPassword = mysqli_real_escape_string($mysqli,$_POST['suPassword']);
$sql="INSERT INTO users (`username`, `password`) VALUES ('$suFirstName', '$suPassword')";
}
if (!mysqli_query($mysqli,$sql)) {
die('Error: ' . mysqli_error($mysqli ));
}
echo "1 record added";
mysqli_real_escape_string requires two arguments the connection and the string.
You can read more :https://www.w3schools.com/php/func_mysqli_real_escape_string.asp

Javascript id as parameter in href

Second image ,First image I have a set of links, which will open a pop-up form.
When the link is clicked,I want to send a parameter to the form and then use it on form submission.
I'm able to set the value to be passed as id of <a> tag. Can I send to further?
<div> <span>Chapter $i:</span>
<a href='$viewlink '>View</a><span class='status'>Status:$status </span>
<a href=$reqlink id=$i data-rel='popup' class='ui-btn ui-btn-inline ui-corner-all ui-icon-check ui-btn-icon-left'>Request Access</a></div><br/>";
<form method="post" action=" " id="myPopup" data-role="popup" style="padding:10px">
<h3>Enter your details</h3>
<input type="text" name="name" id="name" placeholder="Name" required>
<input type="email" name="email" id="email" placeholder="Email" required>
<input type="date" name="date" id="date" placeholder="Intended completion date" required>
<input type="submit" data-inline="true" value="Submit" name='submit'>
</form>
Is it possible to do in javascript? How to do it?
Option #1:
Set up hidden inputs, and send the values to them when clicking the link. You can then get these on the other end where the form is sent.
(Note: in my code examples I'm explicitly using PHP as that's where you seem to have copied your code snipped from)
echo "<a href='$viewlink' onclick='$(\'#viewlink\').val(1);'>View</a><span class='status'>Status:$status </span>
<!-- Do the following inside the form -->
<input type='hidden' name='viewlink' id='viewlink' value='0' />";
And on the PHP receiving end you can do this:
if ($_POST['viewlink'] == 1) {
// do stuff
}
Option #2:
Alternatively you could send the data to a javascript array, prevent posting on submit of the form, take care of adding the array to the form action as query string, then explicitly send the form.
echo "<a href='$viewlink' onclick='linkClicked('viewlink');'>View</a><span class='status'>Status:$status </span>
This is what you'd do in your javascript file:
var queryString = [];
function linkClicked (type) {
queryString[type] = 1;
}
$("#myPopup").submit(function(event) {
event.preventDefault();
$(this).attr('action', $(location).attr('host') + $.param(queryString));
$(this).submit();
});
And on the PHP receiving end you can do the following (note the $_POST from above has changed to $_GET):
if ($_GET['viewlink'] == 1) {
// do stuff
}
try this..
<a id = 'yourid' class = 'mybtn'>click me..</a>
<form id = 'myform'>
....
</form>
Jquery
$(document).ready(function(){
$('.mybtn').click(function(){
var id = $(this).attr('id');
var SubmitForm = $("#myform").serializeArray();
$.post("somepage.php",
{
SubmitForm:SubmitForm,
ID:id
},
function(res){
alert(res);//your result..
});
});

autofill textbox with database values when 1st value is entered

Here i am linking the question and it is the continuation of that question LINK IS HERE
Actually i have made that work by changing the script like this
my javascript
<script type="text/javascript">
$(document).ready(function()
{ var ac_config = { source: "fill_patient_info.php", select: function(event, ui){ $("#p_name").val(ui.item.p_name); $("#p_dob").val(ui.item.p_dob) }, minLength:1 }; $("#p_name").autocomplete(ac_config); });
</script>
and in fill_patient_info1.php
$p_name = $_GET['p_name'];
$result = mysql_query("SELECT patient_id, patient_name, dob from patient WHERE patient_name LIKE '".$p_name."%'");
$myrow = mysql_fetch_array($result);
if(mysql_num_rows($result))
{
$p_name = $myrow["patient_name"];
$p_dob = $myrow["dob"];
$textout = $p_name.','.$p_dob;
echo $textout;
}else
{
echo "Sorry This Patient Does Not Exist";
}
It is not working properly. If i have more than 1 name with the same letter, i cannot type in the 1st textbox. As soon as i enter the 1st letter it just fills up both the name and dob with the 1st patient name starts with that letter. after that i cannot delete and change that too.
Here is my input box for patient name and dob, which should be filled automatically(form)
<form name="consult" method="post" action="consult_submit.php" enctype="multipart/form-data" onsubmit="return validate()">
<table class="selection">
<tr><td>Patient Name :</td><td><input type="text" name="p_name" id="p_name" onkeyup="return filldetail()" /></td></tr>
<tr><td>DOB :</td><td><input type="text" name="p_dob" id="p_dob" class="tcal" /></td></tr>
please suggest how to correct it
Instead of onkeyup you need to use onblur. If you use onkeyup event, the javascript function is called whenever you complete entering a charecter with keyboard. If you use onblur, the function will be called when you finish entering the text and change focus from the text field.
<form name="consult" method="post" action="consult_submit.php" enctype="multipart/form-data" onsubmit="return validate()">
<table class="selection">
<tr><td>Patient Name :</td><td><input type="text" name="p_name" id="p_name" onblur="return filldetail()" /></td></tr>
<tr><td>DOB :</td><td><input type="text" name="p_dob" id="p_dob" class="tcal" /></td></tr>

Simple Percentage Calculation of an Input Field with JQuery

I'm building a PayPal form that the user enters the amount and after that transfered to paypal,
everything is working fine but i need to add a calculation plugin to do the following,
If a user enters in the field 10$ (Calculate 10$-2%=8$) and return the result as text inside a span 8$
At the end of the form i have a "(p) paragraph" with a span id "site_commission_box" inside.
I need to show the calculated number inside this span.
Which JQuery plugin is good for use on this and how i can use it?
Any good example or tutorial to find out how i can do it?
Thanks a lot,
Philip
<form id="form_paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="business" value="mail#url.url"/>
<input type="hidden" name="cmd" value="_xclick"/>
<input type="hidden" name="return" value="http://returnpage.url"/>
<input type="hidden" name="cancel_return" value="http://cancelreturnpage.url"/>
<input type="hidden" name="rm" value="2"/>
<input type="hidden" name="currency_code" value="USD"/>
<input type="hidden" name="quantity" value="1"/>
<input type="hidden" name="item_name" value="Item Name"/>
<input type="hidden" name="item_number" value="Item ID"/>
<label>Amount (US$) : </label>
<input type="text" name="amount" id="input_amount" class="text" />
<input type="hidden" name="invoice" value="Post ID"/>
<input type="hidden" name="cbt" value="Make Payment →"/>
<input type="hidden" name="item_number" value="Item ID"/>
<input type="submit" name="submit" value="Confirm & Pay →" class="submit" />
<br/>
<span id="msg_moreamount" class="icon_warning red" style="display:none;">PayPal takes $0.35 commission for a $1 donation.</span>
<span id="msg_noamount" class="icon_warning red" style="display:none;">Please enter an amount and try again.</span>
<span id="msg_activity" style="display:none;"> <img src="loader.gif" align="middle" alt="load"/> Transferring to PayPal, please wait...</span>
<p>-2% of the price it will be <b>$<span class="text_decoration" id="site_commission_box"></span> USD</b>.</p>
</form>
Is there a reason you use jQuery() instead of $()?
Also, you should really cache your selected elements so you don't have to query the DOM multiple times for the same element.
Here's how I would do it:
$(function() {
// the minimum required value to be entered.
// in this case PayPal takes $0.35 from a $1
// donation, hence we ask for at least $1.35
var minimum_value = 1.35;
// cache elements that are used at least twice
var $amount = $("#input_amount"),
$msg = $("#msg"),
$commission = $("#site_commission_box");
// attach handler to input keydown event
$amount.keyup(function(e){
if (e.which == 13) {
return;
}
var amount = parseFloat($amount.val()),
commission = amount*0.02;
if (isNaN(commission) || isNaN(amount)) {
$msg.hide();
$commission.hide();
return;
}
if (amount <= minimum_value) {
$commission.hide();
$msg
.text("PayPal takes $0.35 commission for a $"+amount+" donation.")
.fadeIn();
} else {
$msg.hide();
$commission
.fadeIn()
.find("span")
.text((amount-commission).toFixed(2));
}
});
// attach handler to the form submit event
$('#form_paypal').submit(function() {
// check if there is an amount entered
if ($amount.val() > null) {
// is the amount equal to or higher than the minimum_value?
if ($amount.val() < minimum_value) {
// need more amount
// show more amount error
$msg
.addClass("icon_warning_red")
.text("Please enter an amount and try again.")
.fadeIn();
return false; // prevent the form from submitting
}
else {
// amount is more than minimum_value
// show activity
$msg
.removeClasss("icon_warning_red")
.html('<img src="loader.gif" align="middle" alt="load"/> Transferring to PayPal, please wait...')
.fadeIn();
return true; // submit the form
}
}
else {
// no amount entered at all
// show no amount error;
$msg.addClass("icon_warning_red").fadeIn();
return false; // prevent the form from submitting
}
});
});
You can see a working example here, there you can see the changes I did in the HTML as well.
You have to add a event-handler for a change event. Everytime if the input value is changed the discount is recalculated. See an example on http://jsfiddle.net/3sXZw/

Categories