I have 4 inputs on a form and I want to do a calculation based on the number of inputs filled.
I have come up with this and it works in IE but not in FF. FF doesnt seem to like the multiple document.getElementById. Any help would be appreciated.
<script type="text/javascript" language="javascript">
function countlines(what) {
var headline = 1 ;
var oneline = 1 ;
var twoline = 1 ;
var webline = 1 ;
var valhead = document.getElementById('adverttexthead').value;
if (/^\s*$/g.test(valhead) || valhead.indexOf('\n') != -1)
{var headline = 0};
var valone = document.getElementById('adverttextone').value;
if (/^\s*$/g.test(valone) || valone.indexOf('\n') != -1)
{var oneline = 0};
var valtwo = document.getElementById('adverttexttwo').value;
if (/^\s*$/g.test(valtwo) || valtwo.indexOf('\n') != -1)
{var twoline = 0};
var valweb = document.getElementById('adverttextweb').value;
if (/^\s*$/g.test(valweb) || valweb.indexOf('\n') != -1)
{var webline = 0};
(document.getElementById('webcost').value = "$" + ((headline + oneline + twoline + webline) * 16.50).toFixed(2));
(document.getElementById('totallines').value = headline + oneline + twoline + webline);
}
</script>
HTML
<input name="adverttexthead" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input name="adverttextone" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input name="adverttexttwo" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input name="adverttextweb" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<input name="totallines" id="totallines" size="4" readonly="readonly" type="text">
<input name="webcost" id="webcost" size="6" readonly="readonly" type="text">
You could put the inputs in a form and do like so:
function countFormElements(formNumber){
var fn = !formNumber ? 0 : formNumber;
var frm = document.getElementsByTagName('form')[fn], n = 0;
for(var i=0,l=frm.length; i<l; i++){
if(frm.elements[i].value !== '')n++;
}
return n;
}
console.log(countFormElements());
You did not set the 'id' attribute on some elements
You reinitialized your variables in the 'if' clauses.
Working code:
<input id="adverttexthead" name="adverttexthead" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input id="adverttextone" name="adverttextone" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input id="adverttexttwo" name="adverttexttwo" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input id="adverttextweb" name="adverttextweb" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<input id="totallines" name="totallines" size="4" readonly="readonly" type="text">
<input id="webcost" name="webcost" size="6" readonly="readonly" type="text">
function countlines(what) {
var headline = 1;
var oneline = 1;
var twoline = 1;
var webline = 1;
var valhead = document.getElementById('adverttexthead').value;
if (/^\s*$/g.test(valhead) || valhead.indexOf('\n') != -1) {
headline = 0
};
var valone = document.getElementById('adverttextone').value;
if (/^\s*$/g.test(valone) || valone.indexOf('\n') != -1) {
oneline = 0
};
var valtwo = document.getElementById('adverttexttwo').value;
if (/^\s*$/g.test(valtwo) || valtwo.indexOf('\n') != -1) {
twoline = 0
};
var valweb = document.getElementById('adverttextweb').value;
if (/^\s*$/g.test(valweb) || valweb.indexOf('\n') != -1) {
webline = 0
};
(document.getElementById('webcost').value = "$" + ((headline + oneline + twoline + webline) * 16.50).toFixed(2));
(document.getElementById('totallines').value = headline + oneline + twoline + webline);
}
Here is a working jsFiddle: http://jsfiddle.net/YC6J7/1/
You'll need to set the id attribute for the inputs as well as the name, otherwise getElementById works inconsistently cross browser.
For instance:
<input id="adverttexthead" name="adverttexthead" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
(Technically name is optional for purposes of document.getElementById, since id is accepted pretty universally, but you'll probably want to keep it so your forms submit correctly.)
For more details, see: Document.getElementById() returns element with name equal to id specified
Related
I created two input fields where they should substract from each other keeping a max value at 100.
Currently it substracted value is shown in the second value. I want it to be interchangeable. Irrespective of whether I put in first or second input field, the answer shows in the other.
Could someone help?
function updateDue() {
var total = parseInt(document.getElementById("totalval").value);
var val2 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val2) { val2 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val2;
var val1 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val1) { val1 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val1;
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue()">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue()">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue()">
</div>
The simple way to achieve this would be to group the inputs by class and attach a single event handler to them. Then you can take the entered value from 100, and set the result to the field which was not interacted with by the user. To do that in jQuery is trivial:
$('.updatedue').on('input', function() {
var total = parseInt($('#totalval').val(), 10) || 0;
var subtracted = total - (parseInt(this.value, 10) || 0);
$('.updatedue').not(this).val(subtracted);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="totalval" name="totalval" value="100" />
<div>
Enter Value:
<input type="text" name="inideposit" class="updatedue form-control" id="inideposit" />
</div>
<div>
Subtracted:
<input type="text" name="remainingval" class="updatedue form-control" id="remainingval" />
</div>
You can easily validate this so that outputs < 0 and > 100 can be discounted, if required.
Edit your code as below
function updateDue(box) {
var total = parseInt(document.getElementById("totalval").value);
if(box == 1){
var val = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val;
}else if(box == 2){
var val = parseInt(document.getElementById("remainingval").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("inideposit");
ansD.value = total - val;
}
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue(0)">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue(1)">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue(2)">
</div>
<input class="red" id="LR2" type="text" value="1" >
<p id="demo"></p> <br>
This is my JS code:
<script>
var price3 = 7; <br>
var price4 = 8; <br>
var selectValue = function RedAlert(data) { <br>
if( $("#LR2").val() = 0) { <br>
var price1 = 5; <br>
} <br>
else { <br>
var price2 = 6; <br>
} <br>
} <br>
var total = selectValue + price3 + price4; <br>
document.getElementById("LR2").innerHTML = <br>
"The total is: " + total; <br>
</script> <br>
maybe
$("#LR2").val() = 0
should be :
$("#LR2").val() == 0
also not sure if the value isn't a string... maybe should cast to number like :
Number( $("#LR2").val() ) == 0
Try this
var selectValue = 0;
if( $("#LR2").val() == 0) {
selectValue = 5;
}
else {
selectValue = 6;
}
I have this textbox:
<td width="10%"><input name="date" type="text" size=11 maxlength=10 /></td>
when typing date in the field it must add a forward slash in it like 09/02/2016
You can do the same functionality in PHP using JS OR jQuery.
Replace
<input name="date" type="text" size=11 maxlength=10 />
To
<!-- SET type="date" -->
<input type="date" name="date">
jQuery Code:-
//Put our input DOM element into a jQuery Object
var $jqDate = jQuery('input[name="date"]');
//Bind keyup/keydown to the input
$jqDate.bind('keyup','keydown', function(e){
//To accomdate for backspacing, we detect which key was pressed - if backspace, do nothing:
if(e.which !== 8) {
var numChars = $jqDate.val().length;
if(numChars === 2 || numChars === 5){
var thisVal = $jqDate.val();
thisVal += '/';
$jqDate.val(thisVal);
}
}
});
Hope it will help you :)
This one was very ticky! This is how I got it working, though it's not complete as you will need to check for when a number is deleted
<input type="hidden" id='counter' value='0'>
<input name="date" id='date' type="text" size=11 maxlength=10 onkeydown="doDate()"/>
<script>
function doDate(){
var dateSoFar = document.getElementById("date");
var counter = parseInt(document.getElementById("counter").value);
counter = counter+1;
document.getElementById("counter").value = counter;
if(counter == 3 || counter == 5 )
document.getElementById("date").value = document.getElementById("date").value + '/';
}
</script>
Try this,
<input name="date" id='date' type="text" size=11 maxlength=10 onkeydown="updateDate()"/>
<script>
function updateDate(){
var dateSoFar = document.getElementById("date");
var counter = dateSoFar.value.length;
if(counter == 2 || counter == 5 )
document.getElementById("date").value = document.getElementById("date").value + '/';
}
</script>
I can't seem to get my JavaScript to add the elements from my HTML page. Do I have a syntax error?
var mondayHours = document.getElementById("mondayHours").value;
var tuesdayHours = document.getElementById("tuesdayHours").value;
var wednesdayHours = document.getElementById("wednesdayHours").value;
var thursdayHours = document.getElementById("thursdayHours").value;
var fridayHours = document.getElementById("fridayHours").value;
var saturdayHours = document.getElementById("saturdayHours").value;
var sundayHours = document.getElementById("sundayHours").value;
var totalHours = mondayHours + tuesdayHours + wednesdayHours + thursdayHours + fridayHours + saturdayHours + sundayHours;
function alertHours() {
alert(totalHours);
}
<fieldset>
<p>Hours of Operation</p>
<p>
<label for="mondayHours">Monday
<input name="mondayHours" type="number" id="mondayHours" />
</label>
</p>
<p>
<label for="tuesdayHours">Tuesday
<input name="tuesdayHours" type="number" id="tuesdayHours" />
</label>
</p>
<p>
<label for="wednesdayHours">Wednesday
<input name="wednesdayHours" type="number" id="wednesdayHours" />
</label>
</p>
<p>
<label for="thursdayHours">Thursday
<input name="thursdayHours" type="number" id="thursdayHours" />
</label>
</p>
<p>
<label for="fridayHours">Friday
<input name="fridayHours" type="number" id="fridayHours" />
</label>
</p>
<p>
<label for="saturdayHours">Saturday
<input name="saturdayHours" type="number" id="saturdayHours" />
</label>
</p>
<p>
<label for="sundayHours">Sunday
<input name="sundayHours" type="number" id="sundayHours" />
</label>
</p>
</fieldset>
<input name="Calculate" type="submit" value="submit" onclick="alertHours()" />
<script src="Calculator_script.js"></script>
You have to retrieve form data when you called your alertHours function.
The problem was that you retrieved form data at the beginning, and these data were undefined.
JS
function alertHours(){
var mondayHours = parseFloat(document.getElementById("mondayHours").value) || 0;
var tuesdayHours = parseFloat(document.getElementById("tuesdayHours").value) || 0;
var wednesdayHours = parseFloat(document.getElementById("wednesdayHours").value) || 0;
var thursdayHours = parseFloat(document.getElementById("thursdayHours").value ) || 0;
var fridayHours = parseFloat(document.getElementById("fridayHours").value) || 0;
var saturdayHours = parseFloat(document.getElementById("saturdayHours").value ) || 0;
var sundayHours = parseFloat(document.getElementById("sundayHours").value) || 0;
var totalHours = mondayHours + tuesdayHours + wednesdayHours + thursdayHours + fridayHours + saturdayHours + sundayHours;
alert(totalHours)
}
When you see parseFloat(...) || 0, this tell : ok if an input is empty, i will set the 0 value for this input.
You are grabbing the values on page load and storing those in variables. Since at that time, they are valueless, you aren't getting your expected result. I would recommend the following option...
var mondayHours = document.getElementById("mondayHours");
var tuesdayHours = document.getElementById("tuesdayHours");
var wednesdayHours = document.getElementById("wednesdayHours");
var thursdayHours = document.getElementById("thursdayHours");
var fridayHours = document.getElementById("fridayHours");
var saturdayHours = document.getElementById("saturdayHours");
var sundayHours = document.getElementById("sundayHours");
function alertHours() {
var totalHours = mondayHours.value + tuesdayHours.value + wednesdayHours.value + thursdayHours.value + fridayHours.value + saturdayHours.value + sundayHours.value;
alert(totalHours);
}
This way you are getting the values of the inputs at the time the function is invoked, and not the time that the page was loaded. And scoping the getElementById outside of the alertHours function still gives you access to those elements should you need to use them somewhere else in code. There are more clever/eloquent ways to do this still, but this should work.
I have a Paypal form which has been built using some borrowed code. The main purpose of the form is to add some optional extras to a standard product and send that data to the paypal checkout. It seems to be working quite well, but...
I have a text field that I want to be required when the related checkbox is checked and for it to be disabled, and therefore not required when its unchecked.
Crucially I need the data in the text field to be sent to the paypal shopping basket.
I have validation on another text field which will always be required, that works and sends the data to Paypal, but I'm a javascript newbie and can't get to grips with the second field.
This is the borrowed javascript
function Dollar (val) { // force to valid dollar 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;
}
var amt,des,obj,val,op1a,op1b,op2a,op2b,itmn;
function ChkTok (obj1) {
var j,tok,ary=new Array (); // where we parse
ary = val.split (" "); // break apart
for (j=0; j<ary.length; j++) { // look at all items
// first we do single character tokens...
if (ary[j].length < 2) continue;
tok = ary[j].substring (0,1); // first character
val = ary[j].substring (1); // get data
if (tok == "#") amt = val * 1.0;
if (tok == "+") amt = amt + val*1.0;
if (tok == "%") amt = amt + (amt * val/100.0);
if (tok == "#") { // record item number
if (obj1.item_number) obj1.item_number.value = val;
ary[j] = ""; // zap this array element
}
// Now we do 3-character tokens...
if (ary[j].length < 4) continue;
tok = ary[j].substring (0,3); // first 3 chars
val = ary[j].substring (3); // get data
if (tok == "s1=") { // value for shipping
if (obj1.shipping) obj1.shipping.value = val;
ary[j] = ""; // clear it out
}
if (tok == "s2=") { // value for shipping2
if (obj1.shipping2) obj1.shipping2.value = val;
ary[j] = ""; // clear it out
}
}
val = ary.join (" "); // rebuild val with what's left
}
function StorVal () {
var tag;
tag = obj.name.substring (obj.name.length-2); // get flag
if (tag == "1a") op1a = op1a + " " + val;
else if (tag == "1b") op1b = op1b + " " + val;
else if (tag == "2a") op2a = op2a + " " + val;
else if (tag == "2b") op2b = op2b + " " + val;
else if (tag == "3i") itmn = itmn + " " + val;
else if (des.length == 0) des = val;
else des = des + ", " + val;
}
function ReadForm (obj1, tst) { // Read the user form
var i,j,pos;
amt=0;des="";op1a="";op1b="";op2a="";op2b="";itmn="";
if (obj1.baseamt) amt = obj1.baseamt.value*1.0; // base amount
if (obj1.basedes) des = obj1.basedes.value; // base description
if (obj1.baseon0) op1a = obj1.baseon0.value; // base options
if (obj1.baseos0) op1b = obj1.baseos0.value;
if (obj1.baseon1) op2a = obj1.baseon1.value;
if (obj1.baseos1) op2b = obj1.baseos1.value;
if (obj1.baseitn) itmn = obj1.baseitn.value;
for (i=0; i<obj1.length; i++) { // run entire form
obj = obj1.elements[i]; // a form element
if (obj.type == "select-one") { // just selects
if (obj.name == "quantity" ||
obj.name == "amount") continue;
pos = obj.selectedIndex; // which option selected
val = obj.options[pos].value; // selected value
ChkTok (obj1); // check for any specials
if (obj.name == "on0" || // let this go where it wants
obj.name == "os0" ||
obj.name == "on1" ||
obj.name == "os1") continue;
StorVal ();
} else
if (obj.type == "checkbox" || // just get checkboxex
obj.type == "radio") { // and radios
if (obj.checked) {
val = obj.value; // the value of the selection
ChkTok (obj1);
StorVal ();
}
} else
if (obj.type == "select-multiple") { //one or more
for (j=0; j<obj.options.length; j++) { // run all options
if (obj.options[j].selected) {
val = obj.options[j].value; // selected value (default)
ChkTok (obj1);
StorVal ();
}
}
} else
if (obj.name == "size") {
val = obj.value; // get the data
if (val == "" && tst) { // force an entry
alert ("Enter data for " + obj.name);
return false;
}
StorVal ();
} else
if (obj.name == "stamp") {
val = obj.value; // get the data
//if (val == "" && tst) { // force an entry
// alert ("Enter data for " + obj.name);
// return false;
//}
StorVal ();
}
}
// Now summarize stuff we just processed, above
if (op1a.length > 0) obj1.on0.value = op1a;
if (op1b.length > 0) obj1.os0.value = op1b;
if (op2a.length > 0) obj1.on1.value = op2a;
if (op2b.length > 0) obj1.os1.value = op2b;
if (itmn.length > 0) obj1.item_number.value = itmn;
obj1.item_name.value = des;
obj1.amount.value = Dollar (amt);
if (obj1.tot) obj1.tot.value = "£" + Dollar (amt);
}
and this is the html
<form action="https://www.paypal.com/cgi-bin/webscr" name="weboptions" method="post" onsubmit="this.target='_blank'; return ReadForm(this, true);">
<input type="hidden" name="cmd" value="_cart" />
<input type="hidden" name="add" value="1" />
<input type="hidden" name="business" value="craig#craigomatic.co.uk" />
<input type="hidden" name="shipping" value="0.00">
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="return" value="">
<input type="hidden" name="item_name" value />
<input type="hidden" name="amount" value />
<input type="hidden" name="currency_code" value="GBP" />
<input type="hidden" name="lc" value="US" />
<input type="hidden" name="bn" value="PP-ShopCartBF">
<input type="hidden" name="basedes" value="Collar">
<h4>Collar details...</h4>
<div>
<p>Matching lamb nappa lining <br />
with antique brass finished hardware</p>
<div>
<p>Pick a colour:</p>
<p>Chose a width:</p>
<p>Tell us the Size:<br />
in cms (?)</p>
</div>
<div>
<p>
<select name="colour" onclick="ReadForm (this.form, false);" size="1">
<option value="Black +55.00">Black</option>
<option value="Brown +55.00">Brown</option>
<option value="Tan +55.00">Tan</option>
</select>
</p>
<p>
<select name="width" onclick="ReadForm (this.form, false);" size="1">
<option value="1 and quarter inch">1¼ inch</option>
<option value="1 and half inch">1½ inch</option>
</select>
</p>
<p><input name="size" type="text" class="size"></p>
<p></p>
</div>
</div>
<h4>Optional extras...</h4>
<div>
<p>
<label>
<input type ="checkbox" onclick="ReadForm (this.form, false);"
value ="Double D +1.50"
name ="DoubleD">
Double D Me (£1.50)
</label>
</p>
<p>
<label>
<input type ="checkbox" onclick="ReadForm (this.form, false);"
value ="Max Me +1.50"
name ="MaxMe">
Max Me! (£1.50)
</label>
</p>
<p>
<label>
<input type ="checkbox" onclick="ReadForm (this.form, false);"
value ="Match Me +1.50"
name ="MatchMe">
Match Me (£1.50)
</label>
</p>
<p>
<label>
<input type ="checkbox" onclick="ReadForm (this.form, false);"
value ="Stamp Me +1.50"
name ="StampMe">
Stamp Me (£1.50)</label>
</p>
<p><input name="stamp" type="text" class="lettering" maxlength="12"></p>
</div>
<p>Total:<input class="nbor" type="text" name="tot" size="7" value="£55.00" /> <input class="buy" type="submit" value="Buy Me" name="B1"></p>
</form>
If your wondering you can find the page in question here http://booleather.co.uk/option1/bronze-bronco.php
Any help would be much appreciated.
Give this code a try:
if (val == "" && obj1.elements["StampMe"].checked) {
// if the value of the stamp text field is empty and the user has checked the StampMe box
alert ("Enter data for " + obj.name);
return false;
}
(instead of)
//if (val == "" && tst) { // force an entry
// alert ("Enter data for " + obj.name);
// return false;
//}