获取单选按钮值并触发单击

时间:2016-04-12 07:18:06

标签: javascript jquery html

我有 2个单选按钮,有两个不同的值和一个按钮。单选按钮例如,值2 ,一个值4

这是我的单选按钮:

<input type="radio" value="2" name="match[rounds]" id="match_rounds_2">
<input type="radio" value="4" name="match[rounds]" id="match_rounds_4">

这是我的按钮:

<a id="clickme">Click me</a>

我要找的是“选择”单选按钮值,并根据所选的单选按钮/值触发点击。

如果用户选择值为2 的单选按钮,则触发 1单击,如果选择,单击值4 的单选按钮,则触发 2次点击

3 个答案:

答案 0 :(得分:1)

您可以通过编写以下代码来完成。

$('#clickme').on('click', function(){
 var v =  $('input[name=match[rounds]]:checked').val();
})

答案 1 :(得分:0)

&#13;
&#13;
// get some dom elements
var $radios = document.getElementsByName('match[rounds]');
var $button = document.querySelector('#clickme');
var $log = document.querySelector('#log');

// dispatch event by name on element
var dispatch_event = function(el, eventName){
  el.dispatchEvent(new Event(eventName));
}

// debugging: add some logs to show exact clicks
var add_log = function(root, log_string){
  var $new_log = document.createElement('li');
  $new_log.textContent = log_string;
  root.appendChild($new_log);
};
                             
// iterate over all $radios elements
[].forEach.call($radios, function(el) {
    
    // bind event
    el.onchange = function(event){
      
      // get value
      var value = event.target.value;

      // value is the radio.value property, 
      // when 2, t trigger 1 click
      if(value == 2){
        
        // trigger event 1 time
        dispatch_event($button, 'click');
      } else if (value == 4) {
        
        // 2 times
        dispatch_event($button, 'click');
        dispatch_event($button, 'click');
      }
    }
});

// the button that must be clicked
// for demo, we just log it
// YOU HAVE TO MAKE YOUR OWN LOGIC HERE
$button.onclick = function(){
  add_log($log, 'clicked');
}
&#13;
<input type="radio" value="2" name="match[rounds]" id="match_rounds_2">
<input type="radio" value="4" name="match[rounds]" id="match_rounds_4">

<a id="clickme">Click me</a>

<ul id="log"></ul>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

嗨请仔细检查https://jsfiddle.net/n2njbt9b/我希望这是你想要的......

<强>的jQuery

$(document).ready(function(){
    $('#match_rounds_2,#match_rounds_4 ').on('change', function(){
    if($('#match_rounds_2').is(':checked'))
    {
        $('#clickme').trigger('click');
    }
    if($('#match_rounds_4').is(':checked'))
    {
        $('#clickme').trigger('dblclick');
    }
  });

  $('#clickme').on('click', function(){
    alert ('clicked'); // Click logic
  });

  $('#clickme').on('dblclick', function(){
    alert ('double clicked'); // Double Click logic
  });
});