Как изменить значение input через js

How would you set the default value of a form text field in JavaScript?

How would you set the default value of a form <input> text field in JavaScript?

Kamil Kiełczewski's user avatar

asked Sep 30, 2011 at 10:32

SebastianOpperman's user avatar

1

This is one way of doing it:

document.getElementById("nameofid").value = "My value";

Community's user avatar

answered Sep 30, 2011 at 10:33

James's user avatar

12

I use setAttribute():

<input type="text" id="example"> // Setup text field 
<script type="text/javascript"> 
  document.getElementById("example").setAttribute('value','My default value');
</script>

TheGoldenTree's user avatar

answered Jun 18, 2014 at 14:37

Pepe Amoedo's user avatar

Pepe AmoedoPepe Amoedo

8456 silver badges2 bronze badges

5

if your form contains an input field like

<input type='text' id='id1' />

then you can write the code in javascript as given below to set its value as

document.getElementById('id1').value='text to be displayed' ; 

answered Sep 30, 2011 at 10:38

Varada's user avatar

VaradaVarada

15.5k13 gold badges47 silver badges67 bronze badges

1

2023 Answer

Instead of using document.getElementById() you can now use document.querySelector() for different cases

more info from another Stack Overflow answer:

querySelector lets you find elements with rules that can’t be
expressed with getElementById and getElementsByClassName

EXAMPLE:

document.querySelector('input[name="myInput"]').value = 'Whatever you want!';

or

let myInput = document.querySelector('input[name="myInput"]');
myInput.value = 'Whatever you want!';

Test:

document.querySelector('input[name="myInput"]').value = 'Whatever you want!';
<input type="text" name="myInput" id="myInput" placeholder="Your text">

answered Nov 19, 2020 at 19:10

Runsis's user avatar

RunsisRunsis

7718 silver badges18 bronze badges

2

If you are using multiple forms, you can use:

<form name='myForm'>
    <input type='text' name='name' value=''>
</form>

<script type="text/javascript"> 
    document.forms['myForm']['name'].value = "New value";
</script>

answered Mar 17, 2017 at 14:42

David Caissy's user avatar

David CaissyDavid Caissy

2,1315 gold badges24 silver badges26 bronze badges

5

Try out these.

document.getElementById("current").value = 12

// or

var current = document.getElementById("current");
current.value = 12

luis_laurent's user avatar

answered Dec 11, 2012 at 18:23

dallinchase's user avatar

dallinchasedallinchase

3252 silver badges3 bronze badges

2

The answer is really simple

// Your HTML text field

<input type="text" name="name" id="txt">

//Your javascript

<script type="text/javascript"> 
document.getElementById("txt").value = "My default value";
</script>

Or if you want to avoid JavaScript entirely: You can define it just using HTML

<input type="text" name="name" id="txt" value="My default value">

Alexander Johansen's user avatar

answered Sep 2, 2015 at 5:59

php-coder's user avatar

php-coderphp-coder

9551 gold badge12 silver badges23 bronze badges

2

<input id="a_name" type="text" />

Here is the solution using jQuery:

$(document).ready(function(){
  $('#a_name').val('something');
});

Or, using JavaScript:

document.getElementById("a_name").value = "Something";

Happy coding :)

answered Apr 8, 2021 at 6:39

Rashed Rahat's user avatar

Rashed RahatRashed Rahat

2,0802 gold badges20 silver badges36 bronze badges

The simple answer is not in Javascript the simplest way to get the placeholder is through the place holder attribute

<input type="text" name="text_box_1" placeholder="My Default Value" />

answered Aug 6, 2014 at 15:38

RWolfe's user avatar

RWolfeRWolfe

4479 silver badges27 bronze badges

4

document.getElementById("fieldId").value = "Value";

or

document.forms['formId']['fieldId'].value = "Value";

or

document.getElementById("fieldId").setAttribute('value','Value');

answered Feb 5, 2018 at 11:59

Arun Karnawat's user avatar

2

It’s simple; An example is:

