1

I created a radio button where the user can select either Metric or Imperial units. The following code is the event handler:

var metricRadio = document.getElementById("metric");
var imperialRadio = document.getElementById("imperial");

metricRadio.addEventListener("click", toMetric, false);

imperialRadio.addEventListener("click", toImperial, false);

When the user clicks the Metric radio button the function toMetric is called. In the function toMetric I convert what the user entered in Imperial to Metric and I update the input boxes with the Metric values. The problem is that if Metric is selected and he clicks the Metric radio button again the function toMetric is called again. How can I prevent calling the toMetric function when the Metric radio button is selected.

You can test what I mean here: JSFiddle

Just enter 3 values and click the Metric or Imperial radio button more than once.

2
  • You want to disable the metric handler when you are displaying metric and disable the imperial handler when you are displaying metric? Commented Mar 10, 2014 at 22:56
  • Yes that's what I'm trying to do. Commented Mar 10, 2014 at 22:59

2 Answers 2

5

Look at this: jsFiddle.

I used "change" instead of "click":

metricRadio.addEventListener("change", toMetric, false);

imperialRadio.addEventListener("change", toImperial, false);
Sign up to request clarification or add additional context in comments.

1 Comment

An alternative is to have a single handler for the div above it and detect which one is active. jsfiddle.net/mendesjuan/aYxph/2
1

Instead of trying to call a function only once (which you can do setting a variable), you should add a variable containing the current state (metric or imperial) and in your function you test the current state with an if condition

3 Comments

Here's an implementation of what you are suggesting jsfiddle.net/mendesjuan/43xqq/3 However, Siva's idea seems to be the best choice because you don't have to track state yourself
In fact you don't need to add a variable, you can check the status of the checkbox. See update : jsfiddle.net/43xqq/5
That doesn't work because the checked state already changed by the time your handler is called (I tried that too) Try clicking metric multiple times

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.