Set focus after a particular item in an inputbox in jquery/javascript - javascript

So lets say I have an input box that looks something like this:
<input id="fuzzyname" value="" placeholder="&Fuzzybear">
I want to use javascript/JQuery so that when I click in that input box it will put the cursor after the & and the placeholder becomes the value in the input box.
This is kind of what I have so far:
$("#fuzzyname").focus(function () {
var value = $(this).attr("placeholder");
var symbol = "&";
var cursorIndex = value.indexOf(symbol);
//This is where I want to output the value into the inputbox with the cursor after cursorIndex
});

var cursorIndex = value.indexOf(symbol) + 1;
$(this).val(value);
this.setSelectionRange(cursorIndex, cursorIndex);

Related

How to get the index of a char that is clicked in a input field?

Is there a way to get the index of a character that is clicked on inside an input field?
For example, in an input field the value: "abc" is put.
and I click on the input field specifically on the "b".
I would like to know that the click was handled on index 1;
I have searched through the mouse event that is fired with an onClick and onFocus but couldn't find anything useful. The closest is the x and y position of the mouse click. But then you need to make an estimation on where the mouse would have clicked. And that won't be accurate once the input field is overflowing.
Here is an example:
const inp = document.querySelector('#t1');
inp.addEventListener('click', e => {
console.log(e.target.selectionStart);
});
<input type="text" id="t1" value="abcd">
This example is based on this post
You might be looking for inputElement.selectionStart and InputElement.selectionEnd
I did a quick JSFiddle, hope it's what's you're looking for:
const input = document.getElementById("one");
const text = document.getElementById("mousepos");
const selectHandler = (evt) => {
const starts = evt.target.selectionStart;
const ends = evt.target.selectionEnd;
const textSelected = evt.target.value.slice(starts, ends);
text.innerHTML = starts + " - " + ends + " <br/> Text: "+ textSelected;
}
input.addEventListener('click', selectHandler);
input.addEventListener('mousedown', selectHandler);
input.addEventListener('mouseup', selectHandler);
https://jsfiddle.net/12ow9br7/2/

How can I prevent users input to be cloned in the appended input box in javascript

When I insert some thing in the input box of module 1 and click add module button to clone the required elements that I need it clones also the inserted input I've tried to prevent that using event.preventDefault(); but it's still copying the input box with the inserted input from module 1 however, I can't clear it using the clear button that is located in the input box moreover the appended select options doesn't work and when I select an option it doesn't change.
Here is my demo of what's happening:-
http://jsfiddle.net/0ojjt9Lu/6/
and here is my javascript code:
$(document).ready(function(){
$("#Sadd").click(function(event) {
event.preventDefault();
var lastId = $("#modules h1").length;
var $newLabel = $("#module-1-label").clone();
var $newSc = $("#module-1-scredit").clone();
var $newSgrade = $("#module-1-sgrade").clone();
$newLabel.html("<h1>Module " + (lastId+1) + ":</h1>");
$newSc.find("label").attr("for", "Sc"+(lastId+1));
$newSc.find("input").attr("name", "Sc"+(lastId+1)).attr("id", "Sc"+(lastId+1));
$newSgrade.find("label").attr("for", "Sgrade"+(lastId+1));
$newSgrade.find("select").attr("name", "Sgrade"+(lastId+1)).attr("id", "Sgrade"+(lastId+1));
$("#modules").append($newLabel, $newSc, $newSgrade);
});
$("#Sremove").click(function() {
var lastId = $("#modules h1").length;
if(lastId > 5){
var lastLi = $("#modules h1").last().closest("li");
var lastLi2 = lastLi.next("li");
var lastLi3 = lastLi2.next("li");
lastLi.remove();
lastLi2.remove();
lastLi3.remove();
}
});
});
Use .val("") on the new input to clear the data in on the clone
or do $(clone).find('input').val(""); if there is more than one input
In your case with the select box you need to add the following lines
After you declare (or on the same line) the variables
var $newSc = $("#module-1-scredit").clone().find('input').val("");
var $newSgrade = $("#module-1-sgrade").clone().find('option:selected').removeAttr('selected');
$newSgrade.find('option[value="-1"]').attr('selected',true);
Edit: Had to handle the reselection of the select due to default value being "-1" however you may need to look at the cloning of this select element. Perhaps on the page have the blank question hidden and just clone that.

