Asalan Asalan -4 years ago 170
Javascript Question

jquery: convert textarea (separated by new lines) to select option menu

this the demo jsfiddle

I have tried this :



$('.generate').click(function () {
$('.inthis').text('<select class="select" id="' + $('.select-menu').val() + '"><option>' + $('.text-area').val().split('\n') + '</option><option>' + $('.text-area').val().split('\n') + '</option><option>' + $('.text-area').val().split('\n') + '</option></select>');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="Text1" type="text" value="option_one" class="select-menu">
<br>
<textarea class="text-area" name="Text2" cols="40" rows="5" placeholder="enter one wdg in one line">green
yellow
blue</textarea>
<br>
<input class="generate" type="button" value="test" />
<br>
<br>
<div class="inthis"></div>





but it did not work.

I want to be like this :

<select class="select" id="option_one">
<option>green</option>
<option>yellow</option>
<option>blue</option>
</select>

Answer Source

$('.generate').click(function() {

var options = $('.text-area').val().split('\n')

  $('.inthis').html('<select class="select" id="' + $('.select-menu').val() + '"><option>' + options[0] + '</option><option>' +  options[1] + '</option><option>' +  options[2] + '</option></select>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="Text1" type="text" value="option_one" class="select-menu">
<br>
<textarea class="text-area" name="Text2" cols="40" rows="5" placeholder="enter one wdg in one line">green
yellow
blue</textarea>
<br>
<input class="generate" type="button" value="test" />
<br>
<br>
<div class="inthis"></div>

use .html() not .text()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download