Search code examples
htmlprototypejs

determine which button was clicked in HTML form - NOT submit type


I do NOT want the type="submit" because it changes the page -
I'm submitting thru ajax.. so I'm using type="button"

<input type="button" value="This is a submit button" name="submit1" onClick="submitMe( this.form )">
<input type="button" value="Another submit button" name="submit2" onClick="submitMe( this.form )">
<input type="button" value="Yet another submit button!" name="submit3" onClick="submitMe( this.form )">

However ALL the button names appear as passed form variables - I'd expect only the clicked button to be passed, like checkboxes or submit buttons...(if its NOT selected - don't pass it)

how can I determine WHICH button was selected - I need this because the action will be different based on button.

Using prototype 'AJAX.UPDATER' to handle the form.

The JS looks like this...

function submitMe( frm ) {
    var div = 'msgDiv';
    var url = 'mypage.aspx';
    var pars = Form.serialize( frm ); 
    var myAjax = new Ajax.Updater( div, url, { asynchronous:true, method:'post', parameters:pars    });
}

thx


Solution

  • You should probably use the observe or on() methods instead of the normal onclick attributes - for your html add a class

    <input type="button" value="This is a submit button" class="submitbutton" name="submit1" >
    <input type="button" value="Another submit button" class="submitbutton" name="submit2" ">
    <input type="button" value="Yet another submit button!" class="submitbutton" name="submit3" >
    

    if you attach an observer to your form by giving it an id of "myform" the "click" event will bubble up from the button to the parent form and you can find out what button the click originated from using the findElement() method on the event that is passed like so. In this instance I would use the on() method as you can specify a CSS selector to limit the scope of the event handling. Otherwise every click would fire the handler.

    $('#myform').on('click','.submitbutton',function(event){
        var clickedbutton = event.findElement();
    
        //then you can fire your submitMe() function
        submitMe(this);
    });
    

    in the on() method this is the element that is being observed