<input type="text" id="example"> // Setup text field 
<script type="text/javascript"> 
var elem = document.getElementById("example"); // Get text field
elem.value = "My default value"; // Change field
</script>

answered Apr 4, 2014 at 8:00

ultimatetechie's user avatar

If the field for whatever reason only has a name attribute and nothing else, you can try this:

document.getElementsByName("INPUTNAME")[0].value = "TEXT HERE";

answered Jul 25, 2020 at 18:34

Cake Princess's user avatar

<form>
  <input type="number"  id="inputid"  value="2000" />
</form>


<script>
var form_value = document.getElementById("inputid").value;
</script>    

You can also change the default value to a new value

<script>
document.getElementById("inputid").value = 4000;     
</script>

Marcello B.'s user avatar

Marcello B.

4,03711 gold badges47 silver badges64 bronze badges

answered Oct 17, 2018 at 6:43

Tobiloba's user avatar

TobilobaTobiloba

1,4101 gold badge10 silver badges7 bronze badges

This part you use in html

<input id="latitude" type="text" name="latitude"></p>

This is javaScript:

<script>
document.getElementById("latitude").value=25;
</script>

answered Jan 3, 2019 at 8:13

Amranur Rahman's user avatar

You can also try:

document.getElementById('theID').value = 'new value';

answered Sep 2, 2015 at 10:56

Bogdan Mates's user avatar

1

Direct access

If you use ID then you have direct access to input in JS global scope

myInput.value = 'default_value'
<input id="myInput">

answered Jun 26, 2020 at 16:11

Kamil Kiełczewski's user avatar

Kamil KiełczewskiKamil Kiełczewski

80.5k29 gold badges352 silver badges327 bronze badges

The following code work perfectly well:

var $div = ('#js-div-hour input');
$div.attr('value','2022/01/10');

answered Jan 6, 2022 at 13:13

mahmoud aoata's user avatar

How would you set the default value of a form <input> text field in JavaScript?

Kamil Kiełczewski's user avatar

asked Sep 30, 2011 at 10:32

SebastianOpperman's user avatar

1

This is one way of doing it:

document.getElementById("nameofid").value = "My value";

Community's user avatar

answered Sep 30, 2011 at 10:33

James's user avatar

12

I use setAttribute():

<input type="text" id="example"> // Setup text field 
<script type="text/javascript"> 
  document.getElementById("example").setAttribute('value','My default value');
</script>

TheGoldenTree's user avatar

answered Jun 18, 2014 at 14:37

Pepe Amoedo's user avatar

Pepe AmoedoPepe Amoedo

8456 silver badges2 bronze badges

5

if your form contains an input field like

<input type='text' id='id1' />

then you can write the code in javascript as given below to set its value as

document.getElementById('id1').value='text to be displayed' ; 

answered Sep 30, 2011 at 10:38

Varada's user avatar

VaradaVarada

15.5k13 gold badges47 silver badges67 bronze badges

1

2023 Answer

Instead of using document.getElementById() you can now use document.querySelector() for different cases

more info from another Stack Overflow answer:

querySelector lets you find elements with rules that can’t be
expressed with getElementById and getElementsByClassName

EXAMPLE:

document.querySelector('input[name="myInput"]').value = 'Whatever you want!';

or

let myInput = document.querySelector('input[name="myInput"]');
myInput.value = 'Whatever you want!';

Test:

document.querySelector('input[name="myInput"]').value = 'Whatever you want!';
<input type="text" name="myInput" id="myInput" placeholder="Your text">

answered Nov 19, 2020 at 19:10

Runsis's user avatar

RunsisRunsis

7718 silver badges18 bronze badges

2

If you are using multiple forms, you can use:

<form name='myForm'>
    <input type='text' name='name' value=''>
</form>

<script type="text/javascript"> 
    document.forms['myForm']['name'].value = "New value";
</script>

answered Mar 17, 2017 at 14:42

David Caissy's user avatar

David CaissyDavid Caissy

2,1315 gold badges24 silver badges26 bronze badges

5

