简体   繁体   English

检测选中的单选按钮并触发点击

[英]Detect checked radio button and trigger click

I have a set of 4 radio buttons, which when clicked show/hide divs on my page. 我有一组4个单选按钮,当单击页面上的show / hide divs时,这些按钮就会显示。

On unsuccessful validation of my form I return the user back to the form with last clicked radio button checked. 在我的表单验证失败时,我使用户返回到选中了最后单击的单选按钮的表单。

The issue I have is it does not show/hide the divs as in this instance the radio button isnt being clicked. 我的问题是它不会显示/隐藏div,因为在这种情况下,没有单击单选按钮。

What I want to be able to do is on page load detect which radio button is checked and then fire a click event. 我想要做的是在页面加载中检测选中了哪个单选按钮,然后触发click事件。 (ie simulate someone clicking that radio button) so that it then shows/hides my divs. (即模拟某人单击该单选按钮),以便随后显示/隐藏我的div。

My code to show hide looks like this 我显示隐藏的代码如下所示

$('#showduo').click(function(){
$('div[id^=div]').hide();
$('#div1').show();

html: 的HTML:

<input type="radio" name="type" value="Single" id="hideall" <?php echo set_radio('type', 'Single', TRUE); ?> />
<input type="radio" name="type" value="Singleplus" id="showsingleplus" <?php echo set_radio('type', 'Singleplus'); ?> />
<input type="radio" name="type" value="Duo" id="showduo" <?php echo set_radio('type', 'Duo'); ?> />
<input type="radio" name="type" value="Family" id="showfamily" <?php echo set_radio('type', 'Family'); ?> />

<div id="div1" style="display:none;">

If you call .click() without any parameters on the selected radio button it will execute the click handler for that button, just as if the user clicked on it. 如果在选定的单选按钮上调用没有任何参数的.click() ,它将执行该按钮的单击处理程序,就像用户单击它一样。

Try: 尝试:

$('input:radio[name=xxx]:checked').click();

Of course, you have to change "xxx" to the name you gave the radio buttons. 当然,您必须将“ xxx”更改为单选按钮的名称。

Note: I feel compelled to say that I wouldn't have it so each radio button has its own handler. 注意:我不得不说我不会,所以每个单选按钮都有自己的处理程序。 That means you have to add JavaScript if you want to add another radio button. 这意味着如果要添加另一个单选按钮,则必须添加JavaScript。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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