Add text on that field where cursor is with jquery - javascript

There are two fields, subject and description and I want to add text where the cursor is. It means, if cursor is on description, it should add text in description and if cursor is on subject, it should add text on subject field.
one field is #subject
other one is #description
How I can achieve it?
<button type="button" class="btn btn-light mb-1" onclick="insertText('ticket_id')">Ticket ID</button>
function insertText(text)
{
// here will be code
}
inputs
<textarea class="form-control form-control-solid" rows="4" id="description" name="description" placeholder="Description"></textarea>
<input type="text" class="form-control form-control-solid" placeholder="Subject" name="subject" value="" />

There is a document.activeElement property, which contains currently focused element, but this will already be changed when click event occurs, so you'll need to use mousedown event, which happens before the focus changes to the button.
Then, element.selectionStart can be used to determine the cursor location. If you also need to replace selected text in the input you should use this in combination with element.selectionEnd and modify the click handler accordingly.
Here is an example:
ticketIdButton = document.getElementById('ticketIdButton')
ticketIdInput = null
ticketIdInputCursorLocation = 0
// In mousedown event document.activeElement has not changed yet
// which allows to keep track of previously focused input
ticketIdButton.addEventListener('mousedown', function() {
activeElement = document.activeElement
// For simplicity, let's use ticketIdInput class to identify
// the acceptable inputs for ticket id
if (activeElement.classList.contains('ticketIdInput')) {
ticketIdInput = activeElement
ticketIdInputCursorLocation = activeElement.selectionStart
}
else {
ticketIdInput = null
}
})
ticketIdButton.addEventListener('click', function() {
ticketId = '#1234'
if (ticketIdInput !== null) {
ticketIdInput.value = ticketIdInput.value.substring(0, ticketIdInputCursorLocation) + ticketId + ticketIdInput.value.substring(ticketIdInputCursorLocation)
}
})
<textarea id="description" class="ticketIdInput" placeholder="Description"></textarea><br />
<input id="subject" class="ticketIdInput" placeholder="Subject"><br />
<hr>
<button type="button" id="ticketIdButton">Ticket ID</button>

Related

Stop focus event adding the stopPropagation method issue

I want to show only one alert when i focus on this textbar, i'm using the JS stop.Propagation() method to stop the event listener, this don't seems to work, i also want to avoid adding the html attribute "onFocus='' ".
Thank you.
const textbar = document.querySelector('#search');
textbar.addEventListener('focus', (event) => {
alert("hi");
event.stopPropagation();
});
<input type="text" name="search" id="search" placeholder="Search Employee Details" class="form-control" />
You can try to use a boolean variable to achieve that. Not sure it will work as you wish for the next focus (after you leave the input and focus it again).
const textbar = document.querySelector('#search');
let focused = false
textbar.addEventListener('focus', (event) => {
if(!focused) {
alert("hi");
focused=true
} else {
focused=false
}
});
<input type="text" name="search" id="search" placeholder="Search Employee Details" class="form-control" />

Validating Dynamically Added Form Inputs - Vanilla JS