Try out these.

document.getElementById("current").value = 12

// or

var current = document.getElementById("current");
current.value = 12

luis_laurent's user avatar

answered Dec 11, 2012 at 18:23

dallinchase's user avatar

dallinchasedallinchase

3252 silver badges3 bronze badges

2

The answer is really simple

// Your HTML text field

<input type="text" name="name" id="txt">

//Your javascript

<script type="text/javascript"> 
document.getElementById("txt").value = "My default value";
</script>

Or if you want to avoid JavaScript entirely: You can define it just using HTML

<input type="text" name="name" id="txt" value="My default value">

Alexander Johansen's user avatar

answered Sep 2, 2015 at 5:59

php-coder's user avatar

php-coderphp-coder

9551 gold badge12 silver badges23 bronze badges

2

<input id="a_name" type="text" />

Here is the solution using jQuery:

$(document).ready(function(){
  $('#a_name').val('something');
});

Or, using JavaScript:

document.getElementById("a_name").value = "Something";

Happy coding :)

answered Apr 8, 2021 at 6:39

Rashed Rahat's user avatar

Rashed RahatRashed Rahat

2,0802 gold badges20 silver badges36 bronze badges

The simple answer is not in Javascript the simplest way to get the placeholder is through the place holder attribute

<input type="text" name="text_box_1" placeholder="My Default Value" />

answered Aug 6, 2014 at 15:38

RWolfe's user avatar

RWolfeRWolfe

4479 silver badges27 bronze badges

4

document.getElementById("fieldId").value = "Value";

or

document.forms['formId']['fieldId'].value = "Value";

or

document.getElementById("fieldId").setAttribute('value','Value');

answered Feb 5, 2018 at 11:59

Arun Karnawat's user avatar

2

It’s simple; An example is:

<input type="text" id="example"> // Setup text field 
<script type="text/javascript"> 
var elem = document.getElementById("example"); // Get text field
elem.value = "My default value"; // Change field
</script>

answered Apr 4, 2014 at 8:00

ultimatetechie's user avatar

If the field for whatever reason only has a name attribute and nothing else, you can try this:

document.getElementsByName("INPUTNAME")[0].value = "TEXT HERE";

answered Jul 25, 2020 at 18:34

Cake Princess's user avatar

<form>
  <input type="number"  id="inputid"  value="2000" />
</form>


<script>
var form_value = document.getElementById("inputid").value;
</script>    

You can also change the default value to a new value

<script>
document.getElementById("inputid").value = 4000;     
</script>

Marcello B.'s user avatar

Marcello B.

4,03711 gold badges47 silver badges64 bronze badges

answered Oct 17, 2018 at 6:43

Tobiloba's user avatar

TobilobaTobiloba

1,4101 gold badge10 silver badges7 bronze badges

This part you use in html

<input id="latitude" type="text" name="latitude"></p>

This is javaScript:

<script>
document.getElementById("latitude").value=25;
</script>

answered Jan 3, 2019 at 8:13

Amranur Rahman's user avatar

You can also try:

document.getElementById('theID').value = 'new value';

answered Sep 2, 2015 at 10:56

Bogdan Mates's user avatar

1

Direct access

If you use ID then you have direct access to input in JS global scope

myInput.value = 'default_value'
<input id="myInput">

answered Jun 26, 2020 at 16:11

Kamil Kiełczewski's user avatar

Kamil KiełczewskiKamil Kiełczewski

80.5k29 gold badges352 silver badges327 bronze badges

The following code work perfectly well:

var $div = ('#js-div-hour input');
$div.attr('value','2022/01/10');

answered Jan 6, 2022 at 13:13

mahmoud aoata's user avatar

Изменение, удаление значения в value js примеры

Сегодня будем менять значение в value в любом типе тега, в основном это input! Для того, чтобы изменить данные value , нужно каким-то образом обратиться к тегу! Далее добавим кнопку и изменим данные по клику по кнопке!