changing text for a selected option only when its in selected mode

I am not sure if I confused everyone with the above title. My problem is as follows.
I am using standard javascript (no jQuery) and HTML for my code. The requirement is that for the <select>...</select> menu, I have a dynamic list of varying length.
Now if the length of the option[selectedIndex].text > 43 characters, I want to change the option[selectecIndex] to a new text.
I am able to do this by calling
this.options[this.selectedIndex].text = "changed text";
in the onChange event which works fine. The issue here is once the user decides to change the selection, the dropdownlist is showing the pervious-selected-text with changed text. This needs to show the original list.
I am stumped! is there a simpler way to do this?
Any help would be great.
Thanks
You can store previous text value in some data attribute and use it to reset text back when necessary:
document.getElementById('test').onchange = function() {
var option = this.options[this.selectedIndex];
option.setAttribute('data-text', option.text);
option.text = "changed text";
// Reset texts for all other options but current
for (var i = this.options.length; i--; ) {
if (i == this.selectedIndex) continue;
var text = this.options[i].getAttribute('data-text');
if (text) this.options[i].text = text;
}
};
http://jsfiddle.net/kb7CW/
You can do it pretty simply with jquery. Here is a working fiddle: http://jsfiddle.net/kb7CW/1/
Here is the script for it also:
//check if the changed text option exists, if so, hide it
$("select").on('click', function(){
if($('option#changed').length > 0)
{
$("#changed").hide()
}
});
//bind on change
$("select").on('change', function(){
var val = $(":selected").val(); //get the value of the selected item
var text = $(':selected').html(); //get the text inside the option tag
$(":selected").removeAttr('selected'); //remove the selected item from the selectedIndex
if($("#changed").length <1) //if the changed option doesn't exist, create a new option with the text you want it to have (perhaps substring 43 would be right
$(this).append('<option id="changed" value =' + val + ' selected="selected">Changed Text</option>');
else
$('#changed').val(val) //if it already exists, change its value
$(this).prop('selectedIndex', $("#changed").prop('index')); //set the changed text option to selected;
});

Html Code not working properly while generated with JavaScript

