use*_*203 7 jquery html-select
我有一个简单的选择菜单,例如
<p>Would you recommend this company?</p>
<select>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
Run Code Online (Sandbox Code Playgroud)
我要求用户反馈,它目前通过一个简单的表单提交功能,现在它是2013年我喜欢使它成为2个按钮,例如"Thumbs Up"或"Thumbs Down"(选择时突出显示)/ interchangable(例如can一次选择2).
到目前为止......但它并没有真正应用选择值或"选定"效果:
我最接近的是以下...将选择的菜单转换为星级评级... - 但它并不是真正可用的,所以希望有人可以帮助/指向正确的方向或一些代码示例.
更新:
为所选值的表单提交添加了隐藏元素.
这是您希望实现的简单实现.
演示:http://jsfiddle.net/mBUgc/19/
JavaScript:
$("select option").unwrap().each(function() {
var btn = $('<div class="btn">'+$(this).text()+'</div>');
if($(this).is(':checked')) btn.addClass('on');
$(this).replaceWith(btn);
});
$(document).on('click', '.btn', function() {
$('.btn').removeClass('on');
$(this).addClass('on');
});
Run Code Online (Sandbox Code Playgroud)
CSS:
div.btn {
display: inline-block;
/** other styles **/
}
div.btn.on {
background-color: #777;
color: white;
/** styles as needed for on state **/
}
Run Code Online (Sandbox Code Playgroud)
注意:无论您在选择中使用多少选项,这都将有效 - http://jsfiddle.net/mBUgc/20/
如果有人回到这个问题,我根据@techfoobar 的示例提出了一个略有不同的解决方案。
基本上: - 动态代码(可用于同一页面上的多个选择) - 不需要隐藏字段,选择仍然存在(隐藏)
测试: - 当前的 chrome、firefox、edge(铬)、ie11
用法:
jQuery(document).ready(function($) {
ReplaceSelectWithButtons($('#test'));
});
Run Code Online (Sandbox Code Playgroud)
https://jsfiddle.net/koshimon/pobcvxf4/2/
// 是的,这是我在这里的第一篇文章,欢迎反馈:)
小智 5
不过你不需要 jQuery 来做这件事。对此有一个非常简单的解决方案。
此代码片段仅使用输入和标签标签,其中我们隐藏单选按钮圆圈并使用按钮代替
<input type="radio" name="name_name" id="id_name" value="1" style="visibility: hidden;">
<label class="btn btn-primary" for="id_name">1</label>
<input type="radio" name="name_name" id="id_name2" value="2" style="visibility: hidden;">
<label class="btn btn-primary" for="id_name2">2</label>
Run Code Online (Sandbox Code Playgroud)
<input type="radio" name="name_name" id="id_name" value="1" style="visibility: hidden;">
<label class="btn btn-primary" for="id_name">1</label>
<input type="radio" name="name_name" id="id_name2" value="2" style="visibility: hidden;">
<label class="btn btn-primary" for="id_name2">2</label>
Run Code Online (Sandbox Code Playgroud)
input[type=radio]:checked + label {
font-style: normal;
color: rgb(56,110,246);
border: 1px solid rgb(56,110,246);
background-color: rgb(226,233,253)
}Run Code Online (Sandbox Code Playgroud)