Click - Add text - Active textbox - javascript

I would like to add text to the active textbox when a button is clicked.
I have read many threads explaining how it is done when one is wishing to add to a specific textbox but nothing on simply adding text to whichever text field is active...
Any help would be appreciated. Thanks.

The below is a solution for a virtual keyboard.
Pure JS + HTML:
function bind() {
var keyArr = document.getElementsByClassName('key');
for(var i = 0; i < keyArr.length; i++) {
keyArr[i].addEventListener('click', function() {
document.getElementById('textinput').value += this.innerHTML;
});
}
var capsLock = document.getElementById('capslock');
capsLock.addEventListener('click', function() {
for(var i = 0; i < keyArr.length; i++) {
if(capsLock.capsactive) {
keyArr[i].innerHTML = keyArr[i].innerHTML.toLowerCase();
} else {
keyArr[i].innerHTML = keyArr[i].innerHTML.toUpperCase();
}
}
capsLock.capsactive = !capsLock.capsactive;
});
}
<body onload='bind()'>
<input id='textinput'><br>
<button class='key'>q</button>
<button class='key'>w</button>
<button class='key'>e</button>
<button class='key'>r</button>
<button class='key'>t</button>
<button class='key'>y</button><br>
<button id='capslock' capsactive=false>CapsLock</button>
</body>
You can access a textbox's value by element.value or by $(selector).val().
For changing, use: element.value = newvalue; (JS) or $(selector).val(newvalue); (jQuery).
In the example, ...addEventListener... attaches a function to each button. The function, here, changes the value of the textinput textbox, to be the previous value + the text of the button which was pressed.
For instance, if the even the capsLock button is given the class key, on clicking capsLock, the text "Caps Lock" will be appended to the textbox.
Note: This solution covers adding text to a definite field. If there are multiple textbox-es present on the page, and the text has to be added to the currently focused one, a different approach has to be taken:
var lfl = -1, capsactive = false;
$(document).ready(function() {
$('*').blur(function() {
lfl = this;
});
$('.key').click(function() {
if($(lfl).hasClass('vkballowed')) {
$(lfl).val($(lfl).val() + $(this).html());
$(lfl).focus();
}
});
$('#capslock').click(function() {
capsactive = !capsactive;
if(capsactive == true) {
$('.key').each(function() {
$(this).html($(this).html().toUpperCase());
});
} else {
$('.key').each(function() {
$(this).html($(this).html().toLowerCase());
});
}
$(lfl).focus();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<input id='input0' class='vkballowed'><p>Editable</p><br>
<input id='input1' class='vkballowed'><p>Editable</p><br>
<input id='input2'><p>Not Editable</p><br>
<button class='key'>q</button>
<button class='key'>w</button>
<button class='key'>e</button>
<button class='key'>r</button>
<button class='key'>t</button>
<button class='key'>y</button><br>
<button id='capslock'>CapsLock</button>
Example instructions: Focus on the Editable text-fields, then press a key on the virtual-keyboard, so that corresponding text is appended to the fields. The virtual-keyboard doesn't work on the Not Editable text-field.
Here, the last element on the page that lost focus (was blurred) is stored in a variable. Next, whenever a key on the virtual-keyboard is pressed, first, it is checked whether the keyboard is allowed on that control, then the button's text is appended to the control, and finally, the control is given its focus back. Note that if the class vkballowed is added to controls such as buttons, no action would be effective on those controls. On other controls such as textareas, which have a value property, the virtual-keyboard will be functional.
The above approach isn't wholly correct. If, for instance, a key on the virtual-keyboard is pressed right after some other interactive button on the page, that button would receive focus again (this may not re-cause the action attached to that button, though). It, hopefully, gives you a starting point though.

jquery
$('#buttonId').click(function(event) {
$('.tstboxClass').val('heelo i am text box value.');
})

Related

Best way to combine multiple functions for clarity?

I have a text input box which does 3 things, it begins with the button 'Report A Bug' when it is closed, upon clicking it opens a text box & the Report A Bug button becomes 'Close'. I now want to combine the code from all JS below to work with with the following HTML Button, but I can't see a clear way to move forward on this. When I've tried my functionality has disappeared, or button simply no longer changes text.
Button HTML.
<button id="myBtnToReportABug" onclick="toggleReportForm()" type="button" class="btn btn-secondary float-right">{{#if report_form_closed }} Report A Problem {{else}} Close {{/if}}</button> </div>
JS:
// changes text on 'report problem' button when form open
function change() {
var theButton = document.getElementById("myBtnToReportABug");
if (theButton.innerHTML == "Close")
theButton.innerHTML = "Report A Problem";
else
theButton.innerHTML = "Close";
}
// clears text field onclick
function clearFields() {
document.getElementById("nameInput").value = "";
}
// changes text on 'submit' back to original button text when report is made
function changeSecond() {
var theButton = document.getElementById("myBtnToReportABug");
if (theButton.innerHTML == "Close")
theButton.innerHTML = "Report A Problem";
}
function toggleReportForm() {
var report_form_closed = document.getElementById("myBtnToReportABug");
}
try using addEventListener;
eg.
function callback(){
//all the functions call them here
}
document.getElementById("myBtnToReportABug").addEventListener(callback)

How to enter text into a input without using input.value

I have an existing app which requires a user to answer questions using an input box. I did not code this app and I do not want to mess around with the apps code. I have created a virtual on screen numpad from buttons which when pressed add the corresponding value to the input box using '.value'. This does 'work' and the numbers do appear in the input box but they are not saved by the existing code meaning that they mustn't be capturing the '.value'.
Is there some easy way of essentially.. simulating a user inputting text
function geet (clicked_value) {
var input = document.querySelector(".pt-subpage-current input");
if (input.value.length < 3) {
input.value += clicked_value;
}
}
function removeValue() {
var input = document.querySelector(".pt-subpage-current input");
var length = input.value.length;
if (length > 0) {
input.value = input.value.substring(0, length-1);
}
}
<input type="button" onClick="geet(this.value)" value="7" class="button
number" id="num7" />
You can use div with content editable true ,if that works for you.This is for your simulating part in your question
function edit()
{
let te=document.getElementById("textdiv").textContent;
console.log(te)
}
<div id="textdiv" contenteditable="true">Hello, edit me!</div>
<button onclick="edit()">Button</button>
I literally just made a numpad for someone here. all you need to do is use the showKeyPad() in an onclick event and give the fields id's. Let me know if you need help.
EDIT: Sorry just realized you said it is not saving .value.
This keypad uses the .value.

Use XPath or onClick or onblur to select an element and use jQuery to blur this element

*UPDATE:I am new to jQuery, as well as using XPath, and I am struggling with getting a proper working solution that will blur a dynamically created HTML element. I have an .onblur event hooked up (doesn't work as expected), and have tried using the $(document.activeElement), but my implementation might be incorrect. I would appreciate any help in creating a working solution, that will blur this element (jqInput) when a user clicks anywhere outside the active element. I have added the HTML and jQuery/JavaScript below.
Some ideas I have had:
(1) Use XPath to select a dynamic HTML element (jqInput), and then use jQuery's .onClick method to blur a this element, when a user clicks anywhere outside of the area of the XPath selected element.
(2) Use the $(document.activeElement) to determine where the .onblur should fire:
var thisTitle = input0;
var activeElement = $(document.activeElement);
if (thisTitle != activeElement) {
jqInput.hide();
_layout.viewHeaderTextInput.inputOnBlurHandler(canvasObj, jqHeaderText, jqInput);
}
I am open to all working solutions. And hopefully this will answer someone else's question in the future.
My challenge: Multiple elements are active, and the .onblur does not fire. See the image below:
NOTE: The <input /> field has focus, as well as the <div> to the left of the (the blue outline). If a user clicks anywhere outside that <input />, the blur must be applied to that element.
My Code: jQuery and JavaScript
This is a code snippet where the variable jqInput and input0 is created:
var jqInput = null;
if (jqHeaderText.next().hasClass("inline-editable"))
{
//Use existing input if it already exists
jqInput = jqHeaderText.next();
}
else
{
//Creaet a new editable header text input
jqInput = $("<input class=\"inline-editable\" type=\"text\"/>").insertAfter(jqHeaderText);
}
var input0 = jqInput.get(0);
//Assign key down event for the input when user preses enter to complete entering of the text
input0.onkeydown = function (e)
{
if (e.keyCode === 13)
{
jqInput.trigger("blur");
e.preventDefault();
e.stopPropagation();
}
};
This is my .onblur event, and my helper method to blur the element:
input0.onblur = function ()
{
_layout.viewHeaderTextInput.inputOnBlurHandler(canvasObj, jqHeaderText, jqInput);
};
inputOnBlurHandler: function (canvasObj, jqHeaderText, jqInput)
{
// Hide input textbox
jqInput.hide();
// Store the value in the canvas
canvasObj.headingText = jqInput.val();
_layout.updateCanvasControlProperty(canvasObj.instanceid, "Title", canvasObj.headingText, canvasObj.headingText);
// Show header element
jqHeaderText.show();
_layout.$propertiesContent.find(".propertyGridEditWrapper").filter(function ()
{
return $(this).data("propertyName") === "Title";
}).find("input[type=text]").val(canvasObj.headingText); // Update the property grid title input element
}
I have tried using the active element, but I don't think the implementation is correct:
var thisTitle = input0;
var activeElement = $(document.activeElement);
if (thisTitle != activeElement) {
jqInput.hide();
_layout.viewHeaderTextInput.inputOnBlurHandler(canvasObj, jqHeaderText, jqInput);
}
My HTML code:
<div class="panel-header-c">
<div class="panel-header-wrapper">
<div class="panel-header-text" style="display: none;">(Enter View Title)</div><input class="inline-editable" type="text" style="display: block;"><div class="panel-header-controls">
<span></span>
</div>
</div>
</div>
I thank you all in advance.

jQuery: focusout triggering before onclick for Ajax suggestion

I have a webpage I'm building where I need to be able to select 1-9 members via a dropdown, which then provides that many input fields to enter their name. Each name field has a "suggestion" div below it where an ajax-fed member list is populated. Each item in that list has an "onclick='setMember(a, b, c)'" field associated with it. Once the input field loses focus we then validate (using ajax) that the input username returns exactly 1 database entry and set the field to that entry's text and an associated hidden memberId field to that one entry's id.
The problem is: when I click on the member name in the suggestion box the lose focus triggers and it attempts to validate a name which has multiple matches, thereby clearing it out. I do want it to clear on invalid, but I don't want it to clear before the onclick of the suggestion box name.
Example:
In the example above Paul Smith would populate fine if there was only one name in the suggestion list when it lost focus, but if I tried clicking on Raphael's name in the suggestion area (that is: clicking the grey div) it would wipe out the input field first.
Here is the javascript, trimmed for brevity:
function memberList() {
var count = document.getElementById('numMembers').value;
var current = document.getElementById('listMembers').childNodes.length;
if(count >= current) {
for(var i=current; i<=count; i++) {
var memberForm = document.createElement('div');
memberForm.setAttribute('id', 'member'+i);
var memberInput = document.createElement('input');
memberInput.setAttribute('name', 'memberName'+i);
memberInput.setAttribute('id', 'memberName'+i);
memberInput.setAttribute('type', 'text');
memberInput.setAttribute('class', 'ajax-member-load');
memberInput.setAttribute('value', '');
memberForm.appendChild(memberInput);
// two other fields (the ones next to the member name) removed for brevity
document.getElementById('listMembers').appendChild(memberForm);
}
}
else if(count < current) {
for(var i=(current-1); i>count; i--) {
document.getElementById('listMembers').removeChild(document.getElementById('listMembers').lastChild);
}
}
jQuery('.ajax-member-load').each(function() {
var num = this.id.replace( /^\D+/g, '');
// Update suggestion list on key release
jQuery(this).keyup(function(event) {
update(num);
});
// Check for only one suggestion and either populate it or clear it
jQuery(this).focusout(function(event) {
var number = this.id.replace( /^\D+/g, '');
memberCheck(number);
jQuery('#member'+number+'suggestions').html("");
});
});
}
// Looks up suggestions according to the partially input member name
function update(memberNumber) {
// AJAX code here, removed for brevity
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
document.getElementById('member'+memberNumber+'suggestions').innerHTML = self.xmlHttpReq.responseText;
}
}
}
// Looks up the member by name, via ajax
// if exactly 1 match, it fills in the name and id
// otherwise the name comes back blank and the id is 0
function memberCheck(number) {
// AJAX code here, removed for brevity
if (self.xmlHttpReq.readyState == 4) {
var jsonResponse = JSON.parse(self.xmlHttpReq.responseText);
jQuery("#member"+number+"id").val(jsonResponse.id);
jQuery('#memberName'+number).val(jsonResponse.name);
}
}
}
function setMember(memberId, name, listNumber) {
jQuery("#memberName"+listNumber).val(name);
jQuery("#member"+listNumber+"id").val(memberId);
jQuery("#member"+listNumber+"suggestions").html("");
}
// Generate members form
memberList();
The suggestion divs (which are now being deleted before their onclicks and trigger) simply look like this:
<div onclick='setMember(123, "Raphael Jordan", 2)'>Raphael Jordan</div>
<div onclick='setMember(450, "Chris Raptson", 2)'>Chris Raptson</div>
Does anyone have any clue how I can solve this priority problem? I'm sure I can't be the first one with this issue, but I can't figure out what to search for to find similar questions.
Thank you!
If you use mousedown instead of click on the suggestions binding, it will occur before the blur of the input. JSFiddle.
<input type="text" />
Click
$('input').on('blur', function(e) {
console.log(e);
});
$('a').on('mousedown', function(e) {
console.log(e);
});
Or more specifically to your case:
<div onmousedown='setMember(123, "Raphael Jordan", 2)'>Raphael Jordan</div>
using onmousedown instead of onclick will call focusout event but in onmousedown event handler you can use event.preventDefault() to avoid loosing focus. This will be useful for password fields where you dont want to loose focus on input field on click of Eye icon to show/hide password

Getting siblings value with javascript

I create a textarea and a button on a loop based on a certain condition:
while($row_c= mysqli_fetch_array($result_comments))
{
//some code goes here
<textarea type="text" id="pm_text" name="text"></textarea><br>
<button name="send_comment" id="post_comment" class="button" onClick="post_pm_comment()">Post</button>
}
Now in my function "post_pm_comment" I would like to access the text written in the textarea when the post button is clicked.
I tried this, but it only gives me the text of the first textarea and button created:
function post_pm_comment(thidid, pm_id, path, pm,getter)
{
var pm_text = document.getElementById("pm_text").value;
}
What should I do?
Thank you
Your code is outputting an invalid DOM structure, because id values must be unique on the page. You cannot have the same id on more than one element. Remove the id values entirely, you don't need them.
Having done that, the minimal-changes answer is to pass this into your handler:
onClick="post_pm_comment(this)"
...and then in your handler, do the navigation:
function post_pm_comment(postButton)
{
var pm_text;
var textarea = postButton.previousSibling;
while (textarea && textarea.nodeName.toUpperCase() !== "TEXTAREA") {
textarea = textarea.previousSibling;
}
if (textarea) {
pm_text = textarea.value; // Or you may want .innerHTML instead
// Do something with it
}
}
Live Example | Source

Categories

Resources