2013-07-09 61 views
0

我試圖同時使用<select>字段和<input type='text'>字段以及$ _GET方法。基本上,我希望能有這樣的事情:使用<select>和<input type ='text'>

<select> 
    <option name='artist'>Artist</option> 
    <option name='song'>Song</option> 
</select> 
<input type='text' name='value' /> 

然後希望它爲?artist=value?song=value重定向取決於所選擇的。我希望這是有道理的,任何幫助,將不勝感激。

+0

'<選擇name = 「artist_or_song」>'會給你'artist_or_song =藝術家和值= ...' – user20232359723568423357842364

+0

你在爲此使用ajax嗎? –

+0

目前我沒有使用Ajax,因爲我從來沒有真正看過它。 @First的答案 - 這不是我要找的,因爲我的搜索查詢,我需要的網址是?artist = value或?song = value。 –

回答

2

不,你不能那樣做。不直接。

您應該將name屬性附加到select元素。然後$_GET將包含your_select_name=option_value

然後只在後端關聯你的$_GET['type']$_GET['value']

<form method="GET"> 
<select name="type"> 
    <option value='artist'>Artist</option> 
    <option value='song'>Song</option> 
</select> 
<input type='text' name='value' /> 
</form> 

<?php 
    echo $_GET['type']; // 'artist' or 'song' 
    echo $_GET['value']; // value of text input 

P.S:如果您需要嚴格的形成有關您的網址,您可以提供兩個輸入和搭起一個簡單的JS腳本,將隱藏不相關的選擇的選擇輸入。

其實,這種想法要求有點闡述:

<form method="GET"> 
    <select id='type'> 
     <option name='artist'>Artist</option> 
     <option selected name='song'>Song</option> 
    </select> 
    <input class='inp' id='song' type='text' name='song' /> 
    <input class='inp' style='display:none' id='artist' type='text' name='artist' /> 
</form> 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> 
<script> 
    $('#type').change(function() { 
     $('.inp').val('').hide().prop('disabled', true); // hide and clear both inputs 
     $('#'+$('#type').val()).prop('disabled', false).show(); //show input corresponding to your select 
     // Note the prop('disabled') calls - you want to disable the unused input so it does not add an empty key to your query string. 
    } 
</script> 
+0

感謝您的深入響應,但我隨着您的第一個建議,它工作正常,我可以應付以及URL。謝謝你的幫助。 –

+0

@JordanLovelle,別提了,很高興能有幫助。 –

0

我想你應該把name屬性的<select>標籤。

<select name="Category"> 
    <option>Song</option> 
    <option>Artist</option> 
</select> 
<input type="text" name="Value"/> 

話,應該是很容易驗證什麼已經選擇 爲例(PHP):

if($_GET['Category'] == "Song") 
{ 
    //Do stuff here with $_GET['Value'] 
} 
else if($_GET['Category'] == "Artist") 
{ 
    //Do stuuf here with $_GET['Value'] 
} 
相關問題