get the product automatically from dynamic textbox using javascript - javascript

I'd been searching for 2 days now and i cant find the solution for my problem.
I wanted to automatically multiplied two numbers from dynamically generated textbox with the use of PHP coming from mysql
FROM THIS
<input name="qty<?php echo $x ?>" type="text" id="qty<?php echo $x ?>" size="6" maxlength="10" onfocus="startCalc();" onblur="stopCalc();">
<td><label>
<input name="unit<?php echo $x ?>" type="text" id="unit<?php echo $x ?>" size="9" maxlength="12" onfocus="startCalc();" onblur="stopCalc();">
</label></td>
<td><input name="total<?php echo $x ?>" type="text" id="total<?php echo $x ?>" size="9" maxlength="12" style="background-color:#FFCC33" readonly></td>
</tr>
heres my javascript
function startCalc(){
interval = setInterval("Unit()",1);
}
function Unit()
{
var cost = document.getElementsByName('unit');
for(var i=1; i<cost.length; i++)
{
unit[i] = document.getElementById('unit' + i).value;
srr_qty[i]= document.getElementById('qty' + i).value;
total[i]=(unit[i] * 1)*(qty[i]* 1);
document.getElementById('srr_total'+ i).value = total[i];
totalAmount[i]=document.getElementById('total' + i).value;
return (totalAmount[i])
}
}
function stopCalc(){
clearInterval(interval);
}
Hope you can understand what i wanted to do.. thanks and hoping for your quick response :)

set the value attribute for input tags <input type="text" value="<something here>" />

Related

Saving form data into dynamic form when hitting back or refreshing page

Right now I have code to dynamically add input fields to my form. I want to be able to submit the data and go to the next page but if someone decides to go back, the newly made input fields would still be there with the data. The way I have it set up now is to echo onto the input fields which works with the first two but not the third.
When I hit back, I get this:
Here is my code:
<h2>Enter Beneficiaries for Tangible Personal Property:</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="input_fields_container">
<tr>
<td>Name:<input type="text" name="ben[]" value="<?php echo $_SESSION['ben']['0'];?>" class="form-control name_list" /></td>
<td>Percentage of tangible personal property:<input type="number" min="0" max="100" value="<?php echo $_SESSION['percent']['0'];?>" style="width: 40px" name="percent[]" class="form-control name_list" /></td>
<td><input type="button" name="add" id="add" class="add_more_button" value= "Add Another" ></input></td>
</tr>
</table>
</div>
<p style="color:red;"></p>
<h3>Enter Contingent Beneficiary: </h3>
Name:<input type="text" name="conben" value="<?php echo $_SESSION['conben'];?>" >
<br><br>
<button type="button" name="back" value="back" onclick="location.href='county.php'">Back</button>
<input type="submit" name="submitform" value="Next"></input>
<button type="button" name="download" onclick="location.href='downloadAdd.php'">Download will</button>
</form>
<script>
//script to add/remove fields
$(document).ready(function () {
var getControl=getCookie("countControls1");
var max_fields_limit = 2; // Set limit for maximum input fields
var x = 0; // Initialize counter for text box
for(var i=1; i<=getControl; i++) {
console.log(i);
addControls();
}
$('.add_more_button').click(function (e) { // Click event to add more fields
addControls();
});
function addControls()
{
console.log(x);
if (x < max_fields_limit ) {
x++; // Increment counter
setCookie("countControls1",x,100);
$('.input_fields_container').append('<div><tr id="row'+x+'"><td> Name:<input type="text" name="ben[]" value="<?php echo $_SESSION['ben']['1'];?>" class="form-control name_list" /></td><td>&nbspPercentage of tangible personal property:<input type="number" min="0" max="100" style="width: 40px" name="percent[]" value="<?php echo $_SESSION['percent']['1'];?>" class="form-control name_list" /></td><td>Remove</td></tr>');; // Add input field
}
else if (x==2){
$("p").text("*Only 3 tangible beneficiaries are allowed.");
}
}
$('.input_fields_container').on("click", ".remove_field", function (e) { // User click on remove text links
$(this).parent('div').remove();
x--;
$("p").text("");
setCookie("countControls1",x,100);
});
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
$("#div1").html("Add cookie = ",getCookie(cname));
}
function getCookie(cname)
{
console.clear();
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
//console.log(cname);
//console.log(decodedCookie);
console.log(ca);
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
console.log(c.substring(name.length, c.length));
return (c.substring(name.length, c.length));
}
}
return "";
}
});
</script>
Is there anyway to achieve this in this way or do I need to implement something else?
You can just write the fields back using a loop because presumably you have the two arrays in your session. You should also use empty() or isset() to check if the session arrays exist first otherwise you will end up with warnings about undefined keys and such:
<tr>
<td>Name:<input type="text" name="ben[]" value="<?php echo $_SESSION['ben']['0'];?>" class="form-control name_list" /></td>
<td>Percentage of tangible personal property:<input type="number" min="0" max="100" value="<?php echo $_SESSION['percent']['0'];?>" style="width: 40px" name="percent[]" class="form-control name_list" /></td>
<td><input type="button" name="add" id="add" class="add_more_button" value= "Add Another" /></td>
</tr>
<?php
# Remove the first keys since you already used them above
unset($_SESSION['percent'][0],$_SESSION['ben'][0]);
# Just do a normal loop to create any remaining values
foreach($_SESSION['percent'] as $key => $value): ?>
<tr>
<td>Name:<input type="text" name="ben[]" value="<?php echo $_SESSION['ben'][$key];?>" class="form-control name_list" /></td>
<td>Percentage of tangible personal property:<input type="number" min="0" max="100" value="<?php echo $value; ?>" style="width: 40px" name="percent[]" class="form-control name_list" /></td>
</tr>
<?php endforeach ?>

