Getelementbyid javascript form input

Получить значение 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 use getElementById to get the elements in a form

There are many ways of accessing form elements, of which the easiest is by using the cross-browser W3C DOM document.getElementById() method. Before we learn more about this method, it would be useful to know something about the Document Object Model (DOM), the concept of HTML nodes or elements, and the concept of containers. Each time you load an HTML page, the web browser generates an internal representation of the page in the form of an inverted tree structure. Let us look at a simple form. We will use this form later to demonstrate the use of the getElementById method.

Sample code Download the sample code here: getelementbyid-form-sample.zip

form name ="subscribe" id="subscribe_frm" action="#">  Your Name: input type="text" name="name" id="txt_name" />  Your Email: input type="text" name="email" id="txt_email" />  input type="button" name="submit" value="Submit" onclick="processFormData();" />  form> 

There are elements such as and containers like Each element can have attributes associated with it, such as:

input type="text" name="name" id="txt_name"> 

Here, the element has three attributes: type, name and id. The id attribute uniquely identifies this particular element.

Accessing Form Elements using getElementById

In order to access the form element, we can use the method getElementById() like this:

var name_element = document.getElementById('txt_name'); 

The getElementById() call returns the input element object with ID ’txt_name’ . Once we have the object, we can get the properties and call the methods of the object. For example, to get the value of the input element, get the value attribute.

var name = name_element.value; 

Similarly, it is possible to access the element:

var frm_element = document.getElementById ('subscribe_frm'); 

Example: access the form and input elements

See the demo. In this demo, we toggle the visibility of the form. This is done by accessing the form element which we have seen above and setting its display property as shown in the code below:

var frm_element = document.getElementById('subscribe_frm');  var vis = frm_element.style;  if (vis.display == '' || vis.display == 'none')   vis.display = 'block'; > else   vis.display = 'none'; > 

Example: Input validation

The code below makes sure that the field is not empty. First, we trim out any leading and trailing blank space.

 function trim (str)   return str.replace (/^\s+|\s+$/g, ''); > 

The code below validates the txt_name field.

var name_element = document.getElementById ('txt_name');  if (trim(name_element.value) == '')   alert ('Please enter your name'); > 

Checking for getElementById support

All modern browsers support getElementById() method. However if you are to support very old browsers, use the following function:

function getElement(id)   if (document.getElementById)   return document.getElementById(id);  > else if (document.all)   return window.document.all[id];  > else if (document.layers)   return window.document.layers[id];  > > 

Other Cross-browser ways of accessing form element objects

There are two other cross-browser ways of accessing form elements: document.getElementsByTagName and document.getElementsByName .

Using the document.getElementsByTagName Method

This method takes in as argument the name of a tag (element) and returns an array of all matching tags (elements) found in the document.

In our form example, if we had to get a reference to all the elements, we could use the following code:

var inputs = document.getElementsByTagName('input'); 

The variable inputs is a reference to an array of all elements including:

What if we only wanted to access elements with the type attribute as text? We could do it in the following way:

var inputs = document.getElementsByTagName("input"); var message = "The form has the following input elements with the 'type' attribute = 'text': \n\n";  for (var i = 0; i  inputs.length; i++)    if (inputs[i].getAttribute('type') == 'text')   message += inputs[i].tagName + " element with the 'name' attribute = '";  message += inputs[i].getAttribute('name') + "'\n";  > > alert(message); 

This time, the elements retrieved do not include the element: .

Using the document.getElementsByName Method

This method takes in as argument the name attribute value of elements to be retrieved and returns a collection of desired matching elements.

In the code snippet below, let us say we need to get a reference to the element with the name attribute mail_format.

select name="mail_format" id="slt_mail_format"> option value="TEXT">Plain Textoption> option value="HTML">HTMLoption>  select> 

We could access the desired element in this way:

var mail_format_elements = document.getElementsByName('mail_format'); 

Источник

Читайте также:  Как узнать тип питон
Оцените статью