Навигация по странице :

  1. Как изменить данные внутри value по id в javascript
  2. Как изменить данные внутри value по классу в javascript
  3. Как изменить данные внутри value по Name
  4. Как удалить данные внутри value в javascript
  5. Скачать скрипт изменения, удаления данные внутри value в javascript
  6. Скачать можно здесь
  1. Как мы уже выше сказали, то каким-то образом нам нужно обратиться в нашему инпуту! Добавим ему id = example

    <input id=»example» value=»Данные value которые будем менять по клику»>

    Далее нам потребуется кнопка, прямо на неё повесим onclick по нажатию на которую изменим value в input

    <button onclick=»example.value=’Здесь новые данные для value input'»>Измени value по клику</button>

    Готовый скрипт для изменения value в input:

    <input id=»example» value=»Данные value которые будем менять по клику»>

    <button onclick=»example.value=’Здесь новые данные для value input'»>Измени value по клику</button>

    Результат: для изменения value в input, вам нужно нажать на кнопку со словами — Измени value по клику

  2. Как изменить данные внутри value по классу в javascript

    Чем замечательно — использование getElementsByClassName — тем, что мы можем обратить с нескольким элементам, блокам которые имеют данный класс! Возьмем выше приведенный код изменения value и уже поставим во внутрь класс example, меняем лишь ячейку [0] на +1, в зависимости от количество input:

    <input value=»Данные value которые будем менять по клику » class=»example» >

    <button onclick=»document.getElementsByClassName(‘example’)[0].value=’Здесь новые данные для value input!'» class=»button»>Измени value по клику</button>

    Результат: ниже приведено несколько полей input, и каждой прикреплена своя кнопка:

  3. Как изменить данные внутри value по Name

    Но если вдруг у вашего инпута нет ни класса. ни id, ну или просто хотим обратиться к атрибуту name, есть такая функция, с помощью которой мы можем обратиться к атрибуту name -> getElementsByName, данная функция, как и выше приведенная получает HTMLCollection

    Возьмем выше идущий скрипт, и заменим класс на name,getElementsByClassName на getElementsByName и получим:

    <input name=»example» value=»Данные value которые будем менять с помощью getElementsByName»>

    <button onclick=»document.getElementsByName(‘example’)[0].value=’getElementsByName = Здесь новые данные для value input !'» class=»button»>Измени value по клику</button>

    Результат:

  4. Как удалить данные внутри value в javascript

    Если вас интересует, как удалить значение внутри input, то вам нужно выбрать како-то из выше перечисленных способов выше и вместо значение внутри скобок установить значение — ничего, например :

    document.getElementsByName(‘example’)[0].value=»

  5. Скачать скрипт изменения, удаления данные внутри value в javascript

    Скрипт обновлен и внесены все выше приведенные скрипты замены value, скачать можно по ниже идущей ссылке:

Можете не благодарить, лучше помогите!

Название скрипта :javascript передача текста в input

COMMENTS+

 
BBcode


How would you set the default value of a form <input> text field in JavaScript?

Kamil Kiełczewski's user avatar

asked Sep 30, 2011 at 10:32

SebastianOpperman's user avatar

1

This is one way of doing it:

document.getElementById("nameofid").value = "My value";

Community's user avatar

answered Sep 30, 2011 at 10:33

James's user avatar

12

I use setAttribute():

<input type="text" id="example"> // Setup text field 
<script type="text/javascript"> 
  document.getElementById("example").setAttribute('value','My default value');
</script>

TheGoldenTree's user avatar

answered Jun 18, 2014 at 14:37

Pepe Amoedo's user avatar

Pepe AmoedoPepe Amoedo

8456 silver badges2 bronze badges

5

if your form contains an input field like

<input type='text' id='id1' />

then you can write the code in javascript as given below to set its value as

document.getElementById('id1').value='text to be displayed' ; 

answered Sep 30, 2011 at 10:38

Varada's user avatar

VaradaVarada

15.5k13 gold badges47 silver badges67 bronze badges

1

2023 Answer

Instead of using document.getElementById() you can now use document.querySelector() for different cases

