Validation for textfield to restrict for 6 digits - javascript

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>

Related

Storing array in yii framework

I have this form in the view:
<form method="POST" action="<?php echo Yii::$app->request->baseUrl;?>/telephone/addnow/" role="form" enctype="multipart/form-data">
<label>Upload your photo:</label><input type="file" name="image" ><br>
<input type="name" name="name" id="name" placeholder="Name" required><br><br>
<input type="text" name="address" placeholder="Address"><br><br>
<input type="text" name="telephone" placeholder="Telephone number" required>
<br><br>
<div id="dynamicInput">
<br><input type="text" name="myinputs[]" placeholder="Secondary Phone #1">
<span class="glyphicon glyphicon-plus" onClick="addInput('dynamicInput');"></span>
<br><br>
</div>
<input type="text" name="mobile" placeholder="Mobile number" > <br><br>
<input type="email" name="email" placeholder="Email">
<input type="email" name="altemail" placeholder="Alternative Email"><br><BR>
<input type="text" name="company_name" placeholder="Company Name"><br><BR>
<input type="text" name="company_address" placeholder="Company Address"><br><br>
<input type="text" name="company_phone_primary" placeholder="Company Telephone">
<input type="text" name="company_phone_secondary" placeholder="Telephone Secondary "><br><br>
<input type="text" name="company_email" placeholder="Company Email Address"><br><BR>
<button type="submit" class="btn btn-default">Submit</button><BR><BR>
</form>
allowing the user to insert any number of secondary phones i used this javascript code:
<script>
var counter = 1;
var limit = 10;
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Seconday Phone # " + (counter + 1) + " <br><input type='text' name='myinputs[]' placeholder='Secondary Phone '>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
And I have this controller code:
public function actionAddnow()
{
$request = Yii::$app->request;
$add=new telephone();
$add->Name=$request->post('name');
$add->Email=$request->post('email');
$add->Mobile=$request->post('mobile');
$add->Address=$request->post('address');
$add->Telephone=$request->post('telephone');
$add->altemail=$request->post('altemail');
$add->company_name=$request->post('company_name');
$add->company_address=$request->post('company_address');
$add->company_phone_primary=$request->post('company_phone_primary');
$add->company_phone_secondary=$request->post('company_phone_secondary');
$add->company_email=$request->post('company_email');
$add->save();
$getlast=Yii::$app->db->getLastInsertId();
$myinputs=$request->post('myinputs');
$totalinputs=sizeof('$myinputs');
for ($i=0; $i<=$totalinputs; $i++) {
$inputs=$myinputs[$i];
$phones=new phone();
$phones->secondary_phones=$inputs;
$phones->id=$getlast;
$phones->save();
}
return $this->redirect(Yii::$app->request->baseUrl.'/telephone/index');
}
but only the first two values of $myinputs are inserted in the database.
Putting variable $myinputs between single quotation marks ('$myinputs') you will convert your variable to string. sizeof is alias for count function, but as you give argument as string you allways get result as 1. After you will loop with condition ($i=0; $i<=$totalinputs; $i++) meaning that cycle will run 2 times when $i is 0 and when $i is 1.
Instead of:
$totalinputs=sizeof('$myinputs');
You should use
$totalinputs=sizeof($myinputs);
Another error is in your cycle condition.
for ($i=0; $i<=$totalinputs; $i++)
Should be
for ($i=0; $i<$totalinputs; $i++)
Or you could replace for cycle with foreach
foreach($myinputs as $inputs)
{
$phones=new phone();
$phones->secondary_phones=$inputs;
$phones->id=$getlast;
$phones->save();
}
On Yii side of improvements
1.For form you could use ActiveForm widget
$form = \yii\widgets\ActiveForm::begin([
'options' => [
"role" => "form",
"enctype"=> "multipart/form-data",
], ]);
echo $form->field($add, 'Name');
//etc
$form->end();
2.If you would use ActiveField for creating input fields in view or adding manually field names in format like ModelClassName[ModelFieldName], then you would be able to use Model load for assaign'ing values
Example:
$add=new telephone();
if ($add->load(Yii::$app->request->post()))
{
if ($add->save())
{//saved
}
else
{//error
}
}
else
{//no post data
}
3.For urls its probably not needed to add request baseUrl property. Example in redirect you can simply use
$this->redirect('/telephone/index');
4.Using method getLastInsertId() may lead to errors when there are some triggers in database that will create additional rows. So it may be wiser to use:
$getlast=$add->id;//assuming model autoincrement field name is "id"

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;
}

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.

