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" />
Related
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>
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!");
});
In my application I need to submit forms via JavaScript. I know that I can do that with this code:
[...document.querySelectorAll('form')].forEach(form => {
form.addEventListener('submit', e => {
//doing the processing here
e.preventDefault();
})
})
From the server I get completely generated forms as HTML, which I inject into the DOM (or delete them from there), whenever necessary. By doing so, the registered event handlers stop to work, because the form element is either deleted or not registered.
Is it possible to register a global »Submission Listener«, comparable to that:
window.addEventListener('click' e => { … });
what will never be removed if the DOM changes, or will I have to register the submission handlers each time the DOM changes?
Is not a dublicate, because the mentioned delegation strategy is what I am looking for, but not for click events, for submission events instead.
You can definitely catch submit events as they bubble up, so what you want can be achieved by listening from a parent element that is always present as the dynamic forms are added and removed. I like doing this thing with a wrapper element with an ID, as opposed to listening a the body or html level. Here's a very simple example using just vanilla js. Codepen here: http://codepen.io/bsidelinger912/pen/RGbWYb
HTML:
<div id="form-wrapper">
<h2>Form 1</h2>
<form id="form1">
<input name="test" placeholder="enter something" />
<input type="submit" value="submit" />
</form>
<h2>Form 2</h2>
<form id="form2">
<input name="test" placeholder="enter something" />
<input type="submit" value="submit" />
</form>
</div>
<button id="form-adder">
+ Add a form
</button>
Javascript
var formWrapper = document.getElementById('form-wrapper');
// capture the submit event in the parent div
formWrapper.addEventListener("submit", function(e) {
e.preventDefault();
console.log('submit captured');
var thisForm = e.srcElement || e.originalTarget;
console.log('form id:' + thisForm.id);
console.log(thisForm.test.value);
});
// dynamically add divs and see we can still capture the submit
var divNum = 3;
function addDiv(e) {
e.preventDefault();
formWrapper.innerHTML += '<h2>Form ' + divNum + '</h2>\
<form id="form' + divNum + '">\
<input name="test" placeholder="enter something" />\
<input type="submit" value="submit" />\
</form>';
divNum++;
}
document.getElementById('form-adder').addEventListener('click', addDiv);
I am editing some javascript that has a search box with a variable as follows
var secondSearchTerm = $('#2nd-search').val();
In the HTML code '2nd-search' has a placeholder 'Enter search term'
I also have a reset button that clears the search as follows:
$("#2nd-reset-btn").on("click", function () {
return myNetwork.resetSecondSearch();
})
What I would like to do is to get the search box to re-populate with the placeholder when reset is clicked. Right now the last entered term remains in the search box.
Any ideas on how I can edit the code to do this?
Many thanks!
hi refer this link https://plnkr.co/edit/EtLmby5BdD5Yn70EIBRD?p=preview
js
// Add your javascript here
$(function(){
$("#reset").on("click", function () {
return $('#username').val('');
});
});
html
<input type="text" name="name" id = "username" placeholder="uname"/>
<button id="reset">Reset </button>
All you need to do is set the value to blank & take the focus away from the input(As some browsers hide placeholder on focus). The placeholder will be visible again. Try the following:
$("#2nd-reset-btn").on("click", function () {
secondSearchTerm.blur();
return secondSearchTerm.val('');
})
You can do it with pure JS only
Given the initial value
function reset() {
var initialValue = 'Enter your search term.';
var query = document.getElementById('myquery');
query.value = initialValue;
}
<input type="text" id="myquery" />
<input type="button" id="reset" onclick="reset()" value="Reset" />
Given the placeholder
function reset() {
var query = document.getElementById('myquery');
query.value = '';
}
HTML
<input type="text" id="myquery" />
<input type="button" id="reset" onclick="reset()" value="Reset" />
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";
}
};