如何从单选按钮输入字段中获取值? JS , jQuery
How to get value from radio button input field? JS , jQuery
我有 2 个单选按钮,第二个是带有输入字段的。
我需要从输入字段中获取所选值,如果是第二个值。
The thing is, that when the second button is selected, its input value is empty until user types something there.结果,我总是空着字段。
标记和代码如下
<input id="x" type="radio" name="re" value="Undefined" checked>No limit
<input id="y" type="radio" name="re" value="limit">Limit
<input id="y-input-radio" type="number" min="1" max="20" placeholder="Up to 20"/>
//tweet limit
$('input[type="radio"]').on('click', function(){
var value = $(this).val();
if(value === 'limit'){
var tweetLimit = document.getElementById('y-input-radio').value;
console.log(tweetLimit); //returns 0 cos its still empty
}
});
我检查了 setTimeout 但我不确定如何实现它,也许还有其他解决方案
您可以在输入中使用 change() 函数吗? IT 将在文本输入发生更改后触发事件。
您可以使用 $("input").change()
因此每次值发生变化时都会取值
示例:
//tweet limit
$('input[type="radio"]').on('click', function () {
var value = $(this).val();
if (value === 'limit') {
$("input").change(function () {
var tweetLimit = $('#y-input-radio').val();
console.log(tweetLimit);
});
} else {
$("input").off('change');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input id="x" type="radio" name="re" value="Undefined" checked>No limit
<input id="y" type="radio" name="re" value="limit">Limit
<input id="y-input-radio" type="number" min="1" max="20" placeholder="Up to 20" />
我有 2 个单选按钮,第二个是带有输入字段的。 我需要从输入字段中获取所选值,如果是第二个值。 The thing is, that when the second button is selected, its input value is empty until user types something there.结果,我总是空着字段。
标记和代码如下
<input id="x" type="radio" name="re" value="Undefined" checked>No limit
<input id="y" type="radio" name="re" value="limit">Limit
<input id="y-input-radio" type="number" min="1" max="20" placeholder="Up to 20"/>
//tweet limit
$('input[type="radio"]').on('click', function(){
var value = $(this).val();
if(value === 'limit'){
var tweetLimit = document.getElementById('y-input-radio').value;
console.log(tweetLimit); //returns 0 cos its still empty
}
});
我检查了 setTimeout 但我不确定如何实现它,也许还有其他解决方案
您可以在输入中使用 change() 函数吗? IT 将在文本输入发生更改后触发事件。
您可以使用 $("input").change()
因此每次值发生变化时都会取值
示例:
//tweet limit
$('input[type="radio"]').on('click', function () {
var value = $(this).val();
if (value === 'limit') {
$("input").change(function () {
var tweetLimit = $('#y-input-radio').val();
console.log(tweetLimit);
});
} else {
$("input").off('change');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input id="x" type="radio" name="re" value="Undefined" checked>No limit
<input id="y" type="radio" name="re" value="limit">Limit
<input id="y-input-radio" type="number" min="1" max="20" placeholder="Up to 20" />