Skip to content Skip to sidebar Skip to footer

Grab The Name Of An Element With Jquery

I have a series of Form Elements each with different names, I'll post one as an example. I cannot hard code the name into Jquery because unless I inspect the element, I won't know

Solution 1:

Here is a example without knowing more of your code:

$(function () {
    $('input:checkbox').click(function () {
        $(this).prop('disabled', true);
        var iName = this.name;
        $.ajax({
            url: "file.php",
            data: {
                'inputname': iName
            },
            success: function (data) {
                alert(data.returned_val);
            }
        })
    })
})

Demo here

If you want to reach the input via name directly you need to use double backslasshes to escape the square brackets and reach that input via name. Use:

$('input[name=aisis_options\\[package_Aisis-Related-Posts-Package-master\\]]')

Solution 2:

You can add an onchange with checkbox onchange="f(this);"

in js f() function you can use this.name to get the name, this.value to get value etc and do whatever you want.

Solution 3:

To check/unckeck, you can use $element.prop('checked', true/false);like this (fiddle):

HTML

<inputtype="checkbox"name="aisis_options[package_Aisis-Related-Posts-Package-master]"value="...."checked="checked" 
/> Aisis-Related-Posts-Package-master 
<ahref="#"class="trigger">(Disable)</a>

JS

$('.trigger').click (function () {
    closest_checkbox = $(this).siblings('input[type=checkbox]');
    closest_checkbox.prop('checked', !closest_checkbox.prop('checked'));
});

JS part 2: AJAX

You can build an object with all your name:value combinations using the jQuery plugin serializeObject, your form submission event handler would be something like:

$('form').submit( function (e) {

    // Prevent the form from being sent normally since we want it ajaxified
    e.preventDefault(); 

    // Send request to php page
    $.ajax({
        type: "POST",
        url: "some.php",
        data: $('form').serializeObject()  // <== Magic happens here
    });
});

PS. Don't forget to include the serializeObject plugin and give a unique id to the form, $('#unique_id') is way better than $('form') which will match all the forms in the page.

Solution 4:

To grab the value of name attribute, you can use:

$(this).attr('name');

Post a Comment for "Grab The Name Of An Element With Jquery"