You are viewing limited content. For full access, please sign in.

Question

Question

JavaScript assistance - run java if radio button is selected

asked on February 22, 2016

I am trying to run a specific javascript - only if a specific radio button is selected.

  • If radio button - Both is selected - Line 1 and Line 2 must equal

My java code is

$(document).ready(function() {
  $('#q3').click(function () {
  if($('input[value="BothA"]').is(':checked'))
  {$('.Submit').hide();
  $('.cat2 input').on('blur change', function() {
    if (parseInt($('.cat input').val(), 10) == parseInt($('.cat2 input').val(), 10)) {
      $('.Submit').show();
    } else {
      $('.Submit').hide();
      alert("Error in math - Total Hours does not match Split Hours");
    }
      });
     });
 

 

  • I confirmed that "Part One" of the code will work independently

 

$(document).ready(function() {

  $('#q3').click(function () {

  if($('input[value="BothA"]').is(':checked'))

  {

  alert("Error in math - Total Hours does not match Split Hours");

  }

      });

     });

 

  • I also confirmed that "Part Two" of the code will work

 

$(document).ready(function() {

  $('.Submit').hide();

  $(.cat2 input').on('blur change', function() {

    if (parseInt($('.cat input').val(), 10) == parseInt($('.cat2 input').val(), 10)) {

      $('.Submit').show();

    } else {

      $('.Submit').hide();

      alert("Error in math - Total Hours does not match Split Hours");

    }

  });

});

Any suggestions on how to combine these items would be appreciated.

0 0

Answer

SELECTED ANSWER
replied on February 23, 2016

Hi Angash,

You can combine the code by defining a function (i.e. "isEqual") and running it only when the "Both" button is checked. For example:

$(document).ready(function(){
  $('#q3, .cat input, .cat2 input').on('blur change', function(){
    if ($('input[value="Both"]').is(':checked')){
      isEqual();
    }else{$('.Submit').show();}
  });
  
  function isEqual(){
    if ($('.cat input').val() == $('.cat2 input').val()){
      $('.Submit').show();
    }else{
      $('.Submit').hide();
      alert ('Error in math - Total Hours does not match Split Hours');
    }
  }
});

Any time the radio button, Field1 or Field2 is changed/blurred, you run a check to see if "Both" is checked. If so, run the isEqual function, which checks if Field1 equals Field2. If not, show the submit button.

Let me know if this works for you!

0 0

Replies

replied on February 24, 2016

Hi Alexander, 

Thanks! That was very informative. Your suggested code is working perfectly.

1 0
You are not allowed to follow up in this post.

Sign in to reply to this post.