Javascript onclick input text value

Получить значение value из тега input | JavaScript

document.getElementById() — поиск по тегу с атрибутом id

id на веб-странице может быть присвоен только один раз одному тегу HTML Задача: нужно вывести значение выбранного цвета рядом с полем ввода:

idColor" placeholder="введите текст"/> rezultatColor">  

document.getElementsByName() — поиск по NodeList тегов с атрибутом name

Задача: прибавить значение только третьего включенного чекбокса, округлить до сотых и показать в формате 0.00 (с двумя знаками после запятой):
1.00

name="nameCheckbox" value="1"/> name="nameCheckbox" value="20"/> name="nameCheckbox" value="300.555" onclick="onclickCheckbox()"/> name="nameCheckbox" value="400"/> 1.00  Пояснения: имеется четыре тега input с name="nameCheckbox". [0] - это первый по счёту, соответственно, [2] будет третьим.
nameRadio" value="1" checked="checked"/> nameRadio" value="20"/> nameRadio" value="300"/> nameRadio" value="400"/> 1  

document.getElementsByClassName() — поиск по NodeList тегов с атрибутом class

 .classGreen < background: green; width: 130px; height: 130px; margin: 0 auto; transition: .5s; >.classRed 
class="classGreen">

document.body — поиск по тегу body

document.body.innerHTML = document.body.innerHTML.replace(/\u003Ch2/g, '\u003Ch3');" /> Пояснения: я меняю , потому что тег может содержать атрибуты.  пишу как специальный символ в JavaScript \u003C.

document.getElementsByTagName() — поиск по NodeList тегов