How to button enable when all textbox has value in jQuery?

I am new in programming. Here I have given description of my problem
I have one pair of two text box. One text box is for URL and other is for instruction but all text-boxes created dynamically depending on what value comes from database.
For example $testing_type_id=2 so I get total two pair of text boxes, let it called bundle. $i is used to identify textbox uniquely.
<input type = "text" size="33" class="uploadtxt1 url" name="txturl_<?php echo $testing_type_id ; ?>" id = "txturl_<?php echo $testing_type_id; ?>_<?php echo $i ; ?>" value="" />
<input type = "text" class="uploadtxt2" size="33" name="txtinstruction_<?php echo $testing_type_id ; ?>" id = "txtinstruction_<?php echo $testing_type_id; ?>_<?php echo $i ; ?>" value="" /> <br/>
<input type="submit" name="checkout" id="checkout" class="graybtn1 ptr button_float_left_checkout" disabled="disabled" value="Proceed To Checkout" />
Here what I wanted to do that if all bundle has value, either in one textbox or both textbox so and so enable submit button. If I removed value so disable submit button using jQuery.
I think this will work
$(document).ready(function(){
$("input[class^='uploadtxt']").keyup(function(e){
var alltxt=$("input[class^='uploadtxt']").length;
var empty=true;
$("input[class^='uploadtxt']").each(function(i){
if($(this).val()=='')
{
empty=true;
$('#checkout').prop('disabled', true);
return false;
}
else
{
empty=false;
}
});
if(!empty) $('#checkout').prop('disabled', false);
});
});​
An example is here.
if($('.uploadtxt1').val() !='' && $('.uploadtxt2').val() !='')
{
$('#checkout').hide();
}
else
{
$('#checkout').show();
}
So assuming you want to show/ enable the button if the textareas / inputs have values. You could do something like this using jQuery.
$(window).ready(function(){
if( $('input, textarea').val().length >=0 ){
//run function to enable button
}
else if ( $('input, textarea').val().length <=0 ){
//run function to disable button
}
});
I think this is what you are sort of looking for. Let me know if I am way off or not understanding you correctly.
I am going to suggest a minor markup changes so that will be easy to handle the traversing.
Wrap the elements in a <div>
<div class="item">
<input type = "text" size="33" class="uploadtxt1 url" name="txturl_<?php echo $testing_type_id ; ?>" id = "txturl_<?php echo $testing_type_id; ?>_<?php echo $i ; ?>" value="" />
<input type = "text" class="uploadtxt2" size="33" name="txtinstruction_<?php echo $testing_type_id ; ?>" id = "txtinstruction_<?php echo $testing_type_id; ?>_<?php echo $i ; ?>" value="" /> <br/>
<input type="submit" name="checkout" id="checkout" class="graybtn1 ptr button_float_left_checkout" disabled="disabled" value="Proceed To Checkout" />
</div>
Then, Attach a snippet on the change event
$("input[type=text]", $(".item")).change(function() {
var allField = true;
$(this).closest(".item").find("input[type=text]").each(function() {
allField = allField && ($(this).val().length > 0)
});
if(allField) {
$(this).closest(".item").find("input[type=submit]").prop('disabled', false);
}
});
Demo of Working Solution

get the product automatically from dynamic textbox using 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>" />

Categories

Resources