I am in need to generate 1 random letter into 7 form fields. An example of the fields would look like below.
The letters can repeat, but only based on the letter and an amount of times that letter can repeat
For instance
a x 7 (a can repeat only 7 times)
b x 5 (b can repeat only 5 times)
c x 2 (c can repeat only 2 times)
and so on
<input type="text" name="1" maxlength="1" />
<input type="text" name="2" maxlength="1" />
<input type="text" name="3" maxlength="1" />
<input type="text" name="4" maxlength="1" />
<input type="text" name="5" maxlength="1" />
<input type="text" name="6" maxlength="1" />
<input type="text" name="7" maxlength="1" />
So far I have
<script language="javascript" type="text/javascript">
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
var string_length = 1;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
document.randform.randomfield.value = randomstring;
}
</script>
Im a little lost because this will only place it in one field. I am not sure how to optimize my javascript so that it can generate all the letters (1 into each field) AND make sure the letters dont repeat beyond what they are allowed too.
Any ideas?
document.randform.randomfield.value = randomstring;
randomfield is not specified in the block you give. I suspect that either it's interpreted as 0, in which case you might get the first field. Or you might initialize it to a particular field in a section of code you didn't provide. Or (most likely, from my limited knowledge of JavaScript) it's really the name of a field that isn't shown in your HTML snippet.
Regardless, this is likely where your error is. You need to change the location where you want to save the value if you want to save the value to multiple locations.
Related
I'm making a simple html where i make calculations based on different inputs and presenting the results in other inputs using pure js.
In the below example where i divide a / b input and return the result in c,lets say you put 633 / 33 it returns a number like this : 19.181818181818183
Is there a way to make look like 19.18 ?
Using the maxlength Attribute to the result input wont work as it limits the number of characters you can type in,not the number of characters you can send to.
<input type="text" id="input1" style="width: 100px " onkeyup='divide_numbers()'/>
<label> / </label>
<input type="text" id="input2" style="width: 100px " onkeyup='divide_numbers()'/>
<label> = </label>
<input type="text" id="result" style="width: 100px "/>
<script>
function divide_numbers() {
var first_number = parseFloat(document.getElementById("input1").value) ;
var second_number = parseFloat(document.getElementById("input2").value) ;
document.getElementById("result").value=first_number/second_number ;
}
</script>
You can use +number.toFixed(2), which will first create a string with two digits after the decimal point and then coerce it back to a number, removing unnecessary decimal digits.
function add_numbers() {
var first_number = parseFloat(document.getElementById("input1").value) ;
var second_number = parseFloat(document.getElementById("input2").value) ;
document.getElementById("result").value = +(first_number/second_number).toFixed(2);
}
<input type="text" id="input1" style="width: 100px " onkeyup='add_numbers()'/>
<label> / </label>
<input type="text" id="input2" style="width: 100px " onkeyup='add_numbers()'/>
<label> = </label>
<input type="text" id="result" style="width: 100px "/>
I have 2 set of input types of text boxes. 2 fields on each. I am trying to calculate and compare each set individually in single page.
The input types have different ids.
<input type="text" id="tmcp_textfield_1" name="blueberry"
placeholder="blueberry" value="0" onkeydown="calculate()"
onkeyup="calculate()">
<input type="text" id="tmcp_textfield_2" name="plums" placeholder="plums" value="0"
onkeydown="calculate()" onkeyup="calculate()">
<input type="text" id="a3" name="a3" placeholder="a3" value="0">
<br>second set below<br>
<input type="text" id="tmcp_textfield_3" name="blueberry"
placeholder="blueberry" value="0" onkeydown="calculate()"
onkeyup="calculate()">
<input type="text" id="tmcp_textfield_4" name="plums" placeholder="plums" value="0"
onkeydown="calculate()" onkeyup="calculate()">
<input type="text" id="a3`" name="a3" placeholder="a3" value="0">
My javascript in header:
For First set:
<script type="text/javascript">
calculate = function() {
var blueb = parseFloat($('#tmcp_textfield_1').val());//document.getElementById('blueberry').value;
var plumsb = parseFloat($('#tmcp_textfield_2').val());//document.getElementById('plums').value;
var thetotal = /*document.getElementById('a3').value =*/ parseInt(blueb)+parseInt(plumsb);
if (thetotal > 6) {
$('#tmcp_textfield_2').val('');
$('#tmcp_textfield_1').val('');
alert('Combination must be below 6');
}
}
</script>
For Second Set:
<script type="text/javascript">
calculate = function() {
var blueb = parseFloat($('#tmcp_textfield_3').val());//document.getElementById('blueberry').value;
var plumsb = parseFloat($('#tmcp_textfield_4').val());//document.getElementById('plums').value;
var thetotal = /*document.getElementById('a3').value =*/ parseInt(blueb)+parseInt(plumsb);
if (thetotal > 12){
$('#tmcp_textfield_4').val('');
$('#tmcp_textfield_3').val('');
alert('Combination must be below 12');
}
}
</script>
The problem only the first set of calculation work. When i remove the first set of javascript then the second set only work and vise versa.
How could i differentiate the sets in javascript so that both the set of inputs work together in one single html page.
Problem:
You are having same name functions "calculate()" for both sets that's why only 1 is working at a time.
Solution:
Rename the function name to different names like calculateOne() and calculateTwo() then both will work.
Hope this helps
So we have here my code for a GPA calculator. Ive got everything in line but I cant seem to figure out why my IF ELSE statement is stopping short and converting all letter grades to a value of "4".
I have tried putting the statement outside of the for loop that is handling the grades and pushing them to to gVals[] I have tried putting them completely outside of the function in their own function. I have tried alot of different things except apparently the thing that works.
I know there are simple ways of doing this but I am trying to execute this app with a minimalist mentality.
The code:
function calcGPA() {
//Variable Sections
var grades = document.querySelectorAll("#letGrade input[type=text]");
var contacts = document.querySelectorAll("#conHours input[type=text]");
var gVals = [];
var cVals = [];
var failGrade = "The Letter Grade input may only be capitol letters A,B,C,D or F";
var failHours = "The Contact Hours input may only be 1, 2, 3, 4 or 5";
var checkGrade = /^[ABCDF]/;
var checkhours = /^[12345]/;
//Grab the Letter grades and process them
//Should validate all inputs in the letGrade div to capitol A, B, C, D or F
//Should Convert all inputs in the LetGrade div to A = 4,B = 3,C = 2,D = 1,F = 0
//Should push resulting conversion to gVals[]
for (var i = 0; i < grades.length; i++) {
if (!checkGrade.test(grades[i].value)) {
alert(failGrade);
return false;
}
if (grades[i].value == "A"){
gVals.push("4");
}
else if (grades[i].value == "B"){
gVals.push("3");
}
else if (grades[i].value == "C"){
gVals.push("2");
}
else if (grades[i].value == "D"){
gVals.push("1");
}
else if (grades[i].value == "F"){
gVals.push("0");
}
//Should validate all inputs in the conHours div to 1, 2, 3, 4 or 5
//Should push all resulting values to cVals[]
if (!checkhours.test(contacts[i].value)) {
alert(failHours);
return false;
}
cVals.push(contacts[i].value);
}
console.log(gVals, cVals);
document.getElementById("cumGPA").innerHTML = (gVals[0] * cVals[0]);
};
The issue I am having is that the IF ELSE statement to do the conversion from letter grade to quality point value is returning everything back as 4 instead of matching it with its resulting letter grade componant.
Thank you for any help with this in advanced and please if you could dont answer the question outright please explain where I went wrong so I can learn from this.
EDIT: ADDED HTML FOR PROSPERITY! AND "FIXED" JAVASCRIPT!
<div id="calcWrapper">
<form id="calc" name="calc" onsubmit="calcGPA(); return false;">
<div id="letGrade">
<input tabindex="1" type="text" maxlength="1" placeholder="Letter Grade..." />
<input tabindex="3" type="text" maxlength="1" placeholder="Letter Grade..." />
<input tabindex="5" type="text" maxlength="1" placeholder="Letter Grade..." />
<input tabindex="7" type="text" maxlength="1" placeholder="Letter Grade..." />
<input tabindex="9" type="text" maxlength="1" placeholder="Letter Grade..." />
<input tabindex="11" type="text" maxlength="1" placeholder="Letter Grade..." />
<label>Cumulative GPA:</label><output id="cumGPA" type="text" />
</div>
<div id="conHours">
<input tabindex="2" type="text" maxlength="1" placeholder="Contact Hours..." />
<input tabindex="4" type="text" maxlength="1" placeholder="Contact Hours..." />
<input tabindex="6" type="text" maxlength="1" placeholder="Contact Hours..." />
<input tabindex="8" type="text" maxlength="1" placeholder="Contact Hours..." />
<input tabindex="10" type="text" maxlength="1" placeholder="Contact Hours..." />
<input tabindex="12" type="text" maxlength="1" placeholder="Contact Hours..." />
<input type="submit" value="Calculate" />
</div>
</form>
</div>
The reason why it's not working is because in your if statement, you're using a single equals. A single equals is setting grades[i] equal to 'A' - it's not actually evaluating grades[i] == 'A'.
You want to change single = to == for comparison
if (grades[i] == 'A'){
Something like this in your code:
if (grades[i] == 'A'){
gVals.push("4");
}
else if (grades[i] == 'B'){
gVals.push("3");
}
else if (grades[i] == 'C'){
gVals.push("2");
}
else if (grades[i] == 'D'){
gVals.push("1");
}
else if (grades[i] == 'F'){
gVals.push("0");
}
Note:-
Double equality == is used for comparison and single = is used for assignment in Javascript.
Also as Andy well pointed that in comments that your both the for loops are using the same index i which may cause problem to you(atleast not a good practice). It would be better if you create a new variable for second for loop. It is unclear what you want to achieve with both the for loops but I think that it can be done with single for loop also.
As it was pointed in other answers you should use comparison operator == instead of assign operator = in if conditions, and also don't forget that grades[i] are DOM objects and not some plain values - so you have to compare with some property of this objects (if you want to compare with input's text use value property)
if (grades[i].value == "A"){
gVals.push("4");
}
else if (grades[i].value == "B"){
gVals.push("3");
}
I've built a script to add quantities/units and generate a total that displays sales tax.
How can I get this calculator to recognise #discount and subtract it from the total before the GST (10% sales tax) is calculated and added?
Also, is it possible to generate the total when the page loads? Instead of a user having to press the 'Generate total' button?
HTML
<ul>
<li> Item 1 (<input type="text" name="others" size="4" value="5" readonly="readonly" class="readonly_field"/> units)</li>
<li> Item 2 (<input type="text" name="others" size="4" value="1" readonly="readonly" class="readonly_field"/> units)</li>
<li> Item 3 (<input type="text" name="others" size="4" value="3" readonly="readonly" class="readonly_field"/> units)</li>
</ul>
<input type="button" value="Generate Total" onclick="total()" /><br><br>
Discount <input type="text" id="discount" name="discount" value="500"/><br><br>
Total Units: <input type="text" id="units_total" name="units_total" readonly="readonly" /><br>
Sub Total: <input type="text" id="sub_total" name="sub_total" readonly="readonly" /><br>
Includes GST: <input type="text" id="gst_total" name="gst_total" readonly="readonly" /><br>
Total: <input type="text" id="g_total" name="g_total" readonly="readonly" />
JS
function total(){
var total_value = 0;
var all_others = document.getElementsByTagName("input");
for(var i=0; i<all_others.length; i++){
if(all_others[i].type!="text" || all_others[i].name!="others"){
continue;
}
total_value += parseFloat(all_others[i].value);
}
document.getElementById("units_total").value = (total_value).toFixed(1);
document.getElementById("sub_total").value = ((total_value) *100).toFixed(2);
document.getElementById("g_total").value = (((total_value * 10/100) + total_value) * 100).toFixed(2);
document.getElementById("gst_total").value = ((total_value * 10/100) * 100).toFixed(2);
}
Firstly, to get your function to execute on window load, wrap it in a load event:
window.onload = function() {
total();
}
Secondly, to get it to figure in discount, you just need to modify your variable a few times, but then when adding them together, make sure you parse them with .parseFloat():
if (document.getElementById('discount').value != '') {
var discount = document.getElementById('discount').value;
}
else {
var discount = 0;
}
var sub_total = (((total_value) * 100).toFixed(2) - discount).toFixed(2);
var gst = ((total_value * 10 / 100) * 100).toFixed(2);
document.getElementById("sub_total").value = sub_total;
document.getElementById("gst_total").value = gst;
document.getElementById("g_total").value = (parseFloat(sub_total) + parseFloat(gst)).toFixed(2);
DEMO
First of all, I suggest you to perform validation and computations both server side and client side. The first ensures security while the second improves the responsiveness of the UI.
Said that, you'd better introduce several support variables and perform computation on them. You should get the value from the elements you are interested into using getElementById and store it in variables.
Then you should perform computation on that variables and finally place the results in the elements you want to use to display them to the user.
To perform the operation when the page loads have a look at this.
Hi and thanks for looking.
I need to get all form inputs from a form using javascript, the inputs are named like so:
<input name="site[1]" type="text" size="3" id="sitesinput" value="0" />
<input name="site[2]" type="text" size="3" id="sitesinput" value="0" />
<input name="site[3]" type="text" size="3" id="sitesinput" value="0" />
<input name="site[4]" type="text" size="3" id="sitesinput" value="0" />
......
<input name="site[10]" type="text" size="3" id="sitesinput" value="0" />
and I have the following to pick them up and adding the values togther, but it is not working, what am I doing wrong:
function site_change() {
var sites= document.getElementById('sitesinput').value;
var sum= 0;
var inputs= document.getElementById('inputsite').getElementsByTagName('input');
for (var i= inputs.length; i-->0;) {
if (inputs[i].getAttribute('name').match(/^site[\d+$]/))
{
var v= inputs[i].value.split(',').join('.').split(' ').join('');
if (isNaN(+v))
alert(inputs[i].value+' is not a readable number');
else
sum+= +v;
}
}
var phones= document.getElementById('phonesinput').value;
document.getElementById('siteresult').innerHTML = phones-sum;
};
Is the Match function wrong?
Thanks,
B.
Your regex is a little off (using [] blocks characters, but you actually want to find square brackets so they need to be escaped. And $ needs to be at the end). Try:
.match(/^site\[\d+\]$/)