Change input value by javascript in bookmark

1.2k Views Asked by At

I need to make a bookmark which executes a javascript that changes an input value.

<input type="text" placeholder=" - " value=" - " class="test"/>

I tried several different script including this one:

javascript:(function(){var d=document,e=d.getElementsByClassName("test");e.value="new value";})();

But none of them works. Can anyone help please?

3

There are 3 best solutions below

0
On

Document.getElementsByClassName() returns an array-like object of all child elements with that class. Thus, you need to select the first index of the array. This would work:

e=d.getElementsByClassName("test")[0]; // select first element, now e is a DOM element

var d = document,
    e = d.getElementsByClassName("test")[0];
e.value="new value";
<input type="text" placeholder=" - " value=" - " class="test"/>

0
On

Document.getElementsByClassName() returns an array-like object of all child elements which have all of the given class names

see bellow a working snippet

function myBookmark(){
  var d=document,elements=d.getElementsByClassName("test");
  for (var i=0;i<elements.length;i++){
  elements[i].value="new value";
  }
}
<input type="text" placeholder=" - " value=" - " class="test"/>
<input type="text" placeholder=" - " value=" - " class="test"/>
<input type="text" placeholder=" - " value=" - " class="test"/>

<a href="javascript:myBookmark()">Execute Bookmark</a>;

0
On

Slightly more versatile. Enter a selector and some text:

let p=prompt,
    sel=p('enter selector'),
    v=p('new value');
Array.from(document.querySelectorAll(sel)).forEach(e=>e.value=v)

Passed through a bookmarklet creator:

javascript:(function()%7Blet%20p%3Dprompt%2Csel%3Dp('enter%20selector')%2Cv%3Dp('new%20value')%3BArray.from(document.querySelectorAll(sel)).forEach(e%3D%3Ee.value%3Dv)%7D)()