简体   繁体   English

选择单选按钮会更改标签文本,当选择新的单选按钮时,先前选择的单选按钮标签文本需要还原

[英]Selecting radio button changes label text, when selecting new radio button, previously selected radio button label text needs to revert

I'm creating a page where people can choose ingredients for a recipe. 我正在创建一个页面,人们可以在其中选择食谱的配料。

The page is split into 4 different kinds of ingredients, 2 of these ingredient groups you can only choose 1 ingredient of it's kind, so I thought it would make sense to use radio buttons rather than checkboxes, however the client wants the label to change from '+ Add to recipe' to '- Remove from recipe' when a radio input is selected. 该页面分为4种不同的成分,其中的2种成分只能选择一种成分,因此我认为使用单选按钮而不是复选框是有意义的,但是客户希望标签从选择单选输入时,“ +添加到配方”到“-从配方中删除”。 I can make that happen with the below code, but when they select something else in the group, the previously selected radio input label needs to revert to '+ Add to recipe'. 我可以使用以下代码来实现这一点,但是当他们在组中选择其他选项时,先前选择的单选输入标签需要还原为“ +添加到配方”。 That's what I'm struggling with. 那就是我所努力的。

Appreciate the help. 感谢帮助。

 $('input[name="s1-radio"]').on('change', function() { $(this).next().text(function(state, text){ return text === '+ Add to recipe' ? '- Remove from recipe' : '+ Add to recipe'; }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label class="rk_button_container"> <input type="radio" name="s1-radio" class="rk_button_input" value="11" data-variation-id="1" /> <span class="rk_button">+ Add to recipe</span> </label> <label class="rk_button_container"> <input type="radio" name="s1-radio" class="rk_button_input" value="13" data-variation-id="2" /> <span class="rk_button">+ Add to recipe</span> </label> <label class="rk_button_container"> <input type="radio" name="s1-radio" class="rk_button_input" value="9" data-variation-id="3" /> <span class="rk_button">+ Add to recipe</span> </label> 

Just change your jquery code to this: 只需将您的jquery代码更改为此:

$('input[name="s1-radio[]"]').on('change', function() {

$('.rk_button').text('- Remove from recipe' ? '+ Add to recipe' : '+ Add to recipe');
 $(this).next().text(function(state, text){
   return text === '+ Add to recipe' ? '- Remove from recipe' : '+ Add to recipe';
    });

});

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

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