iv got a really simple javascript question. Ill be using query for parts of it here but there are akin ways of doing it via javascript. basically, I'm writing a little script that makes it so when you click a text box with a value in it, it will take out the value so your can type (ex for most username boxes they have a little note in there). there are probably much better ways of doing this (i can already think of some) so feel free to suggest them as well. anyways I got that part running easily, the problem is that whenever a user clicks again all the data is removed, so if they just want to adjust something they can't. to solve this (ill show code in sec) i put a check variable and an if. this is what it looks like. (it doesn't work, btw)
var unumber = 0;
var pnumber = 0;
if(unumber<1){
$('#username').click(function(){
unumber = 1;
$('#username').val('');
});
};
if(pnumber<1){
$('#password').click(function(){
$('#password').val('');
pnumber = 1;
});
};
what I'm assuming happens is that every time some one clicks the variables are reset, and this leads to a more general question if this is this case, why would the whole script, not just the event handler, run? Im new to javascript so forgive me if this is a stupid question. Anyways, this is a really simple script and there are better and more efficient ways to do it, but how can it be done this way?
Your check for number less than 1, should be within the click handler
var unumber = 0;
var pnumber = 0;
$('#username').click(function(){
if(unumber<1){
unumber = 1;
$('#username').val('');
}
});
$('#password').click(function(){
if(pnumber<1){
pnumber = 1;
$('#password').val('');
}
});
Note that this is not very robust, it doesn't handle tabbing into the fields. To fix that, handle the focus event.
Another problem is that you don't get the message back if you don't type anything and leave the field. A better approach is to compare against the initial value when the field receives focus. If there's nothing in there when you leave the field, restore to the original value.
Here's a jQuery plugin for creating these placeholders: https://github.com/mathiasbynens/Placeholder-jQuery-Plugin
Also, newer browsers support a placeholder attribute that does exactly that http://www.paciellogroup.com/blog/2011/02/html5-accessibility-chops-the-placeholder-attribute/
I'd say the best way of doing this is to have a clear button inside the text input. See here for an example : How do I put a clear button inside my HTML text input box like the iPhone does?
No need for the messy number checking, use data on the element in question
This should work for you.
$('#username,#password').focus(function(){
if(!$(this).data('seen')) {
$(this).data('seen',true);
$(this).val('');
}
});
http://jsfiddle.net/DeZ7D/
You could store the placeholder and replace back on blur if the user hasn't entered anything.
more detailed implementation here:
http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
Related
I’m trying to make something where you can input numbers into an input (or would a contenteditable div be better?) and it does some calculations to them and sets the content of another div as the answer. How can I make it so that the other div will update whenever the number changes? I would prefer to make it so that there isn’t a submit button so the number instantly changes as you type it. I could probably achieve this by updating it every time there is a keystroke but the problem is storing the input data without pressing a submit button
First, please take some time to format your questions in the future. This is a difficult read.
Second please try and include all the information to show how far you have gotten.
Also I wasn't really clear what you are trying to do.
What you are looking for is called two way data binding, there are many different options for it, but it doesn't mean that's what you need. It seems like the following would be a good solution for you.
function doSomeCalculationsAndDisplay(event){
const elem = document.getElementById('input');
console.log(elem.value);
document.getElementById('result').innerText = 'Double value: ' + parseFloat(elem.value) * 2;
}
<input id="input" type="number" onKeyUp="doSomeCalculationsAndDisplay()" onChange="doSomeCalculationsAndDisplay()">
<div id="result"></div>
I always seem to figure it out on my own as soon as I make a post about it. It's not very complicated, the problem I had is that I was trying to get the innerHTML of an input which isn't possible, I needed to get its value instead.
To accomplish this all you need to do is make an input, div, and function that sets the div as the input document.getElementById('test1').innerHTML = document.getElementById('input1').value; and call this function onkeyup in the input.
I do not think this exact question has an answer anywhere else.
I have a page with a couple of input fields, and lots of ajax activity for various things. It is an online POS interface. When any of the ajax actions are performed, ususally by a button click, it is desired to always return focus to the main barcode input field.
Whilst this can be done by always calling $('#fieldid').focus() after any of these actions, I was wondering if there was a way of specifying that this field should always have focus after any action. There are other input fields where you need to type a name or something so obviously it cannot just set a timer and set focus on timeout as you would need to allow time for typing.
One option would be to have a timer always running to do it, and constantly reset it when typing. This seems to perhaps be sensible as these fields do have live search on typing associated with them.
Maybe I have answered my own question here, but any better way of doing it would bt greatly appreciated.
Have you tried using the focus trigger within your callback, after appending the html?
Example:
$.post(
'ajax.php',
{ next:next },
function(data){
$('body').append($(data).hide().fadeIn('slow'));
$('textarea').focus();
}
);
To avoid repeated code for each ajax call,
use ajaxStop event.
$.ajaxStop(function(){
$('textarea').focus();
});
You can use preventDefault(); function in Javascript
I have a webpage which has check-boxes, input fields, dropdowns etc.,
Mandatory conditions are checked using javascript. If anyone fails to fill these fields and press next button validation errors popup.
Now what I want to achieve is when someone fails to enter information in the mandatory fields, the cursor should go to the first field which caused the error.
Can anyone suggest me how to do this?
Add a class (something like input-error) for every invalid field. Then use something like:
var errors = document.querySelectorAll(".input-error");
if (errors.length > 0) {
errors[0].focus();
}
Here's an example: http://jsfiddle.net/NtHzV/1/
It really all depends on the structure of your code, how you're validating, what you're actually doing with validation, and what your HTML is.
At the same time, if you're doing something similar to my example, you might as well keep track of the first input with an error, then focus() it at the end of validation. Something like this:
http://jsfiddle.net/NtHzV/2/
UPDATE:
Bergi pointed out that querySelector might as well be used (instead of querySelectorAll) because you're only looking for the first input with errors. So here's an update:
var error_input = input_area.querySelector(".input-error");
if (error_input !== null) {
error_input.focus();
}
http://jsfiddle.net/NtHzV/3/
Here's specs on querySelector: https://developer.mozilla.org/en-US/docs/DOM/element.querySelector - Note that < IE8 does not support it.
The use of ".input-error" is because that is the CSS class selector, and will find the first (if any) element in a specific area with the class "input-error".
This line will focus the page on the element you specify. You should be able to implement this into your validation checks to focus on the bad elements.
document.getElementById("ID_Of_bad_field").focus();
I have two inputs that together form a single semantic unit (think an hours and minutes input together forming a time input). If both inputs lose focus I want to call some Javascript function, but if the user merely jumps between those two, I don't want to trigger anything.
I've tried wrapping these two inputs in a div and adding an onBlur to the div, but it never triggers.
Next I tried adding onBlurs to both inputs and having them check the other's :focus attribute through jQuery, but it seems that when the onBlur triggers the next element hasn't received focus yet.
Any suggestions on how to achieve this?
EDIT: Someone questioned the purpose of this. I'd like to update a few other fields based on the values contained by both these inputs, but ideally I don't want to update the other fields if the user is still in the process of updating the second input (for instance if the user tabs from first to second input).
I made a working example here:
https://jsfiddle.net/bs38V/5/
It uses this:
$('#t1, #t2').blur(function(){
setTimeout(function(){
if(!$('#t1, #t2').is(':focus')){
alert('all good');
}
},10);
});
var focus = 0;
$(inputs).focus(function() { focus++ });
$(inputs).blur(function() {
focus--;
setTimeout(function() {
if (!focus) {
// both lost focus
}
}, 50);
});
An alternative approach is to check the relatedTarget of the blur event. As stated in the MDN documentation this will be the element which is receiving the focus (if there is one). You can handle the blur event and check if the focus has now been put in your other input. I used a data- attribute to identify them, but you could equally well use the id or some other information if it fits your situation better.
My code is from an angular project I've worked on, but the principle should translate to vanilla JS/other frameworks.
<input id="t1" data-customProperty="true" (blur)="onBlur($event)">
<input id="t2" data-customProperty="true" (blur)="onBlur($event)">
onBlur(e: FocusEvent){
const semanticUnitStillHasFocus = (val.relatedTarget as any)?.dataset?.customProperty === "true";
// Do whatever you like with this knowledge
}
What is the purpose of this behavior ?
The blur event triggers when a field looses focus, and only one field can gain focus at a time.
What you could do, in case of validation for instance, is to apply the same function on blur for both the fields and check the values of the fields altogether.
Without a context, it is difficult to help you more.
d.
I'm trying to update a span tag on the fly with data from an input text field. Basically I have a text field and I'd like to be able to grab the user's input as they type it and show it to them in a span tag below the field.
Code:
<input id="profileurl" type="text">
<p class="url">http://www.randomsite.com/<span id="url-displayname">username</span></p>
JQuery:
var username;
$('#profileurl').keyup(function(username);
$("#url-displayname").html(username);
See it in JS Fiddle: http://jsfiddle.net/pQ3j9/
I'm guessing the keyup function is not the best way to do this. Since checking the key wouldn't be able to grab prefilled or pasted form input.
Ideally there is some magical jQuery function that can just output whatever info is in the box whenever it detects a key up but if that method exists I haven't found it yet.
EDIT: You guys are fricken amazing. It looks like .val() is that magic method.
Second question: How would you restrict input? Looking at the modified jsfiddle's, when a user inputs an html tag like < hr > the browser interprets it and breaks the form. Do you specify an array and then check against that? Does jquery have anything like PHP's strip_tags function?
$('#profileurl').keyup(function(e) {
$("#url-displayname").html($(this).val());
}).keypress(function(e) {
return /[a-z0-9.-]/i.test(String.fromCharCode(e.which));
});
check out the modified jsfiddle:
http://jsfiddle.net/roberkules/pQ3j9/5/
Update: As #GregL points out, keyup indeed is better, (otherwise e.g. backspaces are not handled at all).
Similar to roberkules' answer, but using keyup() like you proposed seems to work better for me in a Chrome-based browser:
$('#profileurl').keyup(function(e) {
$("#url-displayname").html($(this).val());
});
Updated jsFiddle: http://jsfiddle.net/pQ3j9/3/
For the second question, if you wish to maintain characters and not have them parsed as html entities then you should do this instead :
$('#profileurl').keyup(function(key) {
$("#url-displayname").text($(this).val());
});
Check it out at - http://jsfiddle.net/dhruvasagar/pQ3j9/6/
You can bind multiple events with bind
http://jsfiddle.net/dwick/DszV9/