更改无线电更改的输入值

时间:2014-11-05 01:25:55

标签: jquery html

我有2个产品,我想在用户选择性别时附加性别的产品名称。我几乎已经开始工作,但还没到那里。性别有时会重复,如果你从家伙变成小鸡,那么它就会保持两者。我知道有一个优雅的解决方案,但我无法找到它。任何帮助将非常感激。

http://jsfiddle.net/rbh9qzwo/1/

<form>
    <input type="radio" name="name" value="Graphics Sock" required>Graphics
    <input type="radio" name="name" value="Pattern Sock" required>Patterns</br>
    <input type="radio" name="gender" value="Dudes" required>Dudes
    <input type="radio" name="gender" value="Chicks" required>Chicks
</form>

$('input:radio[name="gender"]').each(function () {
    if ($(this).val() == 'Dudes') {
        $('input:radio[name="name"]').val($('input:radio[name="name"]').val() + 'Dudes');
    }

    if ($(this).val() == 'Chicks') {
        $('input:radio[name="name"]').val($('input:radio[name="name"]').val() + 'Chicks');
    }

});

3 个答案:

答案 0 :(得分:0)

使用数据属性保存原始值,如下所示:

<input type="radio" name="product" value="product1" data-original="product1">

然后,在您的javascript中,只需将value = value + gendervalue替换为value = data-original1 + gendervalue。

答案 1 :(得分:0)

你可能正在寻找类似的东西:

$(function() {
    $(':radio').on('change', function() {
        var gender = $(':radio[name=gender]:checked').val();
        gender = gender || '';
        $(':radio[name=name]:checked').val( function() {
            return $(this).attr('value') + gender;
        });
    });
});

$(function() {
    $(':radio').on('change', function() {
        var gender = $(':radio[name=gender]:checked').val();
        gender = gender || '';
        $(':radio[name=name]:checked').val( function() {
            return $(this).attr('value') + gender;
        });
        alert( $(':radio[name=name]:checked').val() );
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="name" value="Graphics Sock" required>Graphics
    <input type="radio" name="name" value="Pattern Sock" required>Patterns<br>
    <input type="radio" name="gender" value="Dudes" required>Dudes
    <input type="radio" name="gender" value="Chicks" required>Chicks

答案 2 :(得分:0)

<form>
    <input type="radio" name="name" value="Graphics Sock" data-original = "Graphics Sock" required>Graphics
    <input type="radio" name="name" value="Pattern Sock" data-original = "Pattern Sock" required>Patterns</br>
    <input type="radio" name="gender" value="Dudes" required>Dudes
    <input type="radio" name="gender" value="Chicks" required>Chicks
</form>

<script>


$('input:radio[name="gender"]').on("click",function () {
    if ($(this).val() == 'Dudes') {
        $('input:radio[name="name"]').each(function(){$(this).val($(this).attr("data-original") + ' Dudes'); } ) 
    }

    if ($(this).val() == 'Chicks') {
        $('input:radio[name="name"]').each(function(){$(this).val($(this).attr("data-original") + ' Chicks');})      
    }
});
</script>