Reputation: 819
My problem is: I have two input boxes one for a code and one for a price:
<input class="style" name="code" id="code" type="text">
<input class="style" name="price" id= "price" type="text" value="€ 15,00" readonly="readonly">
Now i want to change the price by code (like a check from a code array [code1][code2]. result to code1 = price/2 and code2 = price/4 ) This i want to check by a script in real time or befor the post (on submit). This this possible when yes how? Or is there another better way to do this ?
I have:
while(true)
{
var code = document.getElementById("code").value;
var codes = new Array("promo1", "promo2");
for (var i=0; i<codes.length; i++) {
if (codes[i] == code) {
document.getElementById("price").value = "5";
}
}
}
and my input fields are obviously in a form-field but the value doesnt change, but why ? I dont have to change in real time it would be ok if the post sends the new value...any solutions/better ideas/hints ? I know there is JQuery a better approach but it shouldn't be a problem with js.
fiddle link:
jsfiddle.net/vicR/4Mtbr
Upvotes: 1
Views: 11293
Reputation: 222
This can be obtained easily in many ways, specially if one takes use of libraries or frameworks, but with pure javascript it should be done as so:
while(true) {
var code = document.getElementById("code").value
//now check for valid code in some sort of map or array
//REMEMBER javascript supports string indexed arrays such as arr["#45"]
if(code == validatorFunctionOrCode) { //obviously pseudo
document.getElementById("price").value = "your corresponding price to the code"
}
}
With this said I would strongly recommend Angular.js since it supports databinding (example - databinding )
Upvotes: 2
Reputation: 1191
It is done with some jQuery code:
$('#form').submit(function() {
$('#price').val(value_you_want_to_change);
});
Upvotes: 1