I am trying to impliment the IN Place Editing functionality using JQuery.
Here is the code
editinplace.js
$(document).ready(function() {
//When div.edit me is clicked, run this function
$("div.editme").click(function() {
//This if statement checks to see if there are
//and children of div.editme are input boxes. If so,
//we don't want to do anything and allow the user
//to continue typing
if ($(this).children('input').length == 0) {
//Create the HTML to insert into the div. Escape any " characters
var inputbox = "<input type='text' class='inputbox' value=\""+$(this).text()+"\">";
//Insert the HTML into the div
$(this).html(inputbox);
//Immediately give the input box focus. The user
//will be expecting to immediately type in the input box,
//and we need to give them that ability
$("input.inputbox").focus();
//Once the input box loses focus, we need to replace the
//input box with the current text inside of it.
$("input.inputbox").blur(function() {
var value = $(this).val();
$(".editme").text(value);
});
}
});
});
ButtonClickFunction.js
function ADDRADIOBUTTON(){
//Creating the div Tag
var answer_div = document.createElement("div");
answer_div.setAttribute("class", "answer");
answer_div.id = "answer_div_"+counter;
// Creating the Radio button tag
var answer_tag = document.createElement("input");
answer_tag.setAttribute("type", "radio");
answer_tag.id = "answer_tag_"+counter;
answer_tag.setAttribute("name", answer_div.id);
// Creating the Label Tag
var radio_label_tag = document.createElement("label");
radio_label_tag.setAttribute("for", answer_tag.id);
//Creating the label
var In_Place_Edit_div = document.createElement("div");
In_Place_Edit_div.setAttribute("class", "editme");
var In_Place_Edit = document.createTextNode("label");
In_Place_Edit_div.appendChild(In_Place_Edit);
radio_label_tag.appendChild(In_Place_Edit_div);
// Adding Radio button dot on the div and screen actually
answer_div.appendChild(answer_tag);
//Adding the Label here on the right of radio button.
answer_div.appendChild(radio_label_tag);
// Adding Answer div to the main div
var element=document.getElementById("divid_"+counter);
element.appendChild(answer_div);
}
and the index.php file includes these two JS files along with jquery-1.8.2.min.js
<script language="javascript" src="js/jquery-1.8.2.min.js"></script>
<script language="javascript" src="js/editinplace.js"></script>
<script type="text/javascript" src="js/ButtonClickFunction.js"></script>
What I am trying to do is create a radio button with label besides it and the label can be edited when we click on it. Now the problem here is that when I use the Code
<div class="editme">Please click me!!</div>
directly in the index.html page it works fine but when I try to generate the same line of code dynamically as I shown in ButtonClickFuction.js file it Does not work. What might be the problem ?
After crerating the HTML element dynamically you must bind the click function once more.Otherwise it wont work.Just call the click function after dynamic creation of the
< div class="edttime">Please click me!!.Otherwise click wont work for the newly created div with class edttime.
$("div.editme").click(function() {
//This if statement checks to see if there are
//and children of div.editme are input boxes. If so,
//we don't want to do anything and allow the user
//to continue typing
if ($(this).children('input').length == 0) {
//Create the HTML to insert into the div. Escape any " characters
var inputbox = "<input type='text' class='inputbox' value=\""+$(this).text()+"\">";
//Insert the HTML into the div
$(this).html(inputbox);
//Immediately give the input box focus. The user
//will be expecting to immediately type in the input box,
//and we need to give them that ability
$("input.inputbox").focus();
//Once the input box loses focus, we need to replace the
//input box with the current text inside of it.
$("input.inputbox").blur(function() {
var value = $(this).val();
$(".editme").text(value);
});
}

Shuffle selected text on <textarea> using JavaScript

When I select some texts on the <textarea> using my mouse, how can I shuffle/scramble it by clicking on a button?
I've searched for something similar to what I want here on SO, and I saw some who use substring, selectionStart, and selectionEnd.
What I want is: when I select some texts with my mouse, it will be shuffled/scrambled when I click on a button, and the rest of the texts on the <textarea> that are not selected should remain untouched/intact.
I just want to perform an action on the selected texts.
It's more similar to a rich text editor like when you select on some texts, then click on bold button, the selected texts will become bold.
P.S.
It should be shuffled by individual characters.
EDIT:
Got it! I just needed to separate the selection string. My code works now. This is very helpful - https://stackoverflow.com/a/9605191/1101391
Unfortunately, IE 9 and below does not support selectionStart and selectionEnd properties on <input> and <textarea>. Here's the solution that worked for me - https://stackoverflow.com/a/9276457/1101391
You have access to the full text and know the substring where the selection starts and ends. Try something like this:
var txtArea = document.getElementById("foo");
var before = txtArea.value.substr(0, txtArea.selectionStart);
var selection = txtArea.value.substr(txtArea.selectionStart, txtArea.selectionEnd + 1);
var after = txtArea.value.substr(txtArea.selectionEnd, txtArea.value.length);
txtArea.value = before + scrambleThisString(selection) + after;
Suppose you name the textarea with ID content:
var textarea = document.getElementById('content');
var content = textarea.value;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var before = content.slice(0, start);
var after = content.slice(end);
var selected = content.substring(start, end);
selected = shuffleStringByMagic(selected);
textarea.value = before + selected + after;

Categories