1

I have a select element, and two text boxes. When the user clicks a list option, the id and names (text) get populated in those two text boxes.

I want to be able to update the text portion of the select by the click of a button, making sure to update that of the id reflected in the text box. Here's what I've been working with:

HTML:

 <select name="categories" id="categories" multiple> <option value="1">Baby pictures</option> <option value="2">Animals</option> <option value="3">Nature</option> </select> <input type="text" name="catID" id="catID" /> <input type="text" name="selCat" id="selCat" /> <input type="button" id="update" value="update" /> 

jquery:

 $('#update').click(function() { var selID; var selCat; selID = $('#catID').val(); selCat = $('#selCat').val(); $('#categories').val(selID).text(selCat); }) 

I've tried several different things - this is the only one that actually has an effect on the list itself. Although, it completely empties it. heh

Any help would be appreciated.

4
  • 1
    can you share the html also Commented Feb 12, 2014 at 0:13
  • Unless #categories is a form field, .val won't work. What are you using the "id" stuff for? I don't understand what that value is to be used for Commented Feb 12, 2014 at 0:13
  • when the update button is clicked do you want to add a new option to the select element Commented Feb 12, 2014 at 0:14
  • about to post HTML. No, I don't want a new option to be added - I want the option of ID [x] to be updated to whatever is in the textbox. Commented Feb 12, 2014 at 0:16

1 Answer 1

1

If you want to add a new option to the select element when click on the update button then try

$('#update').click(function () { var selID; var selCat; selID = $('#catID').val(); selCat = $('#selCat').val(); $('#categories').append($('<option />', { val: selID, text: selCat })); }) 

To Update an existing item

$('#update').click(function () { var selID = $('#catID').val(); var selCat = $('#selCat').val(); $('#categories option[value="' + selID + '"]').text(selCat) }) 

Demo: Fiddle

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

4 Comments

I'm not looking to add a new option to the list, but to update an option. After selecting an option, the user can change the name of that option - clicking update should set that option in the list to its new name.
@wribit You want to change the text of an existing option whose value is specified in the value cat txtfield
I want to update the option whose value = the id in the catID textbox, and set it's option "i.e. baby pictures" to whatever is in the selCat textbox.
Perfect! thank you Arun, you've answered my question. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.