简体   繁体   English

onclick函数可通过切换将数据插入输入字段

[英]onclick function to insert data into input field with toggle

I would like to build two buttons with an onclick function that will insert "male" or "female" into another input. 我想用onclick函数构建两个按钮,该按钮会将“ male”或“ female”插入到另一个输入中。

The two buttons have background images and need to change background-position when clicked. 这两个按钮具有背景图像,单击时需要更改背景位置。 I need both buttons to toggle from each other. 我需要两个按钮相互切换。

Can anyone suggest a solution with javascript or jquery? 谁能建议使用javascript或jquery的解决方案?

<input type="button" class="gnM" onclick="???????">
<input type="button" class="gnF" onclick="???????">

<input class="req-string gender" id="gender" name="gender">

If you must do this with onclick then I'd suggest: 如果您必须使用onclick进行此操作,则建议:

<input type="button" class="gnM" onclick="$('#gender').val($(this).val())" value="male" />
<input type="button" class="gnM" onclick="$('#gender').val($(this).val())" value="female" />

JS Fiddle demo . JS小提琴演示

I'd strongly suggest moving from an onclick to a jQuery unobtrusive method, using the click() method: 我强烈建议您使用click()方法从onclick变为jQuery不引人注目的方法:

​$('.gnM').click(
    function(){
        var that = $(this);
        $('#gender').val(that.val());
        that.css('background-position','bottom right');
    });​​​​​​

JS Fiddle demo . JS小提琴演示

To allow for toggling: 为了允许切换:

$('.gnM').click(
    function(){
        var that = $(this);
        $('#gender').val(that.val());
        that.siblings().removeClass('active');
        that.toggleClass('active');
    });​

JS Fiddle demo . JS小提琴演示

Or, more concisely: 或者,更简洁地说:

$('.gnM').click(
    function(){
        var that = $(this);
        $('#gender').val(that.val());
        that.toggleClass('active').siblings().removeClass('active');
    });​

JS Fiddle demo . JS小提琴演示

References: 参考文献:

使用jQuery的http://jsfiddle.net/vFsXt/解决方案,避免对js使用内联属性

Create a css class ( button-toggle-on ) that applies the toggled background-position for the buttons. 创建一个css类( button-toggle-on ),该类为button-toggle-on应用切换的背景位置。 Then in the button onclick toggle the class on the button. 然后在按钮onclick切换按钮上的类。 For this to work, one needs to be toggled on initially. 为此,首先需要将其打开。

<input type="button" class="gnM button-toggle-on" onclick="$('#gender').val('male'); $('.gnF, .gnM').toggleClass('button-toggle-on');" /> 
<input type="button" class="gnF" onclick="$('#gender').val('female'); $('.gnF, .gnM').toggleClass('button-toggle-on');" />

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

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