more info from another Stack Overflow answer:

querySelector lets you find elements with rules that can’t be
expressed with getElementById and getElementsByClassName

EXAMPLE:

document.querySelector('input[name="myInput"]').value = 'Whatever you want!';

or

let myInput = document.querySelector('input[name="myInput"]');
myInput.value = 'Whatever you want!';

Test:

document.querySelector('input[name="myInput"]').value = 'Whatever you want!';
<input type="text" name="myInput" id="myInput" placeholder="Your text">

answered Nov 19, 2020 at 19:10

Runsis's user avatar

RunsisRunsis

7718 silver badges18 bronze badges

2

If you are using multiple forms, you can use:

<form name='myForm'>
    <input type='text' name='name' value=''>
</form>

<script type="text/javascript"> 
    document.forms['myForm']['name'].value = "New value";
</script>

answered Mar 17, 2017 at 14:42

David Caissy's user avatar

David CaissyDavid Caissy

2,1315 gold badges24 silver badges26 bronze badges

5

Try out these.

document.getElementById("current").value = 12

// or

var current = document.getElementById("current");
current.value = 12

luis_laurent's user avatar

answered Dec 11, 2012 at 18:23

dallinchase's user avatar

dallinchasedallinchase

3252 silver badges3 bronze badges

2

The answer is really simple

// Your HTML text field

<input type="text" name="name" id="txt">

//Your javascript

<script type="text/javascript"> 
document.getElementById("txt").value = "My default value";
</script>

Or if you want to avoid JavaScript entirely: You can define it just using HTML

<input type="text" name="name" id="txt" value="My default value">

Alexander Johansen's user avatar

answered Sep 2, 2015 at 5:59

php-coder's user avatar

php-coderphp-coder

9551 gold badge12 silver badges23 bronze badges

2

<input id="a_name" type="text" />

Here is the solution using jQuery:

$(document).ready(function(){
  $('#a_name').val('something');
});

Or, using JavaScript:

document.getElementById("a_name").value = "Something";

Happy coding :)

answered Apr 8, 2021 at 6:39

Rashed Rahat's user avatar

Rashed RahatRashed Rahat

2,0802 gold badges20 silver badges36 bronze badges

The simple answer is not in Javascript the simplest way to get the placeholder is through the place holder attribute

<input type="text" name="text_box_1" placeholder="My Default Value" />

answered Aug 6, 2014 at 15:38

RWolfe's user avatar

RWolfeRWolfe

4479 silver badges27 bronze badges

4

document.getElementById("fieldId").value = "Value";

or

document.forms['formId']['fieldId'].value = "Value";

or

document.getElementById("fieldId").setAttribute('value','Value');

answered Feb 5, 2018 at 11:59

Arun Karnawat's user avatar

2

It’s simple; An example is:

<input type="text" id="example"> // Setup text field 
<script type="text/javascript"> 
var elem = document.getElementById("example"); // Get text field
elem.value = "My default value"; // Change field
</script>

answered Apr 4, 2014 at 8:00

ultimatetechie's user avatar

If the field for whatever reason only has a name attribute and nothing else, you can try this:

document.getElementsByName("INPUTNAME")[0].value = "TEXT HERE";

answered Jul 25, 2020 at 18:34

Cake Princess's user avatar

<form>
  <input type="number"  id="inputid"  value="2000" />
</form>


<script>
var form_value = document.getElementById("inputid").value;
</script>    

You can also change the default value to a new value

<script>
document.getElementById("inputid").value = 4000;     
</script>

Marcello B.'s user avatar

Marcello B.

4,03711 gold badges47 silver badges64 bronze badges

answered Oct 17, 2018 at 6:43

Tobiloba's user avatar

TobilobaTobiloba

1,4101 gold badge10 silver badges7 bronze badges

This part you use in html

<input id="latitude" type="text" name="latitude"></p>

This is javaScript:

<script>
document.getElementById("latitude").value=25;
</script>

answered Jan 3, 2019 at 8:13

Amranur Rahman's user avatar

