简体   繁体   中英

Assigning number to .find(type) in Jquery

I have a function that allows me to select a random radio button and click on it. But on different pages I have different .find(type). Example:

Page1.html: controlTypeToIterateOn='label'
Page2.html: controlTypeToIterateOn=':radio'

//Radio button
function randomNumberGenerator(max, min) {
  var randomNumber = Math.floor(Math.random() * (max - min + 1) + min);
  return randomNumber;
}

function SelectRandonRadioButton(radioButtonContainer, controlTypeToIterateOn) { //Genereal function    
  var radios = $(radioButtonContainer).find(controlTypeToIterateOn);
  if (controlTypeToIterateOn == ':radio')
    controlTypeToIterateOn = 1;
  else if (controlTypeToIterateOn == 'label')
    controlTypeToIterateOn = 0;

  var randomnumber = randomNumberGenerator(radios.length - 1, 0);
  //randomizing number
  $(radios[randomnumber]).click();
  return $(radios[randomnumber]);

}

function SelectLiveRandomRadioButton(radioButtonContainer, controlTypeToIterateOn) {
  var elem = SelectRandonRadioButton(radioButtonContainer, controlTypeToIterateOn);
  $(elem).mousedown();
}

function call() {
  $(".YesNoRadio").each(function() {
    SelectLiveRandomRadioButton($(this), 1);
  });
}

call();

My if condition that checks the input type does not seem to work. I want to assign a numeric value that I can pass in my SelectLiveRandomRadioButton() function that's inside the call function. For example if I pass '0' ,my controlTypeToIterateOn = 'label' , if I pass 1 , my controlTypeToIterateOn = ':radio' . Anyone who can help me with this? Thanks.

I am not sure what you are trying to do, but from looking at your code, I guess you might want to do something like this:

function SelectRandonRadioButton(radioButtonContainer, controlTypeToIterateOn) {
  var toFind;
  if (controlTypeToIterateOn === 1) {
    toFind = ':radio';
  } else if (controlTypeToIterateOn === 0) {
    toFind = 'label';
  }
  var hits = $(radioButtonContainer).find(toFind);
  var randomnumber = randomNumberGenerator(hits.length - 1, 0);
  $(hits[randomnumber]).click();
  return $(hits[randomnumber]);
}


function call() {
  $(".YesNoRadio").each(function() {
    // where 1 would find radio, and 0 label
    SelectLiveRandomRadioButton($(this), 1);
  });
}

call();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM