开发者

Jquery + add checkbox values to href element

Here is what I have:

$(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();
});

What I need is to write the checkbox value in the a href of the target #t

For example:

The selected checkboxes:

[x]red

[ ]green

[x]blue

Should result in a href like this:

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

Of course the colors will be added/removed as the user click/unclick the checkboxes.

Thanks for the help.


I would do it this way:

$('#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.


so you have some html like

<div id="find_1">
<input type="checkbox" name="red">
<input type="checkbox" name="green">
</div>

and the div t wich contains an a href, and you want to update the href on change of the checkboxes if i understand you right

$(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(','));
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