You can also try:

document.getElementById('theID').value = 'new value';

answered Sep 2, 2015 at 10:56

Bogdan Mates's user avatar

1

Direct access

If you use ID then you have direct access to input in JS global scope

myInput.value = 'default_value'
<input id="myInput">

answered Jun 26, 2020 at 16:11

Kamil Kiełczewski's user avatar

Kamil KiełczewskiKamil Kiełczewski

80.5k29 gold badges352 silver badges327 bronze badges

The following code work perfectly well:

var $div = ('#js-div-hour input');
$div.attr('value','2022/01/10');

answered Jan 6, 2022 at 13:13

mahmoud aoata's user avatar

How would you set the default value of a form <input> text field in JavaScript?

Kamil Kiełczewski's user avatar

asked Sep 30, 2011 at 10:32

SebastianOpperman's user avatar

1

This is one way of doing it:

document.getElementById("nameofid").value = "My value";

Community's user avatar

answered Sep 30, 2011 at 10:33

James's user avatar

12

I use setAttribute():

<input type="text" id="example"> // Setup text field 
<script type="text/javascript"> 
  document.getElementById("example").setAttribute('value','My default value');
</script>

TheGoldenTree's user avatar

answered Jun 18, 2014 at 14:37

Pepe Amoedo's user avatar

Pepe AmoedoPepe Amoedo

8456 silver badges2 bronze badges

5

if your form contains an input field like

<input type='text' id='id1' />

then you can write the code in javascript as given below to set its value as

document.getElementById('id1').value='text to be displayed' ; 

answered Sep 30, 2011 at 10:38

Varada's user avatar

VaradaVarada

15.5k13 gold badges47 silver badges67 bronze badges

1

2023 Answer

Instead of using document.getElementById() you can now use document.querySelector() for different cases

more info from another Stack Overflow answer:

querySelector lets you find elements with rules that can’t be
expressed with getElementById and getElementsByClassName

EXAMPLE:

document.querySelector('input[name="myInput"]').value = 'Whatever you want!';

or

let myInput = document.querySelector('input[name="myInput"]');
myInput.value = 'Whatever you want!';

Test:

document.querySelector('input[name="myInput"]').value = 'Whatever you want!';
<input type="text" name="myInput" id="myInput" placeholder="Your text">

answered Nov 19, 2020 at 19:10

Runsis's user avatar

RunsisRunsis

7718 silver badges18 bronze badges

2

If you are using multiple forms, you can use:

<form name='myForm'>
    <input type='text' name='name' value=''>
</form>

<script type="text/javascript"> 
    document.forms['myForm']['name'].value = "New value";
</script>

answered Mar 17, 2017 at 14:42

David Caissy's user avatar

David CaissyDavid Caissy

2,1315 gold badges24 silver badges26 bronze badges

5

Try out these.

document.getElementById("current").value = 12

// or

var current = document.getElementById("current");
current.value = 12

luis_laurent's user avatar

answered Dec 11, 2012 at 18:23

dallinchase's user avatar

dallinchasedallinchase

3252 silver badges3 bronze badges

2

The answer is really simple

// Your HTML text field

<input type="text" name="name" id="txt">

//Your javascript

<script type="text/javascript"> 
document.getElementById("txt").value = "My default value";
</script>

Or if you want to avoid JavaScript entirely: You can define it just using HTML

<input type="text" name="name" id="txt" value="My default value">

Alexander Johansen's user avatar

answered Sep 2, 2015 at 5:59

php-coder's user avatar

php-coderphp-coder

9551 gold badge12 silver badges23 bronze badges

2

<input id="a_name" type="text" />

Here is the solution using jQuery:

$(document).ready(function(){
  $('#a_name').val('something');
});

Or, using JavaScript:

document.getElementById("a_name").value = "Something";

Happy coding :)

answered Apr 8, 2021 at 6:39

Rashed Rahat's user avatar

Rashed RahatRashed Rahat

2,0802 gold badges20 silver badges36 bronze badges

