I'm creating a web form that I'd like to add field verification to. The current approach involved specifying a "pattern" attribute in the input tags as follows:
<input id="foo" class="span7" type="text" pattern="^[0-9]*\.?[0-9]*$">
However, this approach has unexpected behavior, and as I've read from MDN, is not supported in all major browsers. Is there an alternative to this functionality?
To be clear, I'd like to trigger a stylistic effect if the contents of the text box does not match a specified regex. I realize this can be achieved with Jquery and add/remove class, but this feels rather inefficient.
there's really no efficient way to do this; you either need to employ pattern or do your own event listener which runs its own regex on a key event.
Try this:
HTML:
<input id="foo" class="span7" type="text" onblur="checkInput(this.value,'^[0-9]*\.?[0-9]*$');">
JavaScript:
<script>
function checkInput(txt, pattern) {
var re = new RegExp(pattern);
var x = re.test( txt );
//--- if x != true then show error message
}
</script>
Related
Its probably something basic but wanted explanation of the use cases. Like sometimes hitting "enter" inputs the data, while sometimes mouseclicks work. I'm concerned about "Gotchas" that I would have overlooked. Like maybe it works in Firefox but not in Chrome for example.
I saw the following 2 ways, both are ways to input data into a form element.
First way
JavaScript
var $body = $(e.target).find('[name=body]'); //defines the content
var comment = { body: $body.val() };
HTML
<form class="form-send-message" id="addcomment" data-keyboard-attach>
<textarea id="body" name="body"></textarea>
</form>
Second way
JavaScript
var message = template.find('input').value;
HTML
<form class="message" data-keyboard-attach>
<input type="text" name="body" id="body">
<button class="icon" type="submit"></button>
</form>
Here you can see two ways to find the value of an input/textarea with an explanation:
'submit .new-post': function(event){
//returns name="postBody" content from the form you're submitting
var postBody = event.target.postBody.value;
//returns the value of an html element that exists in DOM, even if its inside a different template or form.
var postBody = $('.someClass').val()
}
Your first code Is jQuery, while your second code is Meteor. They both can accomplish the same thing under the right circumstances. Also, according to this answer, meteor's template.find is an alias for jQuery's $, meaning they are the exact same.
But, the codes don't do the same thing in this case.
Your first code finds the value an element with a name of "body" inside e.target. I am assuming e is an Event, but there is no way to tell with the current amount of code you gave.
The second code just gets the value of the first INPUT element it finds.
How can I can I alter (change, add, whatever) HTML/text real-time using the input tag? Very similar to the preview interface when asking a question on Stack Overflow minus the code encoding. It just has to be simple.
For example,
<input type="text" name="whatever" />
<div id="example"></div>
Whatever text is entered in the above input tag is added to #example in real-time.
Something involving innerHTML and JavaScript perhaps?
You can do this with jQuery
$('input').keyup(function(){
var a = $(this).val();
$('#example').text(a);
});
Example: http://jsfiddle.net/5TnGT/
There are many other ways to change content than described in the previous answers. Listen for all of them and update realtime. Requires jQuery supporting the newer .on() event handling for this example. Can also use .bind() or .live() with appropriate syntax.
$(document).ready(function() {
$(document).on('keyup propertychange input paste', 'input', function() {
$('#example').text($(this).val());
});
});
The second $(document) can be made more specific depending on the markup of the rest of your page.
See also: http://jsfiddle.net/DccuN/2/
Yes javascript will do this. Have a look at on key up. Then either innerHTML as you say or jQuery makes things a bit easier with .append or .html or .text
(Damn too slow)
Plain JavaScript solution (you won't need any sophisticated lib if you don't get too fancy elsewhere):
<input type="text" onkeypress="document.getElementById('example').innerHTML=this.value;" name="whatever" />
<div id="example"></div>
You can bind to the keyup event. Then set the div contents to that of the input.
http://jsfiddle.net/wYqgc/
var input = document.getElementsByTagName('input')[0];
var div = document.getElementById('example');
input.onkeyup = function() {
div.innerHTML = this.value;
};
You can start with this:
input.onkeyup = function () {
output.innerHTML = this.value;
};
Live demo: http://jsfiddle.net/P4jS9/
hope that title makes sense. I'm a noob at javascript. What I want to do is have a form which will have a couple of inputs like, name and url for example.
When the user enters their name, I'd like the url input to automatically have as a default their name with an underscore between words. So if they type in as their name pedro kinkybottom then automatically set as the default in the url input would be pedro_kinkybottom.
I'm using cakephp if anyone happens to know a particularly cakey way to do this that'd be cool but otherwise any help at all would be most welcome.
Thanks,
Pedro
You'd probably want to do this in JavaScript and not in PHP. Even though you may be more familiar with the latter, the user experience would be better with the former and the overall design simpler (since the page wouldn't need to refresh).
You essentially need to do two things:
Set the value of an input in response to an event on another input.
Replace space characters with underscore characters.
For the second part, take a look at JavaScript's replace function. It's pretty robust and lets you do a lot of string manipulation. Definitely worth trying it out yourself.
For the first part, here's an example with jQuery:
$('#inputName').change(function() {
$('#inputURL').val($('#inputName').val());
});
This would set the value of inputURL to the value of inputName any time the value of inputName changes. For the string replacement, you'd modify it similar to this:
$('#inputName').change(function() {
$('#inputURL').val($('#inputName').val().replace(' ', '_'));
});
Note that the change event will be fired when the control loses focus. If you want to to happen as-you-type then try the keyup event. There are other events as well.
Add a keyup event to the name field that will update the url field:
<form>
<input type="text" id="name" />
<input type="text" id="url" />
</form>
...and the js:
addEvent(document.getElementById('name'), 'keyup', function () {
document.getElementById('url').value = this.value.replace(' ', '_');
});
function addEvent(ele, evnt, funct) {
if (ele.addEventListener) // W3C
return ele.addEventListener(evnt,funct,false);
else if (ele.attachEvent) // IE
return ele.attachEvent("on"+evnt,funct);
}
http://jsfiddle.net/XKEh5/
If you're only going to do some trivial stuff like this, then you'll be fine with plain old javascript. If you're going to be doing a lot of this sort of thing, plus any effects like fading out elements or whatnot, I suggest you look in to mootools or jQuery.
Here is an edited version of the above answer. There was an issue with the "value.replace(' ', '_');" where it would only take the space out between the first two words typed in. This code snippet below does it for all.
<script language="javascript" type="text/javascript">
addEvent(document.getElementById('name'), 'keyup', function () {
document.getElementById('url').value = this.value.split(' ').join('');
});
function addEvent(ele, evnt, funct) {
if (ele.addEventListener) // W3C
return ele.addEventListener(evnt,funct,false);
else if (ele.attachEvent) // IE
return ele.attachEvent("on"+evnt,funct);
}
</script>
I have a form input like so:
<input type="text" name="footer_contact_name" class="footer_contact_input" onfocus="this.value='';" onblur="return inp_cl(this);" value="Name" />
I have made a js function:
function inp_cl(input){
if(input.value==''){
return 'Name';
}
}
The problem is that the form input value wont change to "Name" onBlur!
Any ideas whats wrong here?
Or maybe you all have better suggestions to how to make the code as short as possible, or maybe even a whole different approach to this? All I want is the text "Name" to be the default value, then dissappear onFocus, and if nothing entered, reappear again.
Thanks
You need to change return 'Name'; to input.value = 'Name';
There's a few solutions to this:
Solution 1
A return in your onblur isn't what you want with the function the way you've written it. Without changing your function, you can change your onblur to make use of the return value of your function using this:
onblur="this.value=inp_cl(this);"
or you can fix your function to update the input contents directly:
function inp_cl(input) {
if (input.value == '') {
input.value = 'Name';
}
}
and change your onblur attribute to:
onblur="inp_cl(this);"
The issue with your onfocus is that it's going to wipe out the content of your input box regardless of what's in there, so if you've got it populated and you leave and come back to this field, it's going to be wiped out, so you need the reverse of your function and point your onfocus to that:
onfocus="inp_bl(input)"
<script type="text/javascript">
function inp_bl (input) {
if (input.value == 'Name') {
input.value = '';
}
}
</script>
Solution 2
Alternatively you can hook it up in javascript removing the need for your onfocus/onblur attributes in your markup - this script will hook the watermark onto the required inputs events directly:
<script type="text/javascript">
watermark = function(input, watermarkText) {
input.onfocus = function () {
if (this.value == watermarkText)
this.value == '';
}
input.onblur = function () {
if (this.value == '')
this.value == watermarkText;
}
}
new watermark(document.getElementById("txtName"), "Name");
new watermark(document.getElementById("txtAddress"), "Street Address");
new watermark(document.getElementById("txtPostalCode"), "Postal Code");
</script>
<input type="text" id="txtName" />
<input type="text" id="txtAddress" />
<input type="text" id="txtPostalCode" />
Now you can scrap your onfocus/onblur attributes in your markup... and you've got repeatable code meaning you don't have to contaminate your markup with onfocus/onblur functionality.
Solution 3
By far the simplest way I can think of though, is to use jQuery and the watermark plugin - if you're already using jQuery, then it's no big deal, but if you're not, it adds a bunch of overhead you may not want. jQuery is pretty lightweight, but it comes with a bit of a learning curve as the set based paradigm it uses isn't quite what imperative programmers are used to:
$(document).ready(function() {
//This is the important bit...
$("#id_of_your_input_control").watermark("String to use as watermark");
});
Then scrap your onfocus/onblur attributes as the watermark function will hook it all up for you.
For this kind of functionality, jQuery makes things much more expressive - if you're not familiar with it, it's definitely worthwhile looking up and getting familiar with.
Addendum
The nice thing about Solution 3 is that it handles things like styling of your text when the watermark is displayed so that it looks like a watermark, meaning you don't have to handle all that yourself. It also attaches to the onblur/onfocus properly. If you go with Solution 2, it's a naive solution - if you want multiple handlers for the onblur and/or onfocus then that method doesn't attach properly and all other handlers for those events will be replaced with these - so it's not technically a safe approach, though in 99.9% of cases, it will work just fine.
try dis dude its help u!!
<input type="Text" value="Name" onblur="if(this.value=='') this.value=this.defaultValue; "
onfocus="if(this.value==this.defaultValue) this.value=''; ">
I'm trying to create a generic javascript function that would change attributes on events.
The way it would work is
function fooFunction(sourceElement)
{
var newName = sourceElement+'Span';
var newElement = document.getElementById(newName);
//Important line
newElement.property = "enter properties here";
}
and I'd call it with something like
<img src="foo.gif" id="foo" name="foo" onmouseover="fooFunction(this.id);"/>
<span id="fooSpan" name="fooSpan">some text here</span>
So in theory, when hovering the image, it should change whatever propery I need to change on the fooSpan object. It works in Opera, but on IE it returns a null object.
Any ideas ?
The idea would be that I would have multiple images that would automatically trigger the property change on the associated text span (typically the css style).
Are you sure you're getting the ID properly in IE? Maybe the ID being passed in is null in IE (perhaps this.id isn't working?).
Try calling it like this:
<img src="foo.gif" id="foo" name="foo" onmouseover="fooFunction('foo');"/>
and see if that helps. I don't see any reason why getElementById() would fail, so the only thing I can think of is that it's an ID issue.
May be this line won't work in IE. "newElement.property"
I don't know the exact reason.
You can use this instead of that line
newElement.setAttribute(property,"enter properties here");
In the mean time, i am trying to find out the reason behind the error.
My suggestion would to do something like this.
function fooFunction(sourceElement,property,propertyValue) {
var newElement = document.getElementById(sourceElement);
newElement.setAttribute(property,propertyValue);
};
And your HTML would look like:
<img src="foo.gif" id="foo" name="foo"
onmouseover="fooFunction('fooSpan','class','mouseover_span');"/>
<span id="fooSpan" name="fooSpan">some text here</span>
I'd STRONGLY urge you to consider using jQuery's built-in attr() method which integrates the function you want perfectly across browsers and is incredibly easy to use.
Using your example, if you wanted to change the "src" property for "foo", you could do it in a single line of code:
$("#foo").attr("src","images/whatever.png");
Similarly, if you wanted to change the html WITHIN "fooSpan", all you'd have to do is:
$("#fooSpan").html("something else");
You can even tie these to events that are going to give you a lot more flexibility than the onmouseover property:
$(document).ready(function(){
$("#foo").mouseover(function(){
$("#fooSpan").html("something else");
$("#foo").attr("src","images/whatever.png");
});
});