1

How can I set values (default values) in more input fields by JavaScript or jQuery? Thank you.

<form method="" action="">
Name: <input type="text" id="id1" value="<?php $value; ?>" placeholder="Your name"> <br><br>
Surname: <input type="text" id="id1" value="<?php $value; ?>" placeholder="Your surname"> <br><br>
Email: <input type="text" id="id1" value="<?php $value; ?>" placeholder="Your email"> <br><br>
</form>
  • 3
    Possible duplicate of [How to set value of input text using jQuery](https://stackoverflow.com/questions/10611170/how-to-set-value-of-input-text-using-jquery) – Eddie Jan 14 '18 at 14:39

4 Answers4

2

Iterate over all inputs, and then set the default value with element.value syntaxis.

Array.from(document.getElementsByTagName("INPUT")).forEach(input => {
  input.value = "Default value has been assigned";
});
Input 1: <input type="text">
Input 2: <input type="text">
Input 3: <input type="text">
ESCM
  • 269
  • 2
  • 13
1

You forgot echo the values. Below is updated code.

<form method="" action="">
Name: <input type="text" id="id1" value="<?php echo $value; ?>" placeholder="Your name"> <br><br>
Surname: <input type="text" id="id1" value="<?php echo $value; ?>" placeholder="Your surname"> <br><br>
Email: <input type="text" id="id1" value="<?php echo $value; ?>" placeholder="Your email"> <br><br>
</form>
Aftab H.
  • 1,517
  • 4
  • 13
  • 25
1

The trick is to come up with a selector that selects all the elements that you would like to change.

Because you would like to change all the values of the text boxes, the following selector would do: $("input['type=text']"). And to change or set their value: just to: $("input['type=text']").val('value');

See a running example: https://jsfiddle.net/2od89uou/1/

Beach Chicken
  • 368
  • 3
  • 13
0

To set the values for input fields in jQuery you can use the .val() method:

$('#id1').val("This is a value");// the selector #id1 selects all elements with id "id1"

If you want to set multiple inputs to same value you need to use another selector as id's are designed to be unique:

$('.text-input').val("Some other value"); // this will set value of all elements with class text-input
user3647971
  • 1,069
  • 1
  • 6
  • 13