简体   繁体   English

如何从单选按钮输入字段中获取值? JS , jQuery

[英]How to get value from radio button input field? JS , jQuery

I have 2 radio buttons, the second is with input field.我有 2 个单选按钮,第二个是输入字段。 I need to get the value of the selected, and in case of the second, value from the input field.我需要从输入字段中获取选定的值,如果是第二个,则需要获取值。 The thing is, that when the second button is selected, its input value is empty until user types something there.问题是,当第二个按钮被选中时,它的输入值是空的,直到用户在那里输入一些东西。 As a result, I have always empty field.结果,我总是空场。

The markup and code is below标记和代码如下

<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
     }
    });

I cheked setTimeout but I am not sure how to implement it and maybe there is another solution我检查了 setTimeout 但我不确定如何实现它,也许还有另一种解决方案

You can use $("input").change()您可以使用 $("input").change()

So every time there is a change in value it will be taken所以每次价值发生变化时都会被采用

Examle:例子:

 //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" />

Could you use the change() function on your input ?你能在你的输入上使用 change() 函数吗? IT would trigger an event after a change has been made in the text input.在文本输入中进行更改后,IT 将触发一个事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM