0

I am writing a script that grabs values from an autocomplete form and adds them to a hidden field, which is then processed in php and the values are added to the DB.

var oldVal = $("#models").val();
$("#models").val(oldVal+","+ searchcode);

Instead of overwriting the previous values i need it to store comma separated like this. Say its 4 clicks it should be value="123,1234,12345,123456" but instead it only stores the last value twice as such value="123456,123456" Any ideas?

2
  • Can you show more context to this? Where is searchcode determined? Is this all within some function? IF so, show the whole function so it can be determined if there are scoping or hoisting issues. Commented Aug 10, 2012 at 16:03
  • I feel its similar to stackoverflow.com/questions/10944765/… ? which is asked before Commented Apr 19, 2013 at 8:47

2 Answers 2

3

Made a little improvement:

function appendWords()
{
    var resultObj = $("#result");
    var outputObj = $("#textbox");
    var stringToAppend = resultObj.val().length > 0 ? resultObj.val() + "," : "";
    resultObj .val( stringToAppend + outputObj.val() );
}

See this working: http://jsfiddle.net/95hzx/1/

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

2 Comments

Follow up question, is there anyway to now search through the value field to delete specific keys?
Use indexOf() into value string, searching for the desired key to find a starting position. Then remove the chars between starting position plus the lenght of key. Got it?
2

Write it in plain JS

document.getElementById('models').value += "," + searchcode;

Remember that jQuery is a tool to "write less - do more" As soon as you have a situation that requires you to write more it stops being the useful tool for the job.

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.