2015-11-03 24 views
1

我有4個下拉菜單,2個用於「From」目的地,2個用於「To」目的地。 我想要做的是根據下拉值更新#from div和#to div。如何根據下拉值更新div文本?

例如在「從」目的地,如果1和5被選擇,則#from必須顯示1 -> 5

這意味着,在選擇的1,它會顯示1 ->,直到用戶從第二下拉選擇並完成序列。

from 
<select id="from_country"> 
    <option value="1">1</option> 
    <option value="2">2</option> 
    <option value="3">3</option> 
</select> 

<select id="from_city"> 
    <option value="1">4</option> 
    <option value="2">5</option> 
    <option value="3">6</option> 
</select> 
<br> 
<br /> 
to 
<select id="to_country"> 
    <option value="1">7</option> 
    <option value="2">8</option> 
    <option value="3">9</option> 
</select> 

<select id="to_city"> 
    <option value="1">10</option> 
    <option value="2">11</option> 
    <option value="3">12</option> 
</select> 

<div id="from"></div> 
<div id="to"></div> 
+0

http://jsfiddle.net/uafrzqyo/ – villoui

回答

0
$('#from_country').change(function() { 
    var country = $('option:selected', this).val(); 
    var city = $('#from_city').val(); 
    $('#from').text(country + "->" + city); 

}) 
$('#from_city').change(function() { 
    var city = $('option:selected', this).val(); 
    var country = $('#from_country').val(); 
    $('#from').text(country + "->" + city); 

}) 


$('#to_country').change(function() { 
    var country = $('option:selected', this).val(); 
    var city = $('#to_city').val(); 

    console.log(country + "->" + city) 
    $('#to').text(country + "->" + city); 

}) 
$('#to_city').change(function() { 
    var city = $('option:selected', this).val(); 
    var country = $('#to_country').val(); 
    $('#to').text(country + "->" + city); 

}) 

試試這個

demo

0

你可以做這樣的事情。

$('#from_country').change(function() { 
    $('#from').text($('#from_country :selected').text() + '->' + 
$('#from_city :selected').text()); 
    }); 

$('#from_city').change(function() { 
    $('#from').text($('#from_country :selected').text() + '->' + 
$('#from_city :selected').text()); 
    }); 

$('#to_country').change(function() { 
    $('#to').text($('#to_country :selected').text() + '->' + 
$('#to_city :selected').text()); 
    }); 

$('#to_city').change(function() { 
    $('#to').text($('#to_country :selected').text() + '->' + 
$('#to_city :selected').text()); 
    }); 
0

這裏是一個簡單的解決方案:http://jsbin.com/huvilegeso/edit?html,js,output。我只做了「發件人」部分。 To部分非常相似。

var from = [null, '->']; 

$('#from_country').on('change', function() { 
    from[0] = $(this).val(); 
    renderFrom(from); 
}); 

$('#from_city').on('change', function() { 
    from[2] = $(this).val(); 
    renderFrom(from); 
}); 

function renderFrom(from) { 
    $('#from').html(from.join(' ')); 
}