Validation for textfield to restrict for 6 digits

we need to set validation in textfield : "zip code" under checkout process in magento site.
i need to restrict this textfield for maximum 6 digits.
i am using following code for this :
<input type="text" title="<?php echo $this->__('Zip/Postal Code') ?>"
name="billing[postcode]" id="billing:postcode"
value="<?php echo $this->escapeHtml($this->getAddress()->getPostcode()) ?>"
class="input-text validate-zip-international
<?php echo $this->helper('customer/address')->getAttributeValidationClass('postcode') ?>" placeholder="Postal code"/>
please help me to give validation for Restricting only for 6 digits
try this
function limit(element)
{
var max_chars = 6;
if(element.value.length > max_chars) {
element.value = element.value.substr(0, max_chars);
}
}
<input type="text" onkeydown="limit(this);" onkeyup="limit(this); "title="<?php echo $this->__('Zip/Postal Code') ?>"
name="billing[postcode]" id="billing:postcode"
value="<?php echo $this->escapeHtml($this->getAddress()->getPostcode()) ?>"
class="input-text validate-zip-international
<?php echo $this->helper('customer/address')->getAttributeValidationClass('postcode') ?>" placeholder="Postal code"/>
The better way is use the pattern attribute:
<input type="number" maxlength="6" pattern="[0-9]{6,}" placeholder="Zip code" required>
This is an example for validating phone number of 10 digits:
Html :
<input type="text" id="phone" name="phone" onkeypress="phoneno()" maxlength="10">
Script file:
<script>
function phoneno(){
$('#phone').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!(a.indexOf(k)>=0))
e.preventDefault();
});
}
</script>

Adding Discount code button to Paypal buy now button

