Скопируйте значение радио с помощью его идентификатора для ввода в качестве значения с помощью JavaScript
У меня есть код HTML следующим образом:
<input name="bid" type="radio" value="1" id="1234"/>
<input name="bid" type="radio" value="2" id="5678"/>
<input type="text" id="paymount" name="paymount" value=""/>
Желаемая функциональность:
Если флажок radio=1
установлен, значение поля paymount
будет отображаться как 1234
. Если флажок radio=2
установлен, значение поля paymount
будет отображаться как 5678
.
Я нашел сообщения в Stack Overflow, но многие из них связаны с скрытием текстового поля.
Ответы
Ответ 1
<form name="radioForm">
<input name="bid" type="radio" value="1" id="1234"/>
<input name="bid" type="radio" value="2" id="5678"/>
<input type="text" id="paymount" name="paymount" value=""/>
</form>
<script type="text/javascript">
var radio = document.radioForm.bid,
input = document.getElementById('paymount');
for(var i = 0; i < radio.length; i++) {
radio[i].onclick = function() {
input.value = this.id;
};
}
</script>
jsFiddle
Ответ 2
Используйте обработчик события изменений для прослушивания события.
// use `[].slice.call(document.querySelectorAll('[name="bid"]'))
// for older browser to covert NodeList to Array
// although check polyfill option of `ArrayforEach` for older browser
// or use simple `for` or `while` loop for iterating
// get all radio with the name,covert NodeList to array and iterate
Array.from(document.querySelectorAll('[name="bid"]')).forEach(function(ele) {
// add event handler to the element
ele.addEventListener('change', function() {
// update value of the input element
document.getElementById('paymount').value = this.id;
// if you are used `data-id="value" attribute instead of `id`
// then get the value using `this.dataset.id`
});
});
<input name="bid" type="radio" value="1" id="1234" />
<input name="bid" type="radio" value="2" id="5678" />
<input type="text" id="paymount" name="paymount" value="" />
Ответ 3
Я не уверен, что это лучшее решение, но следующее работает по мере необходимости.
var inputs = document.querySelectorAll('input[name="bid"]'),
paymount = document.getElementById('paymount');
// loop over element, and add event listener
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("change", onChange);
}
// callback
function onChange(){
paymount.value = this.id; // change paymount value to the selected radio id
}
<input name="bid" type="radio" value="1" id="1234"/>
<input name="bid" type="radio" value="2" id="5678"/>
<input type="text" id="paymount" name="paymount" value=""/>
Ответ 4
<script>
function getradio(i)
{
document.getElementById("paymount").value=i;
}
</script>
<input name="bid" type="radio" value="1" id="1234" onclick="getradio(1234)"/>
<input name="bid" type="radio" value="2" id="5678" onclick="getradio(5678)"/>
<input type="text" id="paymount" name="paymount"/>
Вы можете использовать JavaScript и вызвать функцию, используя событие onclick на радиокнопке и передать желаемое значение.