I'm building a multipage form. On a few of the form's pages, I have questions that allow the user to add inputs dynamically if they need to add a job, or an award, etcetera. Here's what I'd like to do/what I have done so far.
What I Want to Do:
As the user adds fields dynamically, I want to validate those fields to make sure they have been filled in, and they are not just trying to move to the next page of the form with empty inputs.
After all the fields are successfully validated, a "Next" button at the bottom of the page, which up until this point was disabled, will become reenabled.
What I know How To Do
With some help, I've been able to workout a validation pattern for the inputs that are not dynamically added (such as First Name, Last Name) and I can extend this same logic to the first set of inputs that are not added dynamically. I have also worked out how to re-enable the "Next" button once all fields are good.
What I do Not Know How To Do
How do I write a function that extends the logic of the simple validation test to also check for dynamically added iterations.
http://codepen.io/theodore_steiner/pen/gwKAQX
var i = 0;
function addJob()
{
//if(i <= 1)
//{
i++;
var div = document.createElement("div");
div.innerHTML = '<input type="text" class="three-lines" placeholder="School Board" name="schoolBoard_'+i+'"> <input type="text" class="three-lines" placeholder="Position" name="position_'+i+'"> <input type="date" class="three-lines" name="years_'+i+'"> <input type="button" value="-" onclick="removeJob(this)">';
document.getElementById("employmentHistory").appendChild(div);
//}
}
function removeJob(div)
{
document.getElementById("employmentHistory").removeChild(div.parentNode);
i--;
};
function checkPage2()
{
var schoolBoard_1 = document.getElementById("schoolBoard_1").value;
if(!schoolBoard_1.match(/^[a-zA-Z]*$/))
{
console.log("something is wrong");
}
else
{
console.log("Working");
}
};
<div id="page2-content">
<div class="input-group" id="previousTeachingExperience">
<p class="subtitleDirection">Please list in chronological order, beginning with your most recent, any and all full-time or part-time teaching positions you have held.</p>
<div class="clearFix"></div>
<label id="teachingExpierience">Teaching Experience *</label>
<div id="employmentHistory">
<input type="text" class="three-lines" name="schoolBoard_1" id="schoolBoard_1" placeholder="School Board" onblur="this.placeholder='School Board'" onfocus="this.placeholder=''" onkeyup="checkPage2()" />
<input type="text" class="three-lines" name="position_1" placeholder="Position" onblur="this.placeholder='Position'" onfocus="this.placeholder=''" onkeyup="checkPage2()" />
<input type="date" class="three-lines" name="years_1" />
<input type="button" name="myButton" onclick="addJob()" value="+" />
</div>
</div><!--end of previousTeachingExperience Div -->
Instead of trying to validate each individual input element, I would recommend trying to validate them all at once. I believe that is what your checkPage2 function is doing.
You can add the onBlur event handler or the onKeyUp event handler you are currently using to all added inputs to run your form wide validation. This has the effect of checking each individual form element if it is valid so you know for sure you can enable the submit button.
Lastly, when removeJob is called, you should also run the form wide validation. It would look something like this:
function addJob()
{
i++;
var div = document.createElement("div");
div.innerHTML = '<input type="text" class="three-lines" placeholder="School Board" name="schoolBoard_'+i+'" onkeyup="checkPage2()"> <input type="text" class="three-lines" placeholder="Position" name="position_'+i+'" onkeyup="checkPage2()"> <input type="date" class="three-lines" name="years_'+i+'" onkeyup="checkPage2()"> <input type="button" value="-" onclick="removeJob(this)">';
document.getElementById("employmentHistory").appendChild(div);
}
function removeJob(div)
{
document.getElementById("employmentHistory").removeChild(div.parentNode);
i--;
checkPage2();
};
For every element that you make with document.createElement(...), you can bind to the onchange event of the input element, and then perform your validation.
Here's an updated version of your CodePen.
For example:
HTML
<div id="container">
</div>
Javascript
var container = document.getElementById("container");
var inputElement = document.createElement("input");
inputElement.type = "text";
inputElement.onchange = function(e){
console.log("Do validation!");
};
container.appendChild(inputElement);
In this case I'm directly creating the input element so I have access to its onchange property, but you can easily also create a wrapping div and append the inputElement to that.
Note: Depending on the freqency in which you want the validation to fire, you could bind to the keyup event instead, which fires every time the user releases a key while typing in the box, IE:
inputElement.addEventListener("keyup", function(e){
console.log("Do validation!");
});

Javascript onclick fails to send value while onfocus of text input

