5

I need to translate this jQuery command in JavaScript:

$('#edit_pickup_date_modal').find('input[name=type]').val('2');

I tried to:

var element = document.getElementById('edit_pickup_date_modal');
var input = element.getElementsByName('type')[0];
input.value = '2'

but I got the error "element.getElementsByName is not a function"

  • 1
    [Javascript Get Child Element by Name](https://stackoverflow.com/questions/14842951/javascript-get-child-element-by-name) – Nathan Champion Aug 21 '20 at 14:38
  • 1
    have you tried ```var elms = document.querySelectorAll('#edit_pickup_date_modal input[name=type]'); elms.forEach(x => { x.value = 2 } )```? Maybe on the oldest browser you have to cast the **NodeList** returned from *Element.prototype.querySelectorAll* to a normal **Array** with ```Array.from(elms)``` – asdru Aug 21 '20 at 15:10

4 Answers4

4

For more info on searching for the elements on DOM such as getElementById, querySelector, please refer here

const modalDiv = document.getElementById('edit_pickup_date_modal')

const inputElem = modalDiv.querySelector('input[name=type]');

inputElem.value = 2
<div id="edit_pickup_date_modal">
  <input name="type"/>
</div>
Nithish
  • 5,393
  • 2
  • 9
  • 24
3

Use getElementById to get the tag with id 'edit_pickup_date_modal'. Than search with querySelector for the first INPUT-field with name = 'type' and set the value.

document.getElementById('edit_pickup_date_modal').querySelector('input[name=type]').value=2;
<div id='edit_pickup_date_modal'>
  <div>
    <input name ='type'>
  </div>
</div>
Sascha
  • 4,576
  • 3
  • 13
  • 34
1

You can also combine the whole operation into a single querySelector:

document.querySelector('#edit_pickup_date_modal input[name=type]').value=2;
<div id='edit_pickup_date_modal'>
  <div>
    <input name ='type'>
  </div>
</div>
Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
1

The equivalent vanilla function for the jQuery $('#edit_pickup_date_modal').find('input[name=type]').val('2');

is:

document.querySelectorAll('#edit_pickup_date_modal input[name=type]').forEach(function(obj, index){
    obj.value=2;
});

//If you need to take the first element only.
document.querySelector('#edit_pickup_date_modal input[name=type]').value=3;
<div id="edit_pickup_date_modal">
  <input name="type"/>
   <input name="type"/>
    <input name="type"/>
     <input name="type"/>
</div>
 

And it means:

for each input[name=type] inside the element with the ID edit_pickup_date_modal, assign to its value property the constant value 2.

asdru
  • 1,147
  • 10
  • 19
toto
  • 1,180
  • 2
  • 13
  • 30