The simple answer is not in Javascript the simplest way to get the placeholder is through the place holder attribute

<input type="text" name="text_box_1" placeholder="My Default Value" />

answered Aug 6, 2014 at 15:38

RWolfe's user avatar

RWolfeRWolfe

4479 silver badges27 bronze badges

4

document.getElementById("fieldId").value = "Value";

or

document.forms['formId']['fieldId'].value = "Value";

or

document.getElementById("fieldId").setAttribute('value','Value');

answered Feb 5, 2018 at 11:59

Arun Karnawat's user avatar

2

It’s simple; An example is:

<input type="text" id="example"> // Setup text field 
<script type="text/javascript"> 
var elem = document.getElementById("example"); // Get text field
elem.value = "My default value"; // Change field
</script>

answered Apr 4, 2014 at 8:00

ultimatetechie's user avatar

If the field for whatever reason only has a name attribute and nothing else, you can try this:

document.getElementsByName("INPUTNAME")[0].value = "TEXT HERE";

answered Jul 25, 2020 at 18:34

Cake Princess's user avatar

<form>
  <input type="number"  id="inputid"  value="2000" />
</form>


<script>
var form_value = document.getElementById("inputid").value;
</script>    

You can also change the default value to a new value

<script>
document.getElementById("inputid").value = 4000;     
</script>

Marcello B.'s user avatar

Marcello B.

4,03711 gold badges47 silver badges64 bronze badges

answered Oct 17, 2018 at 6:43

Tobiloba's user avatar

TobilobaTobiloba

1,4101 gold badge10 silver badges7 bronze badges

This part you use in html

<input id="latitude" type="text" name="latitude"></p>

This is javaScript:

<script>
document.getElementById("latitude").value=25;
</script>

answered Jan 3, 2019 at 8:13

Amranur Rahman's user avatar

You can also try:

document.getElementById('theID').value = 'new value';

answered Sep 2, 2015 at 10:56

Bogdan Mates's user avatar

1

Direct access

If you use ID then you have direct access to input in JS global scope

myInput.value = 'default_value'
<input id="myInput">

answered Jun 26, 2020 at 16:11

Kamil Kiełczewski's user avatar

Kamil KiełczewskiKamil Kiełczewski

80.5k29 gold badges352 silver badges327 bronze badges

The following code work perfectly well:

var $div = ('#js-div-hour input');
$div.attr('value','2022/01/10');

answered Jan 6, 2022 at 13:13

mahmoud aoata's user avatar

  1. Change the Input Value Using the value Property in JavaScript
  2. Change the Input Value Using the setAttribute() Function in JavaScript

Change Input Value in JavaScript

This tutorial will discuss changing the input value using the value property or the setAttribute() function in JavaScript.

Change the Input Value Using the value Property in JavaScript

We use an input tag to get input from a user, and we can use the value property to change the input value. First of all, we need to get the element whose value we want to change using its id or name, and then we can use the value property to set its value to our desired value. To get an element in JavaScript, we can use the getElementById() or the querySelector() function. For example, let’s make a form with input and give it an id to get the element in JavaScript using the getElementById() and set its value using the value property. See the code below.

<!DOCTYPE html>
<html>
<head></head>
<body>
<form>
    <input type="text" id= "123" name="ABC" value="Some Value">
</form>
</body>
<script type="text/javascript">
var Myelement = document.getElementById("123");
console.log(Myelement.value);
Myelement.value = "New value";
console.log(Myelement.value);
</script>
</html>

Output:

In the above code, we used the document.getElementById() function to get the element using its id, and on the next line, we printed the current input value using the console.log() function. After that, we used the value property to set the input value to our desired value, and after that, we printed the new value on the console. You can also use the querySelector() function to select the element whose input value you want to change. For example, let’s repeat the above example using the querySelector() function. See the code below.

<!DOCTYPE html>
<html>
<head></head>
<body>
<form>
    <input type="text" id= "123" name="ABC" value="Some Value">
