Заполнение input из кнопки

340
25 июня 2017, 17:15

Гуглил ,но не нашел подходящего ответа. Как заполнить inputили textarea из кнопки. Допустим есть кнопки с цифрами 1,2,3 и т д. При нажатии на соответствующую кнопку с цифрой в поле инпута или текстового поля появлялся нужная цифра. Например при нажатии на кнопку с номером 1 появлялся 1 при нажатии на кнопку с номером 2 появлялся 2 ...и т д. И при нажатии на другую кнопку или ссылку это значение не исчезало. Дело в том что поле инпут заполняется из разных источников. Если коротко обьяснить то вышеуказанная кнопка добавляет номер зуба, а есть ещё и ссылки с диагнозами должно получится примерно так : Выбран зуб №1, диагноз кариес и т д... Здесь слово выбран зуб №1 заполняется из кнопки то что указал выше, а диагноз кариес заполняется из ссылки которые я зараее подготовил. Для ссылки код такой :

<li><a href="javascript:void(0)" 
onClick="document.getElementById('jaloby').value = 'Кариес' ;">1</a></li>

И + Как его сделать чтоб он и через кнопку работал ?

Answer 1

function addTextToInput(anElement) { 
  var text = document.getElementById('jaloby').value; 
  if (text != "") 
    text += ","; 
  text += anElement.innerText; 
  document.getElementById('jaloby').value = text; 
}
<input id="jaloby" /> 
<br/> 
<button type="button" onclick="addTextToInput(this)">1</button> 
<button type="button" onclick="addTextToInput(this)">2</button> 
<button type="button" onclick="addTextToInput(this)">3</button>

Answer 2

<li> 
  <a href="#" onClick="document.getElementById('jaloby').value = 'Кариес'">1</a> 
</li> 
 
<input id="jaloby"/>

<li> 
  <a href="" onClick="document.getElementById('jaloby').value = 'Кариес'; return false">1</a> 
</li> 
 
<input id="jaloby"/>

<li> 
  <a href="javascript:void(document.getElementById('jaloby').value = 'Кариес')">1</a> 
</li> 
 
<input id="jaloby"/>

<li> 
  <a href="javascript:(function(){document.getElementById('jaloby').value = 'Кариес'})()">1</a> 
</li> 
 
<input id="jaloby" />

Answer 3

;(function ($window) { 
   'use strict'; 
 
    var textTemplate = 'Выбран зуб №$1, диагноз $2;\n'; 
 
    var insertAfter = function (elem, refElem) { 
    	var parent = refElem.parentNode; 
    	var next = refElem.nextSibling; 
    	if (next) { 
    		return parent.insertBefore(elem, next); 
    	} else { 
    		return parent.appendChild(elem); 
    	} 
    }; 
 
    var brand = $window.brand = { 
       init: function (parentElement, toothCount, diagnoseList) { 
    		var self = this; 
 
    		var container = $window.document.createElement('div'); 
    		container.classList.add('container'); 
 
    		var input = $window.document.createElement('textarea'); 
    		input.classList.add('input'); 
 
    		container.appendChild(input); 
    		insertAfter(container, parentElement); 
 
    		for (var i = 1; i <= toothCount; i++) { 
    			var button = $window.document.createElement('button'); 
    			button.setAttribute('data-number', i); 
    			button.classList.add('btn-number'); 
    			button.innerText = i; 
    			button.addEventListener('click', function () { 
    			   self.textTemplate = textTemplate.replace('$1', this.dataset.number); 
    			}); 
    			container.appendChild(button); 
    		} 
    		for (var i = 0; i < diagnoseList.length; i++) { 
    			var button = $window.document.createElement('button'); 
    			button.setAttribute('data-diagnose', diagnoseList[i]); 
    			button.classList.add('btn-diagnose'); 
    			button.innerText = diagnoseList[i]; 
    			button.addEventListener('click', function () { 
    			   if (self.textTemplate) { 
    				 input.value += self.textTemplate.replace('$2', this.dataset.diagnose); 
    				 self.textTemplate = ''; 
    			   } 
    			}); 
    			container.appendChild(button); 
    		} 
    	}, 
    	textTemplate: '', 
    	defaultDiagnoseList: ['Альвеолы', 'Галитоз', 'Кариес'] 
    } 
})(window); 
 
brand.init(window.document.body, 32, brand.defaultDiagnoseList);
.container { 
	margin: 20px auto; 
	width: 450px; 
} 
.container .input { 
	width: 100%; 
	resize: vertical; 
	min-height: 100px; 
	border-radius: 4px; 
} 
.container .btn-number { 
	background-color: #fff; 
	color: #929292; 
	border: 1px solid #aaa; 
	border-radius: 4px; 
	padding: 4px; 
	margin: 2px; 
	outline: none; 
} 
.container .btn-diagnose { 
	background-color: #fdd; 
	color: #555; 
	border: 1px solid #aaa; 
	border-radius: 4px; 
	padding: 4px; 
	margin: 2px; 
	outline: none; 
}

READ ALSO
В чем отличие __proto__ от prototype

В чем отличие __proto__ от prototype

Пытаюсь разобраться с наследованием в js и никак не могу понять для чего нужен prototype если есть __proto__Как я понял(из того материала что изучал),...

1133
Событие при изменении переменной

Событие при изменении переменной

Мне нужно событие которое выполняется при изменении переменной

288
Почему не срабатывает popover при hover?(bootstrap 3)

Почему не срабатывает popover при hover?(bootstrap 3)

Хочу реализовать popover, который будет содержать в себе кнопки меню и не будет исчезать, если на него навести курсорНаткнулся на такие варианты:

249
Правильно ли я понял рекурсию?

Правильно ли я понял рекурсию?

Неделю боролся с осознанием рекурсии, изучаю учебник LearnJavascript

240