Search code examples
javascriptjqueryhtmlbookmarklet

Javascript bookmarklet to select drop down value?


Was hoping you guys can help me out. I can't seem to figure out how to make a bookmarklet to selecting options on a drop-down menu on a webpage.

Hoping to achieve: make a bookmark on my chrome browser. When I click it on this page it will select the drop-down and select level 2 in the membership box

html of the webpage

<select name="membership" onchange="submit()">
<option value="1"> Level 1</option>
<option value="2"> Level 2</option>
<option value="3"> Level 3</option>

thanks. Really new to this.

Edit: Sorry I apologize. This is the current bookmark I tried to make

javascript:document.getElementById("membership").selectedIndex = 2; <

EDIT2 < realized probably can't use get element by id since the <select name="membership" is using name instead of id. Is there one that can search the name=?

EDIT 3 THANKS EVERYONE for your help here you guys are amazing and I've learned a lot in the past 2 hrs with the different types of getElements* and queryselector. thanks sideroxylon!


Solution

  • This might get you started. First up you select the option you want. Then trigger the onchange event. Make sure you're passing the selected value.

    document.getElementsByName('membership')[0].value = 2;
    document.getElementsByName('membership')[0].onchange();
    
    function submit(val) {
      alert(val);
    }
    <select name="membership" onchange="submit(this.value)">
      <option value="1">Level 1</option>
      <option value="2">Level 2</option>
      <option value="3">Level 3</option>
    </select>

    Your bookmarklet should look something like this:

    javascript:document.getElementsByName('membership')[0].value = 2;document.getElementsByName('membership')[0].onchange();