Jquery +将复选框值添加到href元素

时间:2011-02-07 20:22:01

标签: jquery

这就是我所拥有的:

$(function() { 
    $('#find_1 input[type="checkbox"]').change(function() { 
        var $t = $("#t");
        if ( this.checked )
            $t.append(($t.text()?",":"")+this.value);
        else
            $t.text($t.text().replace(
                  new RegExp("\\b"+this.value+"\\b"), ""
            ));
    }).change();
});

我需要的是在目标#t

的a href中写入复选框值

例如:

选中的复选框:

[x]red

[ ]green

[x]blue

应该导致像这样的href:

<div id"t"><a href"/colors/red,blue">preview colors</a>

当然,当用户点击/取消选中复选框时,将添加/删除颜色。

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

我会这样做:

$('#find_1 input:checkbox').change(function() { 
    var colours = $("#find_1 input:checkbox:checked").map(function() {
        return this.value;
    }).get().join(',');
    $("#t").find("a").attr('href', '/colors/' + colours);
}).change();

You can try it out here.

答案 1 :(得分:0)

所以你有一些像

这样的HTML
<div id="find_1">
<input type="checkbox" name="red">
<input type="checkbox" name="green">
</div>

并且div包含一个href,如果我理解你,你想更新复选框的href

$(document).ready(function(){
    //init, if you start with some colors selected you can add those here
    //or you can trigger the change event on all checkboxes
    $('#t').data('colors',[]);
    //bind change event
    $('#find_1 input[type="checkbox"]').change(function(){
        //get the data from the t div
        var data = $('#t').data('colors');
        //update the data with the new value
        data[this.data] = this.checked;
        //save the new data
        $('#t').data('colors',data);
        //rebuild the parts form all data wich has true as value
        var parts = $.map(data,function(el,i){
            //map each value in the data array and check for true
            if (!el) return null;
        });
        //the url is the parts concaternated
        $('#t a').attr('href','/colors/'+parts.join(','));
    });
});