</form>
</body>
<script type="text/javascript">
var Myelement = document.querySelector('input[name="ABC"]');
console.log(Myelement.value);
Myelement.value = "New value";
console.log(Myelement.value);
</script>
</html>

Output:

In the above code, we used the querySelector() function to get the element.

Change the Input Value Using the setAttribute() Function in JavaScript

We can also use the setAttribute() function instead of the value property to set the input value. We can also use the forms() function instead of the getElementById() or querySelector() function to get the element using the form name and input name. For example, let’s repeat the above example with the setAttribute() and froms() function. See the code below.

<!DOCTYPE html>
<html>
<head></head>
<body>
<form name="FormABC">
    <input type="text" id= "123" name="ABC" value="Some Value">
</form>
</body>
<script type="text/javascript">
var Myelement = document.forms['FormABC']['ABC'];
console.log(Myelement.value);
Myelement.setAttribute('value','New value');
console.log(Myelement.value);
</script>
</html>

Output:

As you can see, the output of all these methods is the same, so you can use whatever method you like depending on your requirements.

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Sometimes we need to set a default value of the <input> element, This example explains methods to do so.

    Text Value Property: This property set/return the value of value attribute of a text field. The value property contains the default value, the value a user types or a value set by a script.

    Syntax:

    • Return the value property:
    textObject.value
    • Set the value property:
    textObject.value = text

    Property Values:

    • text: It specifies the value of the input text field.
    • attributeValue: This parameter is required. It specifies the value of the attribute to add.

    JavaScript setAttribute() Method: This method adds the specified attribute to an element and sets its specified value. If the attribute is already present, then it’s value is set/changed. 

    Syntax:

    element.setAttribute(attributeName, attributeValue)

    Parameters:

    • attributeName: This parameter is required. It specifies the name of the attribute to add.
    • attributeValue: This parameter is required. It specifies the value of the attribute to add.

    Example-1:This example sets the value of the input element to ‘textValue’ by Text Value property. 

    html

    <!DOCTYPE html>

    <html>

    <head>

        <title>

           Set the value of an input field.

        </title>

    </head>

    <body style="text-align:center;" id="body">

        <h1 style="color:green;">

                GeeksForGeeks

            </h1>

        <input type='text' id='id1' />

        <br>

        <br>

        <button onclick="gfg_Run()">

            click to set

        </button>

        <p id="GFG_DOWN" style="color:green;

                                font-size: 20px;

                                font-weight: bold;">

        </p>

        <script>

            var el_down = document.getElementById("GFG_DOWN");

            var inputF = document.getElementById("id1");

            function gfg_Run() {

                inputF.value = "textValue";

                el_down.innerHTML =

                    "Value = " + "'" + inputF.value + "'";

            }

        </script>

    </body>

    </html>

    Output:

    Set the value of an input field

    Set the value of an input field

    Example-2: This example sets the value of the input element to ‘defaultValue’ by setAttribute method. 

    html

    <!DOCTYPE html>

    <html>

    <head>

        <title>

            Set the value of an input field.

        </title>

    </head>

    <body style="text-align:center;" id="body">

        <h1 style="color:green;">

                GeeksForGeeks

            </h1>

        <input type='text' id='id1' />

        <br>

        <br>

        <button onclick="gfg_Run()">

            click to set

        </button>

        <p id="GFG_DOWN" style="color:green;

                                font-size: 20px;

                                font-weight: bold;">

        </p>

        <script>

            var el_down = document.getElementById("GFG_DOWN");

            var inputF = document.getElementById("id1");

            function gfg_Run() {

                inputF.setAttribute('value', 'defaultValue');

                el_down.innerHTML =

                    "Value = " + "'" + inputF.value + "'";

            }

        </script>

    </body>

    </html>

    Output:

    Set the value of an input field

    Set the value of an input field

    JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.

    Понравилась статья? Поделить с друзьями:

    Читайте также:

  • Как изменить значение input javascript
  • Как изменить значение final переменной java
  • Как изменить значение f на фотоаппарате
  • Как изменить значение context react
  • Как изменить значение combobox

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии