I have a javascript that is to be used to tag text in a textarea when a user clicks a button. Right now I have only gotten it to work for one button. There are 8 buttons that need to be able to tag in total but I don’t want to repeat the same code over and over for each button id, so I tried a for loop but this didn’t work. I’m not quite sure why though.
These are the button ids: edit-button0, edit-button1, edit-button2, …,edit-button8
I’ve added an alert in the for loop to check the button id.
No matter which button I click later it says button id is edit-button8, and it adds the tag connected to that button.
Any ideas why this doesn’t work or how I should do it instead.
/*globals document*/
(function ($) {
"use strict";
$(document).ready(function () {
for (i=0;i<8;i++) {
$("#edit-button"+i).click(function () {
alert("#edit-button"+i);
var tag = $("#edit-button"+i).attr("value");
var id = "protocol"; /* id of textarea */
var element = document.getElementById(id); /* HTML element object */
var start = element.selectionStart; /* start pos of selection */
var end = element.selectionEnd; /* end pos of selection */
var text = element.value; /* whole text */
var prefix = text.substring(0, start); /* part before selection */
var selected = text.substring(start, end); /* selected text */
var suffix = text.substring(end); /* part after selection */
/* insert tags in selection */
selected = "["+tag+"]" + selected + "[/"+tag+"]";
/* update HTML object */
element.value = prefix + selected + suffix; /* selected text */
element.selectionStart = start; /* new start pos */
element.selectionEnd = start + selected.length; /* new end pos */
return false;
});
}
});
})(jQuery);
You could give all the buttons a class
.tagButtonsand then use.each()in jQuery to loop over them like thisEDIT –
As an alternative and to help in the future, i think the issue with your code was your for loop. Have a look at this jsFiddle example to show how the loop should look.