创建URL开始选择下拉列表

时间:2015-03-17 00:17:06

标签: javascript php jquery

我有两个选择框(下拉列表),我需要创建一个开始这些下拉菜单的网址。例如:

<form name="states_cities">
<select name="states">
<option value="ac">Acre</option>
<option value="rj">Rio de Janeiro</option>
<option value="sp">São Paulo</option>
<option value="to">Tocantis</option>
</select>

<!-- cities of "Rio de Janeiro" -->
<select name="cities"> 
<option value="queimados">Queimados</option>
<option value="volta-redonda">Volta Redonda</option>
<option value="nova-iguacu">Nova Iguaçú</option>
</select>

<button type="submit" value="Go">
</form>

我需要制作这个网址示例:

http://ValueState.ValueCity.domain.comhttp://rj.queimados.domain.com

当用户点击GO!

有什么更好的方法可以做到这一点?

3 个答案:

答案 0 :(得分:1)

要获得选定的选项,您应该以这种方式使用jQuery :selected selector

&#13;
&#13;
$('#go').on('click', function(){
    var city = $('#cities option:selected').text();
    var state = $('#states option:selected').text();
    var newLocation = 'http://' + state + '.' + city + '.domain.com';
    // window.location = newLocation;
    alert(newLocation);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="states" id="states">
    <option value="ac">Acre</option>
    <option value="rj">Rio de Janeiro</option>
    <option value="sp">São Paulo</option>
    <option value="to">Tocantis</option>
</select>

<!-- cities of "Rio de Janeiro" -->
<select name="cities" id="cities"> 
    <option value="queimados">Queimados</option>
    <option value="volta-redonda">Volta Redonda</option>
    <option value="nova-iguacu">Nova Iguaçú</option>
</select>

<button type="submit" id="go">Go</button>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如果你想使用jquery库,请试试这个,演示@ FIDDLE

<强> JS

$('#go').on('click', function(){
    var state = $('[name="states"] :selected').val();
    var city = $('[name="cities"] :selected').val();
    var url = 'http://' + state + '.' + city + '.domain.com?state=' + state +'&city=' + city;
    alert(url);
    window.location = url;
});

答案 2 :(得分:0)

function make_url() {
states = document.getElementsByTagName("select")[0];
selected_state = states.options[states.selectedIndex].value;
cities = document.getElementsByTagName("select")[1];
selected_city = cities.options[cities.selectedIndex].value;

    url='http://'+selected_state+'.'+selected_city+'.'+'domain.com';
alert(url);    

}

go=document.getElementById('go');
go.addEventListener('click',make_url);

Vanilla js ...演示:http://jsfiddle.net/ofkLxy0r/