i'm trying to write unobtrusive default/placeholder text in input (actually, relatively placed label over input, which hides on onFocus, and stays hidden if input isn't empty on onBlur), but I don't want to use jQuery, because this is the only javascript used on page - therefore using jQuery seems a bit over the top.
Please, how can I do this without jQuery?
Thank you.
EDIT: I know the idea (getElementByID), but I'm more looking into how to add it to document - preferably something you have used before. Thank you.
EDIT: Thank you all, I finally went with jQuery, seeing answers :] (my example is here: http://jsbin.com/ehega/3 - it's concept, I'll probably add more eye candy. As an answer I Robert Koritnik - because of valid points... and styling ;])
you will need to manually attach the onfocus and onblur events, having got a handle on the input with getElementById.
here is an example: http://www.aspsnippets.com/Articles/Watermark-TextBox-using-JavaScript.aspx
I suggest you use jQuery
jQuery is nothing more than a cross-browser library that makes it easier for developers to achieve something and not worry about browser particularities. And when you load it once (it's rather small) it's cached so I wouldn't worry because it will save you lots of development/testing time later.
No? Then do it manually but make it more reusable
But if you do decide to do something manually you can always use regular Javascript and manipulate DOM as you wish. You best friends in this case would of course be (as Andrew pointed out):
getElementById() and
getElementsByTagName()
functions, but since you'll be manipulating DOM and styles, make sure you test your code against all common browsers. If you use custom attributes on INPUT elements it's good to use the second function, so you'll attach additional functionality to all inputs at once and only to those that define that particular custom attribute like:
<input type=text id="inputX" name="inputX" placeholder="Enter something">
Your script would then get all inputs and you'd check for the custom attribute existance and attach events to those elements that do define that attribute. This way you won't depend on IDs and make your code universal so you can reuse it app wide. Or even on other projects.
Just a sidenote: Andrew's example works somehow differently than what you said would like to do (using labels), but I suggest you use the same approach, because you'll be running scripts anyway. For the sake of unobtrusiveness make sure that you set default content using Javascript so default values and styles on textboxes won't be set for those users that are not running Javascript.
You can use jQuery and still be unobtrusive and use the ability of HTML5 Browsers, make your input like this:
<input type="whatever" placeholder="Your Default Text"/>
I user Modernizr to check the html5 capabilities of the browser and if the browser doesn't understand the placeholder attribute than I use this little javascript to emulate this function.
if (!Modernizr.input.placeholder) {
$('input').each(function(){
var obj = $(this);
var placeholder = obj.attr('placeholder');
if (placeholder) {
obj.val(placeholder);
obj.focus(function(){
var obj2 = $(this);
if (obj2.val() == obj2.attr('placeholder')) obj2.val('');
});
obj.blur(function(){
var obj2 = $(this);
if (obj2.val() == '') obj2.val(obj2.attr('placeholder'));
});
}
});
}
It is unobtrusive, because you don't need any javascript in your html code. the function above can easily changed if you want to use any other framework. I wouldn't use a solution without any Framework, because the frameworks do a great job in working around the incompatibilities between browsers.
This is how I would do it, without JQuery. It grays out the control when it shows the default text, and allows entering the default text if need be. The "title" tag will fallback to a tooltip for people who disable JavaScript:
<html>
<body>
<input type="text" value="" title="default text" />
<script type="text/javascript">
function DefaultInput(e) {
// Get the elements
this.e = e
this.d = e.title
this.s = e.style
e.removeAttribute('title') // remove the tooltip
e.value = '' // IE cached value remove HACK!
// Bind the events
e.onblur = this.bind(this.onblur)
e.onfocus = this.bind(this.onfocus)
// Show the initial value in gray
this.onblur()
}
DefaultInput.prototype = {
bind: function(f) {
// Return `f` so it's always called as an object of DefaultInput
var o = this
return function(){
f.apply(o, arguments)
}
},
onblur: function() {
// Gray out my value and show the default text if my value's blank
if (!this.h && !this.e.value) {
this.s.color = 'gray'
this.e.value = this.d
this.h = true // true -> help text displayed
// false -> help text hidden/user entered value
}
},
onfocus: function() {
// Make the text black and blank the text if in "help" mode
if (this.h) {
this.s.color = 'black'
this.e.value = ''
this.h = false
}
}
}
// Make sure the page is loaded before
// running for twitchy browsers like IE
window.onload = function() {
// Add defaults for all text input elements which have a `title`
var L = document.getElementsByTagName('input')
for (var i=0; i<L.length; i++) {
var e = L[i]
if (e.type=='text' && 'title' in e)
new DefaultInput(e)
}
}
</script>
</body>
EDIT: Cleared up the comments a bit, fixed some IE bugs and made it so it looks for <input> tags with title's to make it so different pages have less conversion time rather than individually intitializing the input controls ;-)
I think that you need something like this:
<input type="text" onfocus="if (this.value == this.getAttribute('mydefaulttext')) this.value = '';" onblur="if (this.value == '') this.value = this.getAttribute('mydefaulttext');" mydefaulttext="click here..." value="click here..."/>
<input name="test" type="text" id="test" value="testValue" />
<script type="text/javascript">
var myInput = document.getElementById("test");
myInput.onfocus = function() {
this.value = '';
}
myInput.onblur = function() {
if(this.value == '') this.value = "testValue";
}
</script>
Here's how I do:
Online Working Example
http://jsbin.com/ehivo3 (source code)
HTML
<input type="text" name="myfield" id="myfield" value="Please, fill my field!!!" />
jQuery
$(document).ready(function() {
// Handle each input on focus() and blug()
$('input[type="text"]').each(function() {
$(this)
// Store the default value internally
// Don't use .val() because browser autofill will poison it
.data('defaultValue', $(this).attr('value'))
// Handle the focus() (when you enter the field)
.focus(function() {
if ($(this).val() == $(this).data('defaultValue'))
$(this).val('');
})
// Handle the blur() (when you leave the field)
.blur(function() {
if ($(this).val() == '')
$(this).val($(this).data('defaultValue'));
});
});
// Clear all fields with "default value" on submit
$('form').submit(function() {
$('input[type="text"]', $(this)).each(function() {
// If the input still with default value, clean it before the submit
if ($(this).val() == $(this).data('defaultValue'))
$(this).val('');
});
});
});
And that's all! No invalid or extra attributes, valid markup and all handled in your jQuery file. :)
Related
I have an problem with my site when I want to change the css style from the JavaScript it works but only for few seconds.
function validateForm() {
var fname = document.getElementById('<%=UserFnameTextBox.ClientID%>');
if (fname.value == "") {
document.getElementById("WarnUserFnameTextBox").style.opacity = 1;
document.getElementById('<%=UserFnameTextBox.ClientID%>').style.borderColor = "red";
getElementById('<%=UserFnameTextBox.ClientID%>').focus;
}
}
I'm using also Asp.net, that's why I wrote the ID like this
I want that the JS will save the style for as long that the user enter the textbox.
Multiple things here: I suggest that your validateForm() function triggers in an onClick on your submit-button, right? Does your button look somewhat like this?
<input type="submit" value="submit" onClick="validateForm()">
If this is the case, the reason why your styles work only for few seconds is simply that the website reloads. The styles are in effect, but the form is also triggering and send to the site, which you added in your <form action>. After reloading, the website will fall back to its default style, as if the errors never occured... which is correct on that instance of the site.
If you want to have it permanent, you have to disable the submit-button as long as there are invalid fields. You can make use of the required attribute for form elements as well, since the form won't submit as long as there are invalid fields. These can be styled as well.
Have a look at these CSS rules for that:
/* style all elements with a required attribute */
:required {
background: red;
}
You can make use of jQuery as well and disable the form-submit with preventDefault. You can take care of every style and adjust accordingly, as long as there empty / non-valid characters in your input-fields. I suggest combining this with the onKeyUp-function. This way you check everytime the users releases a key and can react as soon as your input is valid.
As an example with jQuery:
var $fname = $('#<%=UserFnameTextBox.ClientID%>');
var $textBox = $('#WarnUserFnameTextBox');
$fname.on("input", function() {
var $this = $(this);
if($this.val() == "") {
$textBox.show();
$this.focus().css("border", "1px solid red");
}
});
(thanks for pointing out my errors and optimizing the code, #mplungjan!).
To "disable" the actual form-submission, refer to this answer:
https://stackoverflow.com/a/6462306/3372043
$("#yourFormID").submit(function(e){
return false;
});
This is untested, feel free to point out my mistake, since I can't check it right now. You can play around on how you want to approach your "errorhandling", maybe switch to onKeyDown() or change(), that kind of depends on your needs / usecase.
Since your question isn't tagged with jQuery, have a look at this answer given by mplungjan as well, since it uses native JS without any framework.
https://stackoverflow.com/a/53777747/3372043
This is likely what you want. It will stop the form from being submitted and is reusing the field and resetting if no error
It assumes <form id="myForm"
window.addEventListener("load", function() {
document.getElementById("myForm").addEventListener("submit", function(e) {
var field = document.getElementById('<%=UserFnameTextBox.ClientID%>');
var error = field.value.trim() === "";
document.getElementById("WarnUserFnameTextBox").style.opacity = error ? "1" : "0"; // or style.display=error?"block":"none";
field.style.borderColor = error ? "red" : "black"; // reset if no error
if (error) {
field.focus();
e.preventDefault();
}
});
});
I have a checkbox on my website which is currently enabled and it can be disabled by users. What I want to do is to keep it locked in that way so it cannot be disabled.
I think this can be achieved using jquery or javascript but I'm not quite sure how.
<input type="checkbox" value="check" id="moove_gdpr_strict_cookies">
And please note it's a wordpress website. So I can't edit HTML.
you can simple prevent click.
$(document).ready(function() {
$('#moove_gdpr_strict_cookies').click(function(e) {
e.preventDefault();
});
});
Simply you can return false onclick event
$('#moove_gdpr_strict_cookies').on('click',function(){
return false;
});
Would suggest to do something like this:
var form = document.getElementById('yourform');
form.onSubmit = function () {
var formElems = document.getElementsByTagName('INPUT');
for (var i = 0; i , formElems.length; i++){
if (formElems[i].type == 'checkbox'){
formElems[i].disabled = true;
}
}
}
I would not recommend doing this. As suggested by the id of checkbox this checkbox has to do with GDPR. A user on your sight MUST have the right to decline cookies for tracking purposes (which this seems to be). Please be careful, as fines can be very high.
Technically most answers seem viable.
I am writing a little Meteor app. There is a textarea in a form, which looks like this:
<form name="comments-form">
<label for="textarea">Comment:</label><br>
<textarea cols="40" rows="10" name="comment_textarea" class="comment_textarea">Write your comment here.</textarea><br>
<button class="btn btn-success js-add-comment">add comment</button>
</form>
In my client.js I have the following code for accessing the value of the textarea:
EVENT_HANDLED = false;
Template.website_item_details.events({
"click .js-add-comment": function(event) {
var comment_text = event.target.comment_textarea.value;
if(Meteor.user()) {
Comments.insert({
created_by: Meteor.user()._id,
text: comment_text,
website_id: this._id
});
}
return EVENT_HANDLED;
}
});
However, when I click the button to add the comment, I get the following console output:
TypeError: event.target.comment_textarea is undefined
["click .js-add-comment"]()
client.js:103
Template.prototype.events/eventMap2[k]</</<()
blaze.js:3697
Template._withTemplateInstanceFunc()
blaze.js:3671
Template.prototype.events/eventMap2[k]</<()
blaze.js:3696
attached_eventMaps/</</</<()
blaze.js:2557
Blaze._withCurrentView()
blaze.js:2211
attached_eventMaps/</</<()
blaze.js:2556
HandlerRec/this.delegatedHandler</<()
blaze.js:833
jQuery.event.dispatch()
jquery.js:4690
jQuery.event.add/elemData.handle()
This seems to be basic form handling, but somehow I can't get that text in the textarea into a variable in my javascript code. I've already tried a multitude of variants of accessing it:
document.getElementsByClass()[0].value
$('.comment_textarea').get(0).val() // there should only be one such text area anyway
event.target.comment_textarea.value;
But none of those work for me, I always get that error. It's almost like the textarea was not part of my html or there is a bug in Meteor, which prevents me from accessing textareas.
I also checked whether there are other things named comment_textarea with a fulltext search on all of my projects clientside files, but there isn't any other.
Am I simply blind and overlooking something? How do I get that text?
What's more is, that although I return false, the browser still reloads the page. Could it be related to the error happening before?
You are using the click event of the button and on that event, the textarea is not available. You need to change the event into submit form. First, put the id into your form, change the button into type submit and change the code into
"submit #your-form-id": function(event) {
event.preventDefault();
var comment_text = event.target.comment_textarea.value;
.....
}
After trying even more desperate ways to access that textarea, I think I know now what's wrong:
// var comment_text = event.target.comment_textarea.value;
// var comment_text = document.getElementByName('comment_textarea').value;
// var comment_text = document.getElementByTagName('textarea')[0].value;
// var comment_text = $('textarea').get(0).val();
// var comment_text = $('textarea').get(0).text();
var comment_text = $('textarea').get(0).value; // finally working!
So it seems that when I use jQuery, I can't use the .val() function as stated in my other answers to many other questions, but for some reason I have to treat it like a normal DOM object and use the attribute value instead of the function .val().
Maybe it's specific to the jQuery version in my Meteor app?
So I will test the following:
var comment_text = $('textarea.comment_textarea').get(0).value;
...
Yes, that also works.
Also it fixes the reload issue. I guess since there was an error, it didn't even get to return false and this is why the website reloaded.
Question:
I am running a function where you press the keys C or M using the keypress() function and every time I press one of those keys, the letter is marked automatically in Firefox. Is there a way to disable this using JavaScript or is this something Firefox does by default?
I have tried to look for an answer using Google but it seems no one has had this issue before using the keypress() function in JS.
Code:
<script type="text/javascript">
$(document).ready(function()
{
var once = false;
$(window).keypress(function(e)
{
if(!once)
{
if (e.which == 99)
{
once = true;
$("input#left").val( 1 );
$("form").submit();
}
else if (e.which == 109)
{
once = true;
$("input#right").val( 1 );
$("form").submit();
}
}
});
});
</script>
Thanks in advance for any tips!
Just call preventDefault():
$(window).keypress(function(e)
{
e.preventDefault()
// other code
}
There are a few ways of handling this. If you call e.preventDefault() you should be covered, however that's not your only option.
HTML5 introduced many new tags and attributes into markup, one of them being an autocomplete attribute for text fields. If you add this to your HTML (<input type='text' id='myInput' autocomplete='off'>) you should be covered as well. You can't always rely on your user having support for HTML5, but this is still an easy solution to your problem.
It can't hurt you to implement both of these small changes in your code.
I am trying to call the resetyear function and it's getting called also, but the flow stops at alert("over"). It doesn't transfer its control to resetmaster.
String flag = "";
flag = (String) session.getAttribute("flag");
System.out.println("flag = " + flag);
if (flag == null) {
flag = "";
}
if (flag.equals("yes")) {
%>
<script>
alert(1);
// resetyear();
dontreset();
//document.getElementById("checkyear").value = "1";
//alert(document.getElementById("checkyear").value);
</script>
<%} else if(flag.equals("no"))
{%>
<script>
alert(2);
//document.getElementById("checkyear").value = "2";
//alert(document.getElementById("checkyear").value);
resetyear();
</script>
<%}else{}%>
function resetyear(){
if(confirm("DO YOU WANT TO RESET THE YEAR?"))
{
alert("hello");
//document.forms['indexform'].action = "resetmaster";
//alert(document.forms['indexform'].action);
//document.forms['indexform'].submit();
alert("over");
form.action = "resetmaster";
form.submit();
alert(1);
}
For me it works:
document.getElementById("checkyear").value = "1";
alert(document.getElementById("checkyear").value);
http://jsfiddle.net/zKNqg/
Maybe your JS is not executed and you need to add a function() {} around it all.
You need to run your script after the element exists. Move the <input type="hidden" name="checkyear" id="checkyear" value=""> to the beginning.
It seems to work fine in Google Chrome. Which browser are you using?
Here the proof http://jsfiddle.net/CN8XL/
Anyhow you can also access to the input value parameter through the document.FormName.checkyear.value. You have to wrap in the input in a <form> tag like with the proper name attribute, like shown below:
<form name="FormName">
<input type="hidden" name="checkyear" id="checkyear" value="">
</form>
Have you considered using the jQuery Library? Here are the docs for .val() function.
The first thing I will try - determine if your code with alerts is actually rendered. I see some server "if" code in what you posted, so may be condition to render javascript is not satisfied. So, on the page you working on, right-click -> view source. Try to find the js code there. Please tell us if you found the code on the page.
Your code for setting value for hidden input is correct. Here is the example. Maybe you have some conditions in your if statements that are not allowing your scripts to execute.