javascript - How to set select element font name on click in div -


if text in div clicked, font name of select element shoudl displayed in select, example comic sans ms

i tried html

<select id="fs">   <option value=""></option>   <option value="verdana">verdana</option>   <option value="impact">impact</option>   <option value="comic sans ms">comic sans ms</option> </select>   <br/>  <div id="changeme" style='font-family:"comic sans ms"'>    click here</div> 

with javascript

$(function() {   $("#changeme").on('click', function() {     $('#fs').val($(this).css("font-family"));   });  }); 

after clicking in click here select element empty.

how fix font name comic sans ms appears in select? tried use tostring() in fiddle http://jsfiddle.net/0lce9ob9/8/

but select box still empty.

to change shown option based on css of div (rather other way around, understood previously) use following:

$("#changeme").on('click', function() {   var font = $(this).css("font-family");   $('#fs option[value=' + font + ']').prop("selected", true); }); 

simply changing value of select element won't accomplish want: need explicitly modify option want shown. option elements value of comic sans ms, use:

$("option[value='comic sans ms']") 

also, note when write id attribute in html, not include hash # mark. that's when selecting element in css. finally, whenever you're using font-family name contains spaces, must wrap in quotes. <div> should this:

<div id="changeme" style='font-family:"comic sans ms"'>click here</div> 

here's snippet:

$("#changeme").on('click', function() {    var font = $(this).css("font-family");    $('#fs option[value=' + font + ']').prop("selected", true);  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <select id="fs">    <option value=""></option>    <option value="verdana">verdana</option>    <option value="impact">impact</option>    <option value="comic sans ms">comic sans ms</option>  </select>      <br/>    <div id="changeme" style='font-family:"comic sans ms"'>      click here</div>


Comments