On click, press enter to textbox

72 views Asked by At

There is a combobox and if I click to an option, the value going to copied to a textbox. I want to writing these option values one under the other.

This is the javascript code:

$('#subcategory1').on('change', function() {
    $('#properties').val($('#properties').val() + '' + $(this).val() + ' ');
})

I tried with ' + keyCode==13', but it's not work. Help me!

2

There are 2 answers

0
Ole Spaarmann On BEST ANSWER

This is an example if you want to add the value of the subcategory element to a textarea. You can use the newline character \n instead of the HTML element <br>

$('#subcategory1').on('change', function() {
    $('#properties').val($('#properties').val() + "\n" + $(this).val());
});

HTML:

<textarea name="properties" id="properties"></textarea>  
0
Cagatay Ulubay On

So there are two ways to archieve that.

The first way would be to use the ul-List-Tag and append li-Child-Tags to them with the clicked value.

But if you want to use the textbox, you have to seperate the current value with the new ones and add \n returns between them.

HTML

Select your products: 

<select id="products">
    <option>iPhone</option>
    <option>PC</option>
    <option>Xbox One</option>
    <option>Stack Underflow</option>
    <option>Someone your like</option>
</select>

<br>
<br>

Your selected products:

<br>
<br>

<ul id="selected_products"></ul>

<textarea id="selected_products_textarea"></textarea>

javascript - One script to rule them all

var ul = document.getElementById('selected_products');
var textarea = document.getElementById('selected_products_textarea')

document.getElementById('products').onchange = function() {

    // UL List Part
    var li = document.createElement('li');
    li.innerHTML = this.value;

    ul.appendChild(li);

    // Textarea Part
    textarea.innerHTML = textarea.innerHTML.length == 0 ? this.value : textarea.innerHTML + '\n' + this.value;

}

JSFiddle: http://jsfiddle.net/kuwc6kte/1/

Now you can go further and remove the selected item from the select list or check if the current selected option is already in the list and go on.. whatever your requirements are in your script.


EDIT

Just saw you using jQuery, here a jQuery Solution with the same HTML:

jQuery

var ul = $('#selected_products');
var textarea = $('#selected_products_textarea');

$('#products').on( 'change', function() {

    // UL List Part
    var li = $('</li>');
    li.html( $(this).val() );

    ul.append(li);

    // Textarea Part
    textarea.html( textarea.html().length == 0 ? $(this).val() : textarea.html() + '\n' + $(this).val() );

});

JSFiddle: http://jsfiddle.net/kuwc6kte/3/