0

I need help adding a key value array for this jQuery code I came across. The code does exactly what I need, except I need multiple inputs unlike the single input it provides.

jQuery("#btn").on('click', function() {
    var caretPos = document.getElementById("txt").selectionStart;
    var textAreaTxt = jQuery("#txt").val();
    var txtToAdd = "stuff";
    jQuery("#txt").val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) );
});
<textarea id="txt" rows="15" cols="70">There is some text here.</textarea>
<input type="button" id="btn" value="OK" />

See here.

I want to have an array such as:

OK => stuff,
YES => more stuff,
NO => no stuff

I'm not that familiar with jQuery, please help.

2
  • is it intends three buttons with different value? Commented Feb 15, 2016 at 22:35
  • @RomanPerekhrest yes thats correct Commented Feb 15, 2016 at 22:38

1 Answer 1

1

Javascript doesn't have an arrays with string keys, only indexed arrays. But you can use an object for that purpose.
Change your code as shown below:

<textarea id="txt" rows="15" cols="70">There is some text here.</textarea>
<input type="button" class="btn" value="OK" />
<input type="button" class="btn" value="NO" />
<input type="button" class="btn" value="YES" />

$(".btn").on('click', function() {
    var caretPos = document.getElementById("txt").selectionStart;
    var textAreaTxt = $("#txt").val();
    var txtSet = {'ok' : 'stuff', 'yes' : 'more stuff', 'no' : 'no stuff'};
    var txtToAdd = txtSet[$(this).val().toLowerCase()];
    $("#txt").val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) );
});

Now you can easily extend the object txtSet due to the variety of possible buttons.

http://jsfiddle.net/3pg5zmqg/

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

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.