我有点卡在这里离开的地方。我希望我的单选按钮返回所选按钮的值。但是现在,它只返回第一项的价值。如何让它循环遍历所有值,这是我的代码。
<!DOCTYPE html>
<html>
<body>
<?php include 'db_connector.php';
$result = mysqli_query($con,"SELECT name FROM os_scope");
while($row = mysqli_fetch_array($result)) {
$row['name'];
echo "<input type='radio' name='os' value=".$row['name']." id='myRadio'>";
}
?>
<p>Click the "Try it" button to display the value of the radio button.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myRadio").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
答案 0 :(得分:1)
试试这个:迭代所有带名称=“os”的单选按钮,然后检查哪个属性为checked
属性为真。
注意 - id
必须是唯一的,因此对不同的单选按钮使用不同的id
。
function myFunction() {
var radiobutton = document.getElementsByName("os");
var x = '';
for(var i=0;i<radiobutton.length;i++)
{
if(radiobutton[i].checked)
x = radiobutton[i].value;
}
document.getElementById("demo").innerHTML = x;
}
答案 1 :(得分:1)
第一个:在while循环中元素Id应该是unqiue id='myRadio'
不会是唯一的。
我建议使用class(而不是id
)和jQuery(在javascript中使用for-css作为选择器):
function getSelectedRadioValue() {
alert($('.myRadio:checked').first().val());
}
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<input type='radio' name='os' value="1" class='myRadio'>1
<input type='radio' name='os' value="2" class='myRadio'>2
<input type='radio' name='os' value="3" class='myRadio'>3
<p>Click the "Try it" button to display the value of the radio button.</p>
<button onclick="getSelectedRadioValue()">Try it</button>
<p id="demo"></p>
</body>
</html>
Ajax是一个同步的服务器调用,它们返回您可以在网站上的jquery中使用的数据。例如:
function sendMessage() {
$.post("your url to serverside script you want to execute.php"
, { 'Index': 'Data Found in $_Post'} //in execute.php $_POST['Index'] will now contain: 'Data Found in $_Post'
, function(data) {
//in data will be the stuff you echo-ed in your php script (if you used json_encode($data) in php this will be automatically detected and converted to a javascript object.
$("$body").html(data); //for instance we get html from the AJAX call (execute.php) and insert in the #body div
}).fail(function(){
alert('The server returned an error'); //ofcourse server returns an error, because URL used in this example does not exist
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="body">
</div>
<button onclick="sendMessage()">execute AJAX call</button>
答案 2 :(得分:1)
<script>
function myFunction() {
var x = document.getElementsByName('os');
var rate_value;
for(var i = 0; i < x.length; i++){
if(x[i].checked){
rate_value = x[i].value;
break;
}
}
document.getElementById("demo").innerHTML = rate_value;
}
</script>