I'm trying to add a discount code to the paypal button, The javascript works and says the discount code is valid but isn't taking the discount off the amount when you click the buy now button to pay.
Can anyone help me please
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<p>Please click on the link to pay</p>
<input type="hidden" name="cmd" value="_cart" />
<input type="hidden" name="upload" value="1" />
<input type="hidden" name="business" value="<?php echo C_OUR_EMAIL; ?>" />
<input type="hidden" name="first_name" value="<?php echo strfordisp($ofirstname); ?>" />
<input type="hidden" name="last_name" value="<?php echo strfordisp($olastname); ?>" />
<input type="hidden" name="address1" value="<?php echo strfordisp($theorder["oaddress"]); ?>" />
<input type="hidden" name="address2" value="<?php echo strfordisp($theorder["oaddress2"]); ?>" />
<input type="hidden" name="address3" value="<?php echo strfordisp($theorder["oaddress3"]); ?>" />
<input type="hidden" name="city" value="<?php echo strfordisp($theorder["otown"]); ?>">
<input type="hidden" name="zip" value="<?php echo strfordisp($theorder["opostcode"]); ?>" />
<?php
$orderdets = mysql_query("select * from c4d_orderitems where orderid='" . $_SESSION["db_order"] . "' and confirm");
$iloop = 1;
while ($orderrow = mysql_fetch_array($orderdets))
{
$itemdesc = $orderrow["itemtypedesc"];
$itemdesc .= " to " . $orderrow["dpostcode"];
$itemprice = $orderrow["cost"] + $orderrow["surcharge"] + $orderrow["insurancecost"];
?>
<input type='hidden' name="item_name_<?php echo $iloop; ?>" value='<?php echo strfordisp($itemdesc); ?>' />
<input type='hidden' name="item_number_<?php echo $iloop; ?>" value='<?php echo $orderrow["itemtype"]; ?>' />
<input type='hidden' name="amount_<?php echo $iloop; ?>" value='<?php
if ((strtoupper($ofirstname)=="PCTRENDSTEST") || (strtoupper($olastname)=="PCTRENDSTEST") || (substr($_SERVER['REMOTE_ADDR'],0,11)=="82.152.55.1"))
echo("0.01");
else echo $itemprice;
?>' />
<input type='hidden' name="baseamt_<?php echo $iloop; ?>" value='<?php if ((strtoupper($ofirstname)=="PCTRENDSTEST") || (strtoupper($olastname)=="PCTRENDSTEST") || (substr($_SERVER['REMOTE_ADDR'],0,11)=="82.152.55.1"))
echo("0.01");
else echo $itemprice;
?>' />
<input type="hidden" name="basedes_<?php echo $iloop; ?>" value="" />
<input type='hidden' name="quantity_<?php echo $iloop; ?>" value='1' />
<?
$iloop++;
}
?>
<input type="hidden" name="return" value="<?php echo C_SITE_ROOT; ?>stage7.php" />
<meta http-equiv="return" content="3;url=stage7.php" />
<input type="hidden" name="cancel-return" value="<?php echo C_SITE_ROOT; ?>order-cancel.php" />
<input type="hidden" name="notify_url" value="<?php echo C_SITE_ROOT; ?>paypal.php" />
<input type="hidden" name="rm" value="2" />
<input type="hidden" name="invoice" value="<?php echo $_SESSION["db_order"]; ?>" />
<input type="hidden" name="currency_code" value="GBP" />
<input type="hidden" name="no-shipping" value="1" />
<input type="hidden" name="button_subtype" value="products" />
<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynowCC_LG.gif:NonHostedGuest" />
<input type="hidden" name="country" value="GB" />
Enter Coupon code
<input type="text" size="10" name="coupcode"; />
<input type="button" value="Check code" onclick="coupval =this.form.coupcode.value; ChkCoup();" />
<p class='fmenu'><input type="image" src="https://www.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1"></p>
</form>
The javascript is:
var discnt = 0; // no default percent discount
var coupons = new Array ( // place to put coupon codes
"coup1", // 1st coupon value - comma seperated
"coup2", // 2nd coupon value - add all you want
"coup3" // 3rd coupon value
);
var coupdc = new Array ( 5,10,15
// place to put discounts for coupon vals
);
var coupval = "(blanket)"; // what user entered as coupon code
function ChkCoup () { // check user coupon entry
var i;
discnt = 0; // assume the worst
for (i=0; i<coupons.length; i++) {
if (coupval == coupons[i]) {
discnt = coupdc[i]; // remember the discount amt
alert ("This is a valid promo code! \n\n" + discnt + "%" +" discount now in effect.");
return;
}
}
alert ("'" + coupval + "' is not a valid promo code!");
}
function Pound (val) { // force to valid Pound amount
var str,pos,rnd=0;
if (val < .995) rnd = 1; // for old Netscape browsers
str = escape (val*1.0 + 0.005001 + rnd); // float, round, escape
pos = str.indexOf (".");
if (pos > 0) str = str.substring (rnd, pos + 3);
return str;
}
function ReadForm (obj1) { // apply the discount
var amt,des;
amt = obj1.amount_<?php echo $iloop; ?>.value*1.0; // base amount
des = obj1.basedes_<?php echo $iloop; ?>.value; // base description
if (discnt > 0) { // only if discount is active
amt = Pound (amt - (amt * discnt/100.0));
des = des + ", " + discnt + "%" + "dis, COUP = " + coupval;
}
obj1.amount.value = Pound (amt);
obj1.item_name.value = des;
}

php increase and decrease quantity of product?

