简体   繁体   中英

How to get button id

I have a file Index.aspx connected to file seatbooks.js .
In Index.aspx has a button with id Indexbutton . Indexbutton has eventonclick='book_ticket()' . book_ticket() method is include on seatbooks.js . How to get button id ( Indexbutton ) on book_ticket() . Please check my code bellow:

 <input type="button" name="submit" class="ui-state-default ui-corner-all" id="indexbutton" onclick="book_tickets()" value="Book Seat" />

Above is my code on Index.aspx . And this is my book_ticket() code:

function book_tickets() {    
var tickets = jQuery('.seat.selected').length;
//seatId = $('#button').attr('id');   
//var btnId = this.attr('id');
//console.log(seatId);
if(tickets==0)
{
    alert('Please select at least one seat to continue...!');
    return false;
} else if (tickets > 1)
{
    alert('Please select only one seat to continue...!!');
    return false;
}else
{
    x = jQuery('.seat.selected').toArray();
    jQuery('#seat-form-data').html('');
    jQuery('.seat.selected').each
    (
        function () {
            var ydata = jQuery(this).html();
            xdata = ydata.replace("[class]", "");
            jQuery('#seat-form-data').append(xdata);
        }
    );
    jQuery('#seat-form-data').append('<input type="submit" value="submit">');
    jQuery('#seat-form-data input[type="submit"]:first').trigger('click');
    //console.log(xdata);


    // Link to open the dialog
   $("#dialog").dialog("open");
    //event.preventDefault();
}

}

I had tried:

seatId = $('#button').attr('id');   
var btnId = this.attr('id');

And tried to show it on console. But it doesn't work. It say undefine . I want to get indexbutton (button id) on book_tickets() .

Since you have a hard coded ID why do you want to access it via any other way. You can hard code the button Id isn't it?

Anyway, one solution is to pass the dom reference to the function like

<input type="button" name="submit" class="ui-state-default ui-corner-all" id="indexbutton" onclick="book_tickets(this)" value="Book Seat" />

then

function book_tickets(el) { 
    var buttonId = el.id;
    ....
}

Your code

seatId = $('#button').attr('id');
var btnId = this.attr('id');

$('#button').attr('id') will look for an element with id button and if it is found it will return the id of that element which is again button , same way this inside the book_tickets method does not refer to the button, it is the window object so this.attr('id') will fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM