Kurwyne Gayle
Kurwyne Gayle

Reputation: 35

Modify element based on select option

Hi All I've been searching all over the internet (not just stack overflow) and I can't find an answer directly. Maybe it's how I am searching? But here it is I have a select HTMl element (like the one in the example below). I am trying to use jquery (unless there is a better method) to update a paragraph section on my site depending on what is chosen in the selection.

example.

<select id ="work">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>

<p id="updatedparagraph">
updated text here.
updated text here.
updated text here
</p>

Pretty much by default it should start with A so the text in paragraph section is set to a default. But if the drop down is selected and set to B or C I want the text to change depending on which is chosen. Any ideas on how to get this done correctly?

Upvotes: 0

Views: 58

Answers (1)

DinoMyte
DinoMyte

Reputation: 8858

Based on the comments from OP, in order to show a corresponding paragraph section based on the value from the dropdown.

<select id ="work">
<option value="updatedparagraph">a</option>
<option value="updatedparagraph1">b</option>
<option value="updatedparagraph2">c</option>
</select>
<p id="updatedparagraph">
history will go.
history will go.
history will go.
history will go.
</p>
<p id="updatedparagraph1">
history will not  go.
history will not go.
history will not go.
history will not go.
</p>
<p id="updatedparagraph2">
history will never go.
history will never go.
history will never go.
history will never go.
</p> 



 <script>
    $(document).ready(function(){
    $('#work').change(function()
    {
      $('[id^=updatedparagraph]').hide();  // hide all paragraph tag that starts with id = updatedparagraph
      $('#' + this.value).show(); // extract the value from the dropdown , locate that paragraph with id = value and show it.
    }).change();  // trigger change event as soon as the dropdown is loaded - optional.


});
</script>

Example : http://jsfiddle.net/DinoMyte/X6jzs/31/

If you wish to dynamically insert a specific text into a single paragraph field, you can create a object with key-value pair.

var obj = {'a': 'Hello a', 'b': 'Hello b','c': 'Hello c'};

$('#work').change(function()
{
  $('#updatedparagraph').text(obj[this.value]);
}).change();

Example : http://jsfiddle.net/DinoMyte/X6jzs/42/

Upvotes: 1

Related Questions