D.Bell D.Bell - 5 months ago 9
jQuery Question

How to change text based on option selected?

This is probably simple but I can't work it out.

I want to be able to change some paragraph text based on which option is selected.

HTML

<form action="">
<select name="" id="">
<option id="1" value="One">One</option>
<option id="2" value="Two">Two</option>
<option id="3" value="Three">Three</option>
</select>
</form>
<br />
<p>Text</p>


JQ

$("#1").click(function(){
$("p").html("Changed!");
});


Here's the pen:

https://codepen.io/anon/pen/qNawgv

Answer

You can't trigger a option element by clicking! It all have to do with the selector element. You check if an option is selected and the selecet element automatically get the value of the selected option element.

<form action="">
<select name="" id="slct">
  <option id="1" value="One">One</option>
  <option id="2" value="Two">Two</option>
  <option id="3" value="Three">Three</option>
</select>
</form>
<br />
<p>Text</p>

jQuery

$('#slct').change(function(){ // when a option is selected
  //$("p").html($('#slct').val()); // pushs html code in P element
  $("p").text("Changed!");
  /*
    anyway you should use $.text if you don't have HTML element to push in
  */
});