I have an element:
<input type="number">
When I type in $500, it fails validation, so
console.log("el.value");
//returns ""
This is expected.
Here's the question:
How can I check that there is content?
I'm trying to show/hide placeholder text (no, I can't use the native stuff). It needs to be type="number" because I need to force the mobile number keyboard.
Any thoughts?
Update:
From the responses below I can see that I wasn't clear enough in my question.
1) I need to use JavaScript to tell me whether there is content in the input. (I don't need to extract it, I just need to see whether there is content).
This is tricky, because invalid content (like putting words in a number input field) means the value="" even if there is content typed in.
This is the exact problem I need to solve.
inputEl.validity.valid might work but I can't find any docs on how well it is supported across browsers.
Check if you can do something with that :
html
<input id="my-input" type="number">
js
$(document).ready(function(){
$('#my-input').on('input', function(){
console.log($(this).val());
});
});
At mobile device specially Samsung append value in field do not throw key press event,
you can validate the field with onChange="check(this)"
if (variablename==""){
//no content
}
or
if (variablename.length==0){
//no content
}
If the only reason you need to force the input type to be a number is for the number-pad, why don't you instead make type="text" and pattern="\d*"? This way you can handle and check the input any way you'd like, but still, force the number-pad to show.
<input type="text" pattern="\d*">
This was the one that actually answered it:
How to get the raw value an <input type="number"> field?
Basically you can check input.validity.valid or input.validity.badInput.
Not supported in IE but good support elsewhere.
More details on it here:
https://developer.mozilla.org/en-US/docs/Web/API/ValidityState
Related
I'm trying to add auto focus to a form. I have it working in Chrome but cannot get it working in Firefox with the below code. I think the reason could potentially be that it needs to be just autofocus rather than autofocus="autofocus". Would I be correct in assuming this? If so is there some way I can add it? I'm using a framework called SilverStripe and don't have direct access to editing the input field as it's done dynamically so would need to do it via JavaScript most likely.
<input type="text" name="Search" class="form-control search-form" id="TemplateSearchForm_SearchForm_Search" placeholder="Search..." autofocus="autofocus">
Note I am initially hiding the input box and displaying on the click of an icon by adding a class:
jQuery('.search').click(function () {
if(jQuery('.search-btn').hasClass('fa-search')){
jQuery('.search-open').fadeIn(500);
} else {
jQuery('.search-open').fadeOut(500);
}
});
I couldn't find anything in the HTML specification to validate the autofocus behavior exhibited by Chrome. Here's an excerpt from the spec on this behavior.
From 4.10.19.7 Autofocusing a form control: the autofocus attribute:
When an element with the autofocus attribute specified is inserted into a document, user agents should run the following steps:
[...]
Note: This handles the automatic focusing during document load.
It doesn't mention anything about applying this behavior when the display state changes (as Chrome is apparently doing), only when the element is first inserted into the DOM. This actually appears to a be a bug in Chrome as Firefox is following the HTML spec.
Instead of using the autofocus attribute, you will have to trigger the focus through JavaScript.
You could use JavaScript to automatically focus into any elements with autofocus='yes'
$('[autofocus="yes"], [autofocus="autofocus"], [autofocus="true"]').focus();
This should, theoretically target any elements that have autofocus set to either true, yes, or autofocus and focus on them.
I have a field that accepts the year, so I have created
input type="number"
and implemented keydown event to restrict user to enter more than 4 digits.
Now I'm facing an issue and need help in figuring out the logic. Following is the case:
Enter 4 digits in the textbox
Select entered text using SHIFT + Arrow Keys
Now if you type a number it should replace the data but since I have barred it, it will not. Need to cover this case.
Also find code in following JSFiddle.
I also have lot of css and validation on input[type=number], so cannot change to input[type=text].
Also same form is used on mobile devices, and when user selects textbox, numeric keyboard should appear.
Edit 1
while searching for option, I found a JSfiddle that could direct us to right direction.
Issue here also is input[type=number] does not support selection property. Reference
As an alternative, we have decided to move to input[type=tel]. This would work in similar fashion, but will allow us to use maxLength attribute. Still if anyone has a better way, please share.
HTML:
<input type="tel" class="year" maxlength="4" data-temp="">
jQuery:
$(document).on('input', '.year', function(){
var txt = $(this).val();
if(isNaN(txt) || txt > 9999){
$(this).val( $(this).data('temp') );
return;
}
$(this).data('temp', txt);
});
JSFiddle
May be this will work , you can use the Regular Express to validate only number and
^[0-9\.\-\/]+$
and also you can use the .length method to insure that you have specific length
You can't submit an invalid value in this case:
<form>
<input type=number min=0 max=9999 required />
<input type=submit value=Submit />
</form>
So I have moved my code to input[type=tel] and Updated JSFiddle
If you check, I have added 2 events
Keydown to restrict from entering any invalid key.
Blur event to check if entered value is number only or not.
Now you might be thinking, if I have already restricted user to enter only number, how can he enter incorrect value.
Explanation
In my implementation, I have used keydown and using keycode, I'm allowing/blocking. Interesting case is when user press and holds shift key. Now on keydown, I get same keycode but value is different(A special character). So checking the integrity on blur.
A better way would have been handling keypress and keydown together and I'll update fiddle and update my answer, but for now I guess this has solved my problem.
Thanks you all for all comments/answer. Also kindly let me know if there are any better ways to implement.
I have a form which calculates a cost and sets the value of an input accordingly. For obvious reasons, I have used:
$('#totalcost').attr('disabled',true);
to prevent the user from being able to edit the cost.
However, when I do this, the PHP script I'm using to mail the form doesn't pick up the input (not just the value - it doesn't read the input at all). When the input is enabled, it works fine.
How can I prevent the user from editing the input while still having the PHP mailing the value? Or is there a better way to do this anyway?
Make it readonly, not disabled:
$("#totalcost").attr('readonly', true);
You could also do it in the original HTML, since it's not something you really want to change back and forth dynamically.
<input id="totalcost" type="text" readonly>
Use Read Only property, Though i guess it wont work in internet exploer.
Add readonly attribute, like this:
$("#totalcost").attr('readonly', true);
Add property readonly="true".
$('#totalcost').attr('readonly',true);
you can try:
$("#totalcost").prop("readonly",true);
Use read only in html itself or in script
<input type="text" name="totalcost" id="totalcost" value="" readonly>
$('#totalcost').attr("readonly", true);
Inside a <form> I want to use multiple Password type fields but.. I want to make some of them not to be remembering the value of it.
Normally i can use autocomplete=off inside <form> tag.
But this affects over every single fields inside.
Edited: Got Simple Solution Now
<input autocomplete="off" ....... />
Yes, you can (set autocomplete="off" on individual inputs).
You can set autocomplete on a single field by using:
#Html.TextBoxFor(x => x.Property, new {autocomplete = "off"})
If you're using DisplayForModel than you will have to create a custom Edit Template.
You can set it on individual fields, but it's a non-standard HTMl extension and will cause your pages to fail validation: Is there a W3C valid way to disable autocomplete in a HTML form?
I have a registration form, and i want to use a password field. The problem is, i want it to have a placeholder saying "Password" at the begining so i'm using a text field instead. I need to turn the characters into asterisks or black circles like a password field when the user starts typing.
I've tried changing the "type" attribute to "password" through javascript, so i'm stuck.
Is there a simple way to resolve this with css? or does anyone know of a good javascript(preferably jquery) to hack this?
Thanks
Use a regular password field
Don't abuse the value as a placeholder — it becomes invisible to, among others, screen reader users.
Put the label in a <label>
Position the label behind the input
Restyle the input with JS to change the background
Demo at http://dorward.me.uk/tmp/label-work/example.html
You could use the HTML5 placeholder attribute However, that will not work in all browsers (especially older ones).
<input type="password" name="pwd" placeholder="Enter Password" />
Hover a div or a span tag over your text (password) field, then hide it when the password field takes focus or the div/span is clicked.
Generally, browsers frown at changing the type attribute of input elements via JavaScript. Most workarounds involve cloning the input with the new type, and removing the original.
You could absolutely position the label over the input form, and remove it on focus.
You should consider the implications of not using type="password" - it is the semantically correct option.
Update
Upon reading David Dorward's answer, you should strongly consider his very valid points.
I had a similar problem, where I had the Value of the inputs as my labels, and when you clicked inside one, some Javascript would run, clearing the input. But on the password field, you needed to change the input type from "text" to "password", which works in browsers like Safari or Firefox, but not IE (IE doesn't support the setAttribute function very well). So I was killing myself trying to figure out how best to do this (IE conditionals, etc.)
I found this thread, and I think Quentin had the best idea. Not only because it works and should work in all browsers, but it also provides an actual Label in the code, which, Screenreaders aside, is good practice. Plus, you should always consider those who use screenreaders to some extent.
Here is the basics of the solution:
The HTML:
<label>Enter Password
<input type="password" name="password" class="input" /></label>
The jQuery (note: I am not a jQuery expert. This could probably be written better or more efficient, but for two fields, it works):
$("input[name=password]").focus(function() {
var value = $("input[name=password]").val();
if(value == "") {
$(this).toggleClass("inputBg");
}
});
$("input[name=password]").blur(function() {
var value = $("input[name=password]").val();
if(value == "") {
$(this).toggleClass("inputBg");
}
});
The CSS starts with the Label tag, styled the same as your input class, with a position relative and display block added. Then there are two classes for the input. One that is the correct width, height, etc. positioned absolute, with a higher z-index than the label, BUT WITH NO BACKGROUND. The second class is exactly the same, but WITH THE BACKGROUND.
The jQuery just toggles between the two classes, so you'll see the label under the input, but when you click on the input, the background appears and you can type in text on top of it. Works great, should work in all browsers (although only tested in Safari on Mac and IE/Firefox on Windows). Nice idea Quentin!