h3')[4].innerHTML = 'Скрипт сработал\(\)'"/> Скрипт сработал\(\) - это то, на что мы заменяем наш текст. Он выглядит как Скрипт сработал(). Куда же делись символы \? Они реализуют экранирование скобок, чтобы те были рассмотрены как текстовые символы, а не как код скрипта. 
 Li(); setInterval(Li,1000); function Li() < d = new Date(); var month=new Array("января","февраля","марта","апреля","мая","июня","июля","августа","сентября","октября","ноября","декабря"); var week=new Array("воскресенье","понедельник","вторник","среда","четверг","пятница","суббота"); document.getElementById('d').getElementsByTagName('li')[0].innerHTML='Дата: '+d.getDate()+' '+month[d.getMonth()]+' '+d.getFullYear()+' года, '+week[d.getDay()]; document.getElementById('d').getElementsByTagName('li')[1].innerHTML='Время: '+((d.getHours()

document.querySelector() — поиск по селектору

Задача: показать степень заполнения полей, пароль и email должен быть внесён правильно.
Почта
Пароль

 input:focus:invalid < border: 1px solid #eee; >input:invalid Почта  
Пароль " title="Не менее 6 знаков, в том числе хотя бы одна цифра и буква" onchange="oninputEmail()"/>
0%

document.querySelectorAll() — поиск по NodeList селекторов

Помните этот пример? Там поиск идёт только по h3. Именно на него произойдет замена по этой кнопке. Если её не нажимать, то скрипт не будет работать. А вот так будет и при h2, и при h3

h2, h3')[4].innerHTML = 'Скрипт сработал\(\)'"/>

11 комментариев:

Анонимный Здравствуйте!
У меня вот такой вопрос. Не подскажите.
Есть 2 поля и две кнопки.
Я хочу VALUE кнопок передать в поля.

Просто значение например 1 кнопки передать в 1 поле понятно. Но хотелось бы. Что бы в поле попадало значение кнопки которую нажал. Не важно 1 или 2 или 11.

Вот что-то начал но дальше…

form
input type=»text» value=»1″
input type=»text» value=»2″
/form

input name=»poga2″ type=»button» value=»L» onclick=»q.value = fun()»
input name=»poga3″ type=»button» value=»M»

script
function fun() var per1=document.getElementById(‘q’).value;
var per2=document.getElementById(‘x’).value;

/script
Буду очень благодарен за подсказку.
До свидания.
NMitra Здравствуйте, пример http://jsfiddle.net/NMitra/dhj7epc4/

Анонимный Здравствуйте!
Спасибо Вам за ответ. Спасибо за помощь.
Анонимный Здравствуйте!
Подскажите как перебрать список с помощью javascript :
ul
li1/li
li2/li
li3/li
li4/li
li5/li
li6/li
li7/li
/ul

script
var el = document.querySelector(‘li’);

Источник

How to Get and Set Input Text Value in JavaScript

On most web pages, it is required to get the input text value from the users in order to enter correct data and ensure data security. For instance, you need to get, set or store some specific data to use it for further processing. In such cases, getting and setting input text value in JavaScript becomes very helpful for protecting data privacy.

This write-up will demonstrate the methods to get and set input text values in JavaScript.

How to Get and Set Input Text Value in JavaScript?

To get and set input text value in JavaScript, utilize:

  • getElementById()” method
  • getElementByClassName()” method
  • querySelector()” method

Go through each of the mentioned methods one by one!

Method 1: Get and Set Input Text Value in JavaScript Using document.getElementById() Method

The “getElementById()” method accesses an element with the specified Id. This method can be applied to access the ids of the input fields and buttons for getting and setting the text value.

Here, “elementID” refers to the specified Id of an element.

The below example explains the discussed concept.

Example
Firstly, include two input type fields and separate buttons for getting and setting the input text values with the “onclick” events which will access the specified functions:

Then, get the value of the input field with the help of the document.getElementById() method:

Now, declare a function named “getAndSetText()”. Here, fetch the input field with the “getText” id and pass the input value to the next input field having “setText” id:

function getAndSetText ( ) {
var setText = document. getElementById ( ‘getText’ ) . value ;
document. getElementById ( ‘setText’ ) . value = setText ;
}

Similarly, define a function named “getText()”. After that, get the input field with “getText” id and pass the particular value to the alert box for getting the input text value:

function getText ( ) {
var getText = document. getElementById ( ‘getText’ ) . value ;
alert ( getText ) ;
}

Method 2: Get and Set Input Text Value in JavaScript Using document.getElementByClassName() Method

The “getElementByClassName()” method accesses an element with the help of the specified class name. This method, similarly, can be applied to access the class of the input field and buttons for entering and setting the text value.

In the above syntax, the “classname” represents the class name of elements.

Example
Similar to the previous example, we will first access the first input field with the “getText” class name. Then, define a function named “getAndSetText()” and get the specified input field based on its class name and set the value in the next input field:

document. getElementByClassName ( ‘getText’ ) . value = «Input Here» ;
function getAndSetText ( )
{
var setText = document. getElementByClassName ( ‘getText’ ) . value ;
document. getElementById ( ‘setText’ ) . value = setText ;
}

Likewise, define a function named “getText()”, add the class name of the first input field and pass the particular value to the alert box to display the fetched value:

function getText ( ) {
var getText = document. getElementByClassName ( ‘getText’ ) . value ;
alert ( getText ) ;
}

This implementation will yield the following output:

Method 3: Get and Set Input Text Value in Javascript Using “document.querySelector()” Method

The “document.querySelector()” fetches the first element that matches the specified selector, and the addEventListener() method can add an event handler to the selected element. These methods can be applied to get the id of the input field and buttons and apply an event handler to them.

Here, “CSS selectors” refer to one or more CSS selectors.

Look at the following example.

Example
Firstly, include input types with their placeholder values and buttons for getting and setting the input text values:

Next, fetch the added input fields and buttons using the “document.querySelector()” method:

let buttonGet = document. querySelector ( ‘#get’ ) ;
let buttonSet = document. querySelector ( ‘#set’ ) ;
let getInput = document. querySelector ( ‘#input-get’ ) ;
let setInput = document. querySelector ( ‘#input-set’ ) ;
let result = document. querySelector ( ‘#result’ ) ;

Then, include an event handler named “click” for both buttons to get and set the values, respectively:

buttonGet. addEventListener ( ‘click’ , ( ) => {
result. innerText = getInput. value ;
} ) ;
buttonSet. addEventListener ( ‘click’ , ( ) => {
getInput. value = setInput. value ;
} ) ;

We have discussed the simplest methods for getting and setting input text value in JavaScript.

Conclusion

To get and set input text value in JavaScript, utilize the “document.getElementById()” method or the

document.getElementByClassName()” method for accessing the specified input field and buttons based on their ids or class name and then set their values. Moreover, the “document.querySelector()” can also be utilized for getting and setting input text values in JavaScript. This blog explained the methods to get and set input text values in JavaScript.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.

Источник

Читайте также:  Установка бота телеграм python
Оцените статью