hermann
hermann

Reputation: 6295

Change href value with JS from select box

I have this select box that gets its data from my DB. What I want to do is add Edit and Delete buttons next to my select box that will do the respective actions on the current selected option.

So I added two buttons that direct to php scripts that do all this work. My problem is with JavaScript where I need to update the elements of the buttons.

However my JS function doesn't work. It appears that it isn't even fired.

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;
}​

Upvotes: 1

Views: 5760

Answers (4)

Jignesh Rajput
Jignesh Rajput

Reputation: 3558

You just passed value rather than text on onchange function

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

You can try something like this :

 window.updateButtons = function(value) {

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

See Demo : http://jsfiddle.net/y5g42/46/

Upvotes: 0

Shadow Wizzard
Shadow Wizzard

Reputation: 66397

You have several problems with your logic and the fiddle itself.

Best way without using JavaScript library is to attach the onchange handler in the onload of the window and handle everything there:

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

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

    oDDL.onchange();
};

To have it work, add id="selectHotel" to the <select> element and remove the inline onchange from it.

Updated fiddle.

In your initial fiddle you didn't choose proper framework properties.

Note that I am calling the onchange manually one time to reflect the selected value, otherwise clicking the button before selecting other value won't work.

Upvotes: 1

maialithar
maialithar

Reputation: 3123

You can't use var as variable name - var is javascripts reserved word.

Upvotes: 2

SLaks
SLaks

Reputation: 888223

jsFiddle's onLoad option wraps your code in a callback function.
Therefore, your function definition isn't visible outside the code.

You need to select No Wrap instead.

Upvotes: 1

Related Questions