user1072337
user1072337

Reputation: 12945

How to send multiple values from a checkbox input

I am trying to collect multiple pieces of data from a checkbox, but I am unsure of how to do this. Right now I have:

<input tabindex="1" type="checkbox" name="friend[]" id="{{$friend}}" value="{{$friend}}" style="display:inline-block;">

Which allows me to collect an id (contained in {{$friend}}) that I need. But I also need the name associated with this id. Is there a way to collect multiple values from a single checkbox? I would need this because I am collecting the data and moving to another form without changing the view. This would be used for javascript which would print out stuff in the view as it is checked (i.e. the id and name).

Here is the javascript:

<script>
$(document).ready(function(){
    var callbacks_list = $('.callbacks ul');
    $('.facebook-friends-larger input').on('ifChecked', function(event){
        callbacks_list.prepend('<li><img src="https://graph.facebook.com/'+this.id+'/picture" alt="" height="50" width="50"><span id="#'+this.id+'">#' + this.id + '</span> is ' + event.type.replace('if', '').toLowerCase() + '</li>');
    });

    $('.facebook-friends-larger input').on('ifUnchecked', function(event) {
        callbacks_list.find('span#'+ this.id).closest('li').remove();
        console.log(this.id);
    });    
});
</script>

Any ideas? Thank you for your help.

Upvotes: 0

Views: 1250

Answers (4)

Terry
Terry

Reputation: 66103

If you have the access to the username before the page is loaded (and is therefore able to inject it into the DOM without making ajax queries after pageload or user action), you can store them in HTML5 data- attributes, for example, data-name in the following format:

<input tabindex="1" type="checkbox" name="friend[]" id="{{$friend}}" value="{{$friend}}" data-name="{{name}}" style="display:inline-block;">

You can access the name by simply calling the .data() method in jQuery, i.e. $('input').data('name').

Upvotes: 0

S. S. Rawat
S. S. Rawat

Reputation: 6111

Try this this will be helpyou..

 $("input[type=checkbox]").change(function(){
        alert($(this).val()); //get a val
        alert($(this).attr('name')); //get a value of name attribute

    });

Fiddle here

Upvotes: 1

YashPatel
YashPatel

Reputation: 295

Try this

HTML

<input tabindex="1" type="checkbox" name="friend[]" id="123" value="{{$friend}}" style="display:inline-block;">test

JS

$(document).ready(function(){
    $("#123").change(function(){
        $(this).val(); //get a val
        console.log($(this).attr('name')); //get a value of name attribute

    });

});

FIDDLE

Upvotes: 0

Joshua Kissoon
Joshua Kissoon

Reputation: 3309

Use:

var name = $("#checkbox-id").attr("name"); // Use whatever method you have to target the checkbox

and so on to get the other values

Upvotes: 0

Related Questions