If a user clicks the save button as the next action after typing street data the onblur action intercepts the onclick and does not trigger the save. However, if you add some padding (30px) and click above the word save it works but below the word Save it does not work, the same as with no padding. I'm certain users will go right from typing text in the input field then click Save which will fail unless they first click somewhere else and then click Save. I’ve provide html and javascript example below. Is there a way using javascript to solve this issue?
<html>
<script>
function showstreet() {
var x = document.getElementById('street').value;
alert(x);
}
function focused() {
document.getElementById('title').style.display='';
document.getElementById('street').value='';
}
function blured() {
document.getElementById('title').style.display='none';
if (document.getElementById('street').value == '') {
document.getElementById('street').value='street';
}
}
</script>
<style>
.pad5 { padding:5px; }
.pad30 { padding:30px; }
</style>
<body>
<div id="title" class="pad5" style="display:none;">STREET NAME</div>
<div>
<input id="street" type="text" name="street" value="street" class="pad5"
onfocus="focused()" onblur="blured()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="showstreet()">
</div>
</body>
</html>
I converted this to jsfiddle but I'm not doing something right (newbie) https://jsfiddle.net/eyo63mav/26/
use onMouseDown instead of onClick in your save button. Then onMouseDown will be fired before onBlur
below is working code
function showstreet() {
var x = document.getElementById('street').value;
alert(x);
}
function focused() {
document.getElementById('title').style.display = '';
document.getElementById('street').value = '';
}
function blured() {
document.getElementById('title').style.display = 'none';
if (document.getElementById('street').value == '') {
document.getElementById('street').value = 'street';
}
}
<div id="title" class="pad5" style="display:none;">STREET NAME</div>
<div>
<input id="street" type="text" value="street" class="pad5" onfocus="focused()" onblur="blured()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="showstreet()">
</div>
Styling rarely makes a difference with events -- now, while that's a blanket statement and in lots of cases we find the styling of an inline element such as a link or a paragraph becoming problematic with inline events such as OnClick and OnFocus, in your case, adding thirty pixels to the size of a button is not your problem.
The problem with your code is that the variable you're assigning your #title's value to is local (it's inside the scope of showstreet(), of which can only be accessed by aforementioned function) -- nevermind that, it's never used again. You save a value to it, it alerts the user, and that's it -- it's never reassigned nor reused, so while it'll forever stay as the street name they entered, you'll never see it unless you apply it to something.
It took me a while to figure out what exactly you're trying to save, but I think I've managed it.
Here's the code I've created:
var streetValue = "Your street will appear here.";
function clickedField() {
// Init title
document.getElementById('title').innerHTML = streetValue;
// Reset field
document.getElementById('street').value = '';
}
function saveValue() {
// Reassign streetValue
streetValue = document.getElementById('street').value;
// Checking if value was left empty
if (streetValue === '') {
document.getElementById('title').innerHTML = "Error: No Street Entered!";
} else {
document.getElementById('title').innerHTML = streetValue;
}
}
(I'm not entirely sure what you had onblur for, but it should be very easy to insert back. If you need some help with that, comment on my reply, I'll be happy to.)
Now if we update the HTML with the approprate functions:
<div id="title" class="pad5" style="">STREET NAME</div>
<div>
<input id="street" type="text" name="street" value="street" class="pad5"
onfocus="clickedField()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="saveValue()">
</div>

Prevent certain elements from receiving focus

So I have the following function. What it does is listens for the focus event on all elements. If that element is either in $mobileMenu or $menuItems it permits it otherwise it removes the focus:
var $body = $("body");
var $mobileMenu = $("#mobile-menu");
var $menuItems = $("#main-menu a");
$body.on("focus.spf", "*", function(e){
e.stopPropagation();
$this = $(this);
// Prevent items from recieving focus and switching view
if (!$this.is($mobileMenu) && !$this.is($menuItems)) {
$this.blur();
} else {
console.log(this);
}
})
The issue I have is that this prevents the user from focusing on anything whatsoever if a normally focusable element that is now non-focusable precedes any of my white-listed elements as it just attempts to refocus on the same element over and over again.
Does anyone know how I can tell it to instead skip to the next focusable element?
If you set the tabindex to -1 on the element, it will ignore the tab.
Not sure if this works in all browsers but it works in Google Chrome.
<input type='text' value='regular'/>
<input type='text' tabindex="-1" value='with tabindex set to -1'/>
This works (updated) :
$body.on("focus.spt", "*", function(e){
$this = $(this);
if (!$this.is($mobileMenu) && !$this.is($menuItems)) {
$this.blur();
var next=$this.nextAll().find('a,input');
if (next.length>0) next[0].focus();
} else {
console.log('ok',this);
e.stopPropagation();
}
})
(updated) fiddle -> http://jsfiddle.net/CADjc/
You can see in the console which elements that receives focus (main-menu a and mobile-menu)
Tested on :
<input type="text" tabindex="1" value="test">
<span><input type="text" tabindex="2" value="test"></span>
<div><input type="text" id="mobile-menu" tabindex="3" value="mobile-menu"></div>
<div><span>
<div id="main-menu">
<a tabindex="4">main-menu</a>
<a tabindex="5">main-menu</a>
</div>
</span></div>
<span>
<input type="text" tabindex="6" value="test">
</span>
If you make something disabled, it won't receive focus. For example:
<input type="text" disabled="disabled" />
Do add it programmatically, you could do:
var el = document.getElementById('disableme');
el.setAttribute('disabled', 'disabled');
attr("readonly","readonly"), prevent input focus and value ARE send to the server.
CSS-only solution from one of my past projects
/* Prevents all mouse interactions */
.disabled-div {
opacity: 0.5;
pointer-events: none;
}
/* Prevents all other focus events */
.disabled-div:focus,
.disabled-div:focus-within {
visibility: hidden;
}
<h1>CSS Only Disable with Prevent Focus</h1>
<input placeholder="Normal text field">
<br><br>
<input class="disabled-div" placeholder="Disabled text field">
<br><br>
<input placeholder="Normal text field">
<br><br>
<input class="disabled-div" placeholder="Disabled text field">
<br><br>
Flickers slightly when it receives focus. That is because when it receives focus, visibility is set to 'hidden' and focus is lost and visibility is set back to 'visible' again. This is actually good because the user now has some idea where focus is while going over disabled fields...

How to clear text field on focus of text field

I want to clear the text field when the user clicks on that
<input name="name" type="text" id="input1" size="30" maxlength="1000" value="Enter Postcode or Area" onfocus=="this.value=''" />
Unless you are doing something specific where you only want to clear onclick, I would suggest (as others have noted) to use the onfocus actions instead. This way if someone is using tab to navigate it will also clear the default text.
You can also use onblur to check if it's empty to bring it back:
<input type="text" value="Default text" name="yourName" onfocus="if(this.value == 'Default text') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Default text'; }">
To do this you will need to use a scripting language, probably javascript. Here an example
<input type='text' value'Some text' onclick='javascript: this.value = ""' />
Hope this helps.
Edit:
To meet what David is explain here is a second example in case that is what you are looking for
<script type='javascript'>
var clear = true;
function clear(obj)
{
if(clear)
{
obj.value = '';
clear = false;
}
}
</script>
<input type='text' value'Some text' onfocus='clear(this);' />
Using jQuery library:
<input id="clearme" value="Click me quick!" />
$('#clearme').focus(function() {
$(this).val('');
});
Or you can simply use the placeholder attribute
For example<input name="name" type="text" id="input1" size="30" maxlength="1000" placeholder="Enter Postcode or Area"/>
You can use <input ... onfocus="this.value='';"/>.
This way, the field will be cleared when it gains focus. However, if you only want to clear it when user clicks on it (i.e. not when the field gains focus with the keyboard for example), then use onclick instead of onfocus.
However, as pointed by David Dorward in a comment, this behavior may not be expected by the user. So be careful to set this feature on really specific fields (such as search field).
This is how I use it for a temperature converter/calculator - when the user types (keyup), the text input box calculates using the assigned function; when the user selects the other text input (there are only two inputs), the selected text input will clear.
HTML:
<p class="celcius"><h2 style="color:#FFF">Input:</h2>
<input name="celsius" type="text" class="feedback-input" placeholder="Temperature (Celsius)" onkeyup="Conversion()" onfocus="this.value='';" id="celsius" />
</p>
<hr>
<h2 style="color:#FFF">Result:</h2>
<p class="fahrenheit">
<input name="fahrenheit" type="text" class="feedback-input" id="fahrenheit" onkeyup="Conversion2()" onfocus="this.value='';"placeholder="Temperature (Fahrenheit)" />
</p>
JavaScript:
function Conversion() {
var tempCels = parseFloat(document.getElementById('celsius').value);
tempFarh =(tempCels)*(1.8)+(32);
document.getElementById('fahrenheit').value= tempFarh;
}
function Conversion2() {
var tempFarh = parseFloat(document.getElementById('fahrenheit').value);
tempCels =(tempFarh - 32)/(1.8);
document.getElementById('celsius').value= tempCels;
}
try this ,it worked for me
add this into your input tag
<code>
onfocus="this.value='';"</code>
for example if your code is
<code>
<input type="text" value="Name" /></code>
use it like this
<code><input onfocus="this.value='';" type="text" value="Name" /></code>
function Clear (x) {if (x.cleared) {} else {x.value = ""; x.cleared = true}}
onfocus = "Clear (this)"
Add a following script to your js file:
var input1 = document.getElementById("input1")
input1.onfocus = function() {
if(input1.value == "Enter Postcode or Area") {
input1.value = "";
}
};
input1.onblur = function() {
if(input1.value == "") {
input1.value = "Enter Postcode or Area";
}
};

Categories