问题描述:

I have about 20 checkboxes with same name, but id values is not the same

 <input type="checkbox" name="device" id="1_2"/>

<input type="checkbox" name="device" id="10_4"/>

<input type="checkbox" name="device" id="5_6"/>

<input type="checkbox" name="device" id="4_0"/>

<input type="checkbox" name="device" id="8_9"/>

<input type="checkbox" name="device" id="3_4"/>

I want a function, if i click on a checkbox, then i get a alert with the value of ID

Example, if i click on the first checkbox

alert("Value before _ : 1 - Value after _ : 2")

How can I do that?

网友答案:

Here is an example: jsfiddle

Hope its what you need, have fun playing with it.

HTML: (add a class to the inputs)

 <input class='try' type="checkbox" name="device" id="1_2"/>
 <input class='try' type="checkbox" name="device" id="10_4"/>
 <input class='try' type="checkbox" name="device" id="5_6"/>
 <input class='try' type="checkbox" name="device" id="4_0"/>
 <input class='try' type="checkbox" name="device" id="8_9"/>
 <input class='try' type="checkbox" name="device" id="3_4"/>

SCRIPT: (click event)

$('.try').click(function() {
    var idd= $(this).attr('id');
    var explode = idd.split('_');
    alert('Value before:' + explode[0] + ' - Value after:' + explode[1]);
});
网友答案:

This is what you're looking for

     $(document).ready(function () {
        $('input[type="checkbox"]').click(function(){
           var vals = this.id.split('_');
           alert("Value before _ : "+vals[0]+" - Value after _ : " + vals[1])
        })
     })

This function is called on click of each checkbox. It uses javascript's split function to split the id attribute value into an array.

网友答案:

Is this what you need.? Demo

    $('input:checkbox[name="device"]').click(function(){
    var id = $(this).attr('id');
    alert( 'Value before:' + id.split('_')[0] + ' - Value after:' + id.split('_')[1] );
    });
网友答案:
$("input[type=checkbox]").click(function(){
   arr = $(this).attr("id").split("_");
   alert("Value before _ :"+arr[0]+" Value after _ :"+arr[1]);
});

here is jsFiddle

网友答案:
$("input[type=checkbox]").click(function(){
     alert($(this).attr("id"))
});
网友答案:

I hope this will help:

     $('input:checkbox[name="device"]').click( function(){ 
         var selected_data = $(this).attr('id').split('_'); 
         alert('Value before _ : ' + selected_data[0] + ' - ' + 'Value after _ : ' +      selected_data[1]);
     });
    

相关阅读:
Top