1

I want to fetch value from the textfield and add to the listbox. Here is my jquery code

JS:-

{
$('#btn_AddToList').click(function(
{
    var select = document.getElementById('lst_Regions');
    var region = $('#txt_RegionName').val();

    if('' != region)
    {
        var newOption = document.createElement('option');

        newOption.text = region;
        newOption.value = region;

        if($.browser.msie)
        {
            select.add(newOption);
        }
        else
        {
            select.add(newOption, null);
        }
    }

    return false;
 });
});

here is my html code

html:

<input type="text" name="region" id="txt_RegionName" /><br />
<input type="button" name="add" id="btn_AddToList" value="add" class="btn btn-success" /></br />
<select size="10" id="lst_Regions" style="width: 500px;">
</select>

question: I cannot add the value of the txt_RegionName to the lst_Region ,where i am going wrong?

Thank you.

1

3 Answers 3

2
$('#btn_AddToList').click(function () {
    var val = $('#txt_RegionName').val();
    $('#lst_Regions').append('<option>' + val + '</option>');
    $('#txt_RegionName').val('').focus();
})

jsFiddle example

Sign up to request clarification or add additional context in comments.

3 Comments

Sorry to bother you again , but what if i have more than one text field?? can you please help..
So if you had a few text inputs and you want to fold them all into the same select? I'm not sure I follow, can you elaborate?
Currently i have 4 text-field.And i want to display it in the list box as sr_no) Asset_name 'Particular' Quantity at price cost.The coatted are the text-field. Can you do the same...
1

you can do this like:

$('#btn_AddToList').click(function(event)
{
    var region = $('#txt_RegionName').val();

    if(region && !$('#lst_Regions>option[value=' + region + ']').length){
        var newOption = $('<option value="' + region + '">' + region + '</option>');

        $('#lst_Regions').append(newOption);
    }

    //return false;
    event.preventDefault();
    event.stopPropagation();
 });

just to let you know, you can prevent it from duplicate values using:

$('#lst_Regions>option[value=' + region + ']').length

which has to be zero, and as you see I have added that to my answer.

Comments

1
    {
        $('#btn_AddToList').click(function()
        {
            var select = document.getElementById('lst_Regions');
            var region = $('#txt_RegionName').val();

            if ('' != region) {
                $(document.createElement('option')).text(region).val(region).appendTo(select);
            }
            return false;
        });
    };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.