2013-12-17 281 views
0

我在我的表單中有一個性別字段。使用javascript提交表單?

我已經給它相同的名稱,即「社會性別」,我給它相同的ID,即「社會性別」。

現在我要展示我選擇了這兩個選項。但是,使用相同的ID,它不起作用。我已將onclick事件應用於文本框,並且我希望它能夠在每次點擊該文本框時都顯示一條javascript警報,顯示我已選擇的內容,無論是男性還是女性。

請幫忙!

gender:<input type="radio" name="gender" id="gender" value="female"/>female 
     :<input type="radio" name="gender" id="gender" value="male" />male 

    <input type="text" name="textbox" onclick="check()" /> 



    <script type="text/javascript"> 
     function check() 
{ 

var a=document.getElementById("gender").value; 
alert(a); 
} 

</script> 

 function addUser() { 
//how to check what is the selected radio input 
alert(getCheckedRadioId('u_type')); 
    } 
     function getCheckedRadioId(name) { 
var elements = document.getElementsByName(name); 

for (var i=0, len=elements.length; i<len; ++i) 
    if (elements[i].checked) return elements[i].value; 
    } 


</script> 

    now this code alerts that what i have choosen but the problem is that i want the alert's value in a variable so that i could send this value to database...so how should i take the alerted value in a variable..... 
+0

WElcome to SO。下次,請結束你的句子,只有1。 ,而不是3或4.請記住試着寫下你的問題,以便讓這裏的人們更容易地深入你的問題! –

回答

2

你可能想看看這個: javascript selected radio

基本上,如果你有這樣的名字的問題將得到解決得到檢查無線電值的函數。從上面的鏈接採用:

var selected = ''; 
var elements = document.getElementsByName('gender'); 

for (var i = 0, i < elements.length; i++) 
{ 
    if (elements[i].checked) 
     selected = elements[i].value; 
} 

alert(selected); 

你也可以考慮使用jQuery。這對這樣的情況會有很大的幫助。

+0

for循環線顯示錯誤....怎麼辦nw – user2999062

+0

非常感謝您的幫助...它的工作非常好... thanxx很多 – user2999062

+0

您可能想檢查如果用戶選擇了任何東西。如果他沒有在這種情況下選定的值將是一個空字符串。您也可能希望將此答案標記爲已接受,以便其他人知道它的工作原理。 – MaGnetas

0

你的問題是,每個元素都必須有一個唯一的ID,你是給兩個元素相同的ID。我不確定哪一個getElementById()會返回。我假設第一個。

但是,你很確定給多個元素的名稱相同。然後,您可以使用getElementsByName()來檢索包含這兩個元素的數組,並且可以返回該元素的Checked屬性是否已設置。