2012-04-30 19 views
0

我有這個選擇框從我的數據庫中獲取其數據。 我想要做的是在我的選擇框旁邊添加編輯和刪除按鈕,這些按鈕將對當前選定的選項執行相應的操作。用JS從選擇框中更改href值

因此,我添加了兩個按鈕,它們指向執行所有這些工作的php腳本。 我的問題是JavaScript需要更新按鈕的元素。

但是我的JS功能不起作用。 它似乎並沒有被解僱。

http://jsfiddle.net/y5g42/33/

HTML:

<select name='selectHotel' onChange='updateButtons(this.options[this.selectedIndex].text)'> 
    <option value="volvo.php">Volvo</option> 
    <option value="saab.php">Saab</option> 
    <option value="mercedes.php">Mercedes</option> 
    <option value="audi.php">Audi</option> 
</select> 
<a href='' id='editButton'><button>Edit</button></a> 
<a href='' id='deleteButton'><button>Delete</button></a> 

的JavaScript:

function updateButtons(var) { 
    element = document.getElementById('editButton'); 
    element.href = var; 
}​ 

回答

0

你的邏輯和小提琴本身有幾個問題。

不使用JavaScript庫

最好的辦法是附加onchange處理程序窗口的onload和處理所有的事情有:

window.onload = function() { 
    var oDDL = document.getElementById("selectHotel"); 

    oDDL.onchange = function updateButtons() { 
     var oLink = document.getElementById('editButton');  
     oLink.href = oDDL.value; 
    }; 

    oDDL.onchange(); 
}; 

有它工作,添加id="selectHotel"<select>元素和刪除內聯onchange從中。

Updated fiddle

在你最初的小提琴中,你沒有選擇合適的框架屬性。

注意,我調用onchange手動一次,以反映選定值,選擇其他值都將無法正常工作之前,否則單擊按鈕。

1

的jsfiddle的onLoad選項包裝你的代碼中的回調函數。
因此,你的函數定義在代碼之外是不可見的。

您需要改爲選擇No Wrap

2

您不能使用var作爲變量名 - var是javascript保留字。

0

你剛過價值,而不是文字上onchange功能

onChange='updateButtons(this.options[this.selectedIndex].value)' 

你可以嘗試這樣的事情:

window.updateButtons = function(value) { 

    element = document.getElementById('editButton'); 
    var url = window.location.href; 
    element.href = url + value; 
    console.log(element.href); 
} 

見演示http://jsfiddle.net/y5g42/46/