Search code examples
javascriptbookmarklet

Auto Click With Type or Value Tag


I have a website for which I would like to create a JavaScript bookmarklet for autoclicking, but the site does not use an ID tag. Here is the code of site:

<input type="submit" name="Submit" value="Find Product" 
onclick="return incrementClicksTest('2','true')" class="buttonSubmit">

I used this JavaScript bookmarklet:

javascript:document.getElementById('any_id_here').click()

It works fine for buttons with IDs, but how do I go about making a bookmarklet using the name, value, and type tag?


Solution

  • Use the following:

    document.getElementsByTagName("input")[0].click();
    

    Sample Code: http://jsfiddle.net/dcRsc/

    Now, that will work if your button is the first input in your page.

    Use this if you have numerous elements in your page:

    var elems =document.getElementsByTagName("input");
    
    for(var i=0;i<elems.length;i++)
    {
        if(elems[i].type=="submit" && elems[i].name =="Submit")
        {
            elems[i].click();        
            break;
        }
    }
    

    Sample Code: http://jsfiddle.net/dcRsc/1/

    That will trigger the click event of your submit button, with Submit name.

    Furthermore (and since your button already has a css class) you could use the getElementsByClassName() method:

    var elems =document.getElementsByClassName("buttonSubmit");
    
    for(var i=0;i<elems.length;i++)
    {
        if(elems[i].name =="Submit")
        {
            elems[i].click();        
            break;
        }
    }
    

    Sample Code: http://jsfiddle.net/dcRsc/2/

    That will get all elements with the buttonSubmit class applied.

    Or

    document.getElementsByClassName("buttonSubmit")[0].click();
    

    If your button is the only element in the page with that class on it, hence avoiding the for loop altogether.