Need to change onClick value of a button to another value using select
I am a little lost at this point in my project. I work for a company that provides translation services. Well, I am making a simple calculator to calculate the cost of a translation based on the number of words in the entire project. It also changes rate based on the amount of words entered. I have that part done. I wrote this and it works:
function wordcountprice开发者_开发技巧(){
var price, final,
a=document.getElementById('words'),
wc= parseFloat(a.value) || 0;
if(wc< 10000) price= .29;
else price= wc<20000? .26: .24;
final= (wc*price).toFixed(2);
document.getElementById('estPrice').innerHTML = 'Your estimated price is: $' + final;}
At this point we have 6 types of translation work. Five of them would use that function and the last one would use a basic function with a fixed price. I was thinking I would use a drop down select box to change functions.
I am calling the above function in my HTML like this:
<input type="text" id="words"> <input type="button" id="button" value="Calculate" onClick="wordcountprice();"> <br /><b id='estPrice'>Estimated Price</b>
I have tried several things and none of them have worked. I assume that the best way to go about this is jQuery's change() or select() function. I have tried making a new function with jQuery like this one:
$(function() {
$('#type').change(function() {
var type = $(this).val();
$('#button').val(type);
}); });
That only changes the value of the button and not the onClick event. I do not know how, or if, it is possible to change the onClick event like that. I don't even know if that is the most efficient method to do what I want to do. I called that function when I was trying it with this HTML:
<select id='type'><option value='1'>A</option>
<option value='2'>B</option>
<option value='3'>C</option>
<option value='4'>D</option></select>
I am a noob with jQuery and haven't been programming for a while so I am a little rusty.
Thanks for the help in advance.
I think you want to do something like this:
$('#button').attr("onClick", "wordcountprice('"+type+"');" );
http://api.jquery.com/attr/
There are a couple options.
You could bind a function to the button's click event:
$('#button').click(myFunction)
and either have myFunction check the value of$('#type')
or keep track of type internally in the javascript when it changes. Then you can act conditionally within myFunction based on type to get the reaction you wantYou can bind a function to the button for the intial type, then in the change handler, first call
$('#button').unbind('click')
, and then bind a new event (again,$('#button').click(myNewFunction)
where myNewFunction is chosen based upon type
精彩评论