Reputation: 9
I have an array having 2-3 titles. eg. 'Get 20% Off' , 'Receive 40% Savings' , 'Grab 10% discounts' etc. I would like to get the numeric value before '%' sign. and pass this numeric value into a html form as inputs. and in return the form would calculate a percentage amount. and display all the results.
Right now i have managed to make this work for a single title. but i am not able to get a array of titles.
my code is as follows -
//code for getting all the titles //putting it into an array called '$array'
foreach($array as $str) {
if(preg_match('/(\d+)\%/i' ,$str,$m)) {
echo $m[1],"\n"; ?>
<?php }
} ?>
//the above code extracts the amount before the percentage off sign. and the below code passes it as a input to the form (name=a). and other input (name=b) is coming from a different source. thats working fine. for calculation consider that input to be 100. I would need to calculate the percent value w.r.t 100. for eg- if input a is 5, then another input b is 100. the value to be outputted would be 5.
<form name="form1">
<input type="text" name="a" value="<?php echo $m[1]; ?>" size=5>
<input class="budget-sidebar" type="text" name="b" id="amount" size=5>
the below html is used for displaying the calculated value and submitting the form.
<input type="text" name="total1" value="ans1" size=5 maxlength=4>
<input type="button" value="Calculate" onClick="calc1(this.form)">
</form>
the below javascript function is responsible to take the inputs and calculate the value and displaying it.
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
function calc1(form) {
a = form.a.value/100;
b = a*form.b.value;
form.total1.value = b;
}
// End -->
</script>
i have posted a similar question requesting for different suggestions & this is supposed to be a different query. thanks.
Upvotes: 0
Views: 667
Reputation: 817
try to convert form value to integer before performing calculation
function calc1(form) {
a = parseInt(form.a.value, 10)/100;
b = a* parseInt(form.b.value, 10);
form.total1.value = b;
}
And you will have to round the value to avoid to get strange value
[Edit]:
And to get multi string some thing like this will may work (no test sorry)
// php
$values = array();
foreach($array as $str) {
if(preg_match('/(\d+)\%/i' ,$str,$m)) {
$values[] = $m[1];
}
}
// for html
<form name="form1">
<?php for($i = 0; $i < count($values); $i++) { ?>
<input type="text" name="a<?php echo $i ?>" value="<?php echo $values[i]; ?>" size=5>
<?php} ?>
<input class="budget-sidebar" type="text" name="b" id="amount" size=5>
// javascript
function calc1(form) {
var i = 0, a = 0;
while (form["a" + i]) {
a += parseInt(form["a" + i].value, 10);
i++;
}
b = a/100 * parseInt(form.b.value, 10);
form.total1.value = b;
}
Upvotes: 1