im noob at php but my question is this:
im having a while loop which presents to me all the products from the db
im trying to add a + and - quantity buttons next to the buy now button that will increase and decrease by pressing them (just display the number not affect the db)
but the problem is that the quantity number won't pass the number 2. Can anyone lend me some brains with this one?
$value = 1; //to be displayed
if(isset($_POST['incqty'])){
$value= $value +1;
echo $value;
}
if(isset($_POST['decqty'])){
$value = $value -1;
echo $value;
}
<form method='post'>
<input type='hidden' name='item'/>
<td><button name='incqty'>+</button><input type='text' size='1' name='item' value='$value'/><button name='decqty'>-</button></td>
</form>
I already tried to do it with js
<form name="f1"> <input type='text' name='qty' id='qty' />
<input type='button' name='add' onclick='javascript:document.getElementById("qty").value++;' value='+'/>
<input type='button' name='subtract' onclick='javascript: document.getElementById("qty").value--;' value='-'/>
</form>
but the buttons were unclickable...
I'm guessing you're learning PHP and because of that not doing this with javascript. Below code should work for you:
<?php
$value = isset($_POST['item']) ? $_POST['item'] : 1; //to be displayed
if(isset($_POST['incqty'])){
$value += 1;
}
if(isset($_POST['decqty'])){
$value -= 1;
}
?>
<form method='post' action='<?= $_SERVER['PHP_SELF']; ?>'>
<!--<input type='hidden' name='item'/> Why do you need this?-->
<td>
<button name='incqty'>+</button>
<input type='text' size='1' name='item' value='<?= $value; ?>'/>
<button name='decqty'>-</button>
</td>
</form>
If I understood the question, you need to show the values of the items in the cart and modify it by pressing + and - button.
I think you shoud use javascript for this (as you are saying that no affects database)
I'm writing some code in jQuery to show an example of the plus button
$('button[name="incqty"]').bind('click', funcion(){
var actual = $('input[name="intem"]').val();
if (actual <= 1) {
actual = actual +1;
}
$('input[name="intem"]').val(actual);
});
Of course is better not to hardcode values in the code and use constants or variables (for the 1 limit) but I hope this example help you.
I tried your javascript snippet and it worked perfectly.
That being said, is there a reason you are not using the HTML number input?
<input type="number" name="quantity" min="1" max="99">
Edit: I used the code from Daan's answer as the template but...
<?php
$value = isset($_POST['item']) ? $_POST['item'] : 1; //to be displayed
?>
<form method='post' action='<?= $_SERVER['PHP_SELF']; ?>'>
<!--<input type='hidden' name='item'/> Why do you need this?-->
<td>
<input type="number" name="item" min="1" max="99" value="<?= $value; ?>">
</td>
</form>
<input type="button" value = "-" onclick="minusbot()" />
<input type="number" name="kgcount" id = "kilohere" value = "1" >
<input type="button" value = "+" onclick="plusbot()" />
<script>
function minusbot()
{
document.getElementById('kilohere').value = parseInt(document.getElementById('kilohere').value) - 1;
var checknumifzero = parseInt(document.getElementById('kilohere').value);
if(checknumifzero < 1) //preventing to get negative value
{
document.getElementById('kilohere').value = 1;
}
}
function plusbot()
{
document.getElementById('kilohere').value = parseInt(document.getElementById('kilohere').value) + 1;
var checknumiffifty = parseInt(document.getElementById('kilohere').value);
if(checknumiffifty > 50) //just a limit
{
document.getElementById('kilohere').value = 50;
}
}
</script>

distributing a value into 3 input tag

I have software design that to distribute a value into 3 input tags.
<?php
while ($row = oci_fetch_array($result, OCI_BOTH)){
$qtyAvailable = $row['QTY_REQUIRED'] - $row['QTY_CNCED'];
echo '<input class="form-control" id="test1" name="quantityToCutCnc" type="number" min="0" max='.$qtyAvailable.' placeholder="CNC">';
echo '<input class="form-control" id="test2" name="quantityToCutScator" type="number" min="0" max='.$qtyAvailable.' placeholder="Scator">';
echo '<input class="form-control" id="test3" name="quantityToCutManual" type="number" min="0" max='.$qtyAvailable.' placeholder="Manual">';
echo '<br/>';
echo '<strong>Total : </strong><div id="spent"></div>';
echo '<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>';
echo '<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.js"></script>';
echo '<script src="componentRequestJS/qtyDistribution.js"></script>';
}
?>
So i need to distribute $qtyAvailable into quantityToCutCnc, quantityToCutScator, and quantityToCutManual. So the sum of those 3 cannot exceed $qtyAvailable. I am assuming that we need to use jQuery with that.
Here's a good starting point, I think:
http://jsfiddle.net/X8RFe/2/
// echo from php
var available = 20;
jQuery('.form_control').on('change',function(event) {
setTimeout(function() {
var used = 0;
jQuery('.form_control').each(function() {
used += (parseInt(jQuery(this).val(),10) || 0);
});
if (used > available) {
var current = parseInt(jQuery(event.target).val(),10);
jQuery(event.target).val(current-(used-available));
}
},1);
});
You'll probably want to test and tweak it a bit further, as I only tested it for a few seconds.

Categories

Resources