2

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.