ChathuraG
ChathuraG

Reputation: 160

create a dynamic link with html select option value

I want to create a dynamic link, with the value selected from html . following is a sample code so far i could do.

<select name="sequence" id="sequence" onChange="document.getElementById('selectedValue').innerHTML = this.value;">
    <option>file1</option>
    <option>file2</option>
    <option>file3</option>

    </select>

    <a href="data/file1"><span id="selectedValue"></span></a>

How to create this link dynamically with selected option.

Upvotes: 0

Views: 2636

Answers (5)

Lin Yuan
Lin Yuan

Reputation: 538

function changeLink(val){
  document.getElementById('selectedValue').innerHTML = val;
  document.getElementById('link').href="data/"+val;
}
<select name="sequence" id="sequence" onChange="changeLink(this.value);">
  <option>file1</option>
  <option>file2</option>
  <option>file3</option>
</select>

<a id="link" href="data/file1"><span id="selectedValue"></span></a>

Upvotes: 4

dnetix
dnetix

Reputation: 330

Hi I really think on the separation of code so I just give you a solution for your problem in JSFiddle

https://jsfiddle.net/zjyLqLLx/

Here is your HTML, I just change the id on the "span" element to the "a" element in order to change the url too

<select name="sequence" id="sequence">
    <option>Default Text</option>
    <option>file1</option>
    <option>file2</option>
    <option>file3</option>

</select>
<a id="selectedValue" href="Hola">
    <span>Some Default Value</span>
</a>

And your javascript code

document.getElementById('sequence').addEventListener('change', function(){
    var selected = this.options[this.selectedIndex].text;
    var link = document.getElementById('selectedValue');
    link.innerHTML = selected;
    link.href = "data/" + selected;
});

It's already working on JSFiddle

Upvotes: 0

Joy
Joy

Reputation: 9550

Demo: JSFiddle.

<script>
    function change(e) {
        console.log(e.value);
        document.getElementById('selectedValue').innerHTML = e.value;
    }
</script>
<a href="data/file1"><span id="selectedValue"></span></a>

<select id="c1" onchange="change(this)">
    <option value="value-1">One</option>
    <option value="value-2">Two</option>
    <option value="value-3">Three</option>
</select>

Upvotes: 0

nancyolson531
nancyolson531

Reputation: 148

<select name="sequence" id="sequence" onChange="document.getElementById('selectedValue').innerHTML = this.value;
document.getElementById('myLink').href = 'data/' + this.value;">
<option>file1</option>
<option>file2</option>
<option>file3</option>

</select>

<a id="myLink" href="data/file1"><span id="selectedValue"></span></a>

See fiddle.

Upvotes: 0

Kevin Wheeler
Kevin Wheeler

Reputation: 1452

 onChange="document.getElementById('selectedValue').innerHTML = 'data/' + this.options[this.selectedIndex].text;"

Upvotes: 0

Related Questions