Change input value based on another input's value - javascript

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>

Related

How do I make an OnClick function that will change a word when a user clicks it to another word?

Okay so, I want to make an OnClick function in JavaScript that makes it so when a user clicks on it, it will change the word. Is there a replaceword() function or something that which will let me do so? I know this is not real code, but for example:
<p>Quickly <span onclick="replaceword('Surf');">Search</span> The Web!</p>
If there is, then can someone tell me also how to reverse the code maybe? So when they click on it the second time, it will change back to "Search"?
If you want to jump between multiple words, you'll need to store them someplace. You could have two words in the sentence, and toggle the visibility of one or the other (which doesn't scale well), or you could even store them as values on an attribute placed on the element itself.
<p>Hello, <span data-values="World,People,Stack Overflow">World</span>.</p>
I have placed all possible values within the data-values attribute. Each distinct value is separated from the other values by a comma. We'll use this for creating an array of values next:
// Leverage event-delegation via bubbling
document.addEventListener( "click", function toggleWords ( event ) {
// A few variables to help us track important values/references
var target = event.target, values = [], placed;
// If the clicked element has multiple values
if ( target.hasAttribute( "data-values" ) ) {
// Split those values out into an array
values = target.getAttribute( "data-values" ).split( "," );
// Find the location of its current value in the array
// IE9+ (Older versions supported by polyfill: http://goo.gl/uZslmo)
placed = values.indexOf( target.textContent );
// Set its text to be the next value in the array
target.textContent = values[ ++placed % values.length ];
}
});
The results:
The above listens for clicks on the document. There are numerous reasons why this is a good option:
You don't need to wait for the document to finish loading to run this code
This code will work for any elements added asynchronously later in the page life
Rather than setting up one handler for each element, we have one handler for all.
There are some caveats; you may run into a case where the click is prevented from propagating up past a particular parent element. In that case, you would want to add the eventListener closer to your target region, so the likeliness that bubbling will be prevented is less.
There are other benefits to this code as well:
Logic is separated from markup
Scale to any number of values without adjusting your JavaScript
A demo is available for your review online: http://jsfiddle.net/7N5K5/2/
No, there isn't any native function, but you can create on your own.
function replaceword(that, word, oword) {
that.textContent = that.textContent == oword ? word : oword;
}
You can call it like this:
<p>Quickly<span onclick="replaceword(this,'Surf','Search');">Search</span>The Web!</p>
Live Demo: http://jsfiddle.net/t6bvA/6
<p id="abc">Hello</p>
<input type="submit" name="Change" onclick="change()">
function change(){
var ab=document.getElementById('abc').value;
ab.innerHTML="Hi, Bye";
}
I think so this should help you, you should go to site such as w3schools.com, its basic and it will answer your doubt
You can try something like this if you wanna use jQuery
http://jsfiddle.net/R3Ume/2/
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<body>
<p>Hello <a id='name'>John<a></p>
<input id="clickMe" type="button" value="replace" onclick="onClick();" />
<script>
function onClick() {
$('#name').text('world');
}
</script>

Getting my javascript output to display in my HTML

I am sure this is a simple question.
To begin really playing with javascript and understand it I need to have the environment to see what my output is. I have done lessons in javascript but need to actually get the HTML and javascript talking.
What I am looking to do:
Have a user input information into an text box and have it show the result in the html.
is the sky blue? Yes (makes true be displayed on my HTML)
is the sky blue? No (makes false be displayed in my HTML)
currently i have no idea if my javascript is doing anything!
Here is my code:
HTML:
<form action="" onsubmit="return checkscript()">
<input type="text" name="value">
<input type="submit" value="Submit">
Javascript:
function checkscript() {
for (i=0;i<4;i++) {
box = document.example.elements[i];
if (!box.value) {
alert('You haven\'t filled in ' + box.name + '!');
box.focus()
return false;
}
}
return true;
}
document.write(box);
I am so confused but need to see the results of what i am doing to see where to fix things, i tried using console in chromes inspect elements function but this has confused me more.
Can someone help and clean the code up to make sense by labelling everything as what they do?
box? check script?
Thanks :)
I updated the jsfiddle I had made for you. It's a working version that might get you started.
HTML
<!-- I avoided all the mess of forms, since that submits to a server, and that's more than you want right now. Note that I added ids to each input. Ids make it very easy to access the elements later. -->
<input type="text" name="value" id="fillIn">
<input type="button" value="Submit" id="button">
JS
// My methodology here is totally different, since I directly get the element I care about
function checkscript() {
// find the element in the DOM
var box = document.getElementById("fillIn");
// check for a value
if (box.value) {
// if there is one, add a new div. That's probably not what you'll want in the long run, but it gives you something to work with (and seems to match your old idea of using document.write. I have never yet used document.write, though others with more experience than I may like the concept better.
// This creates a new element. If you press F12 and look at this in your debugger, you'll see it actually appear in the HTML once it's appended
var newElement = document.createElement("div");
// Set the value to what you want
newElement.innerHTML = box.value;
document.body.appendChild(newElement);
} else {
alert('You haven\'t filled in ' + box.name + '!');
box.focus()
// No returns necessary, since we're not dealing with formsubmittal.
}
}
// This hooks up the function we just wrote to the click event of the button.
document.getElementById("button").onclick = checkscript;
This may or may not be what you want, but it's at least a place to get started.
A few things to start out:
1.) Make sure all elements have end tags
<input type="text" name="value" />
Note backslash at end of tag.
2.) You are using a form tag, which submits a form to a server side component.
Suggest you need to use the onclick event. Which is available on all input controls. Suggest you start with buttons so:
<input type="text" name="value" onclick="myFunction()" />
<script type="text/javascript">
function myFunction() {
document.write("Hello");
console.log("Hello");
}
</script>
Writes stuff directly to the html and console. Hope that gets you started.
Regards,
Andy

Alternative to "Pattern" Attribute for Input

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>

javascript function return to a form input element not working

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=''; ">

How to get a DOM Element from a jQuery selector?

I'm having an impossibly hard time finding out to get the actual DOMElement from a jQuery selector.
Sample Code:
<input type="checkbox" id="bob" />
var checkbox = $("#bob").click(function() { //some code } )
and in another piece of code I'm trying to determine the checked value of the checkbox.
if ( checkbox.eq(0).SomeMethodToGetARealDomElement().checked )
//do something.
And please, I do not want to do:
if ( checkbox.eq(0).is(":checked"))
//do something
That gets me around the checkbox, but other times I've needed the real DOMElement.
You can access the raw DOM element with:
$("table").get(0);
or more simply:
$("table")[0];
There isn't actually a lot you need this for however (in my experience). Take your checkbox example:
$(":checkbox").click(function() {
if ($(this).is(":checked")) {
// do stuff
}
});
is more "jquery'ish" and (imho) more concise. What if you wanted to number them?
$(":checkbox").each(function(i, elem) {
$(elem).data("index", i);
});
$(":checkbox").click(function() {
if ($(this).is(":checked") && $(this).data("index") == 0) {
// do stuff
}
});
Some of these features also help mask differences in browsers too. Some attributes can be different. The classic example is AJAX calls. To do this properly in raw Javascript has about 7 fallback cases for XmlHttpRequest.
Edit: seems I was wrong in assuming you could not get the element. As others have posted here, you can get it with:
$('#element').get(0);
I have verified this actually returns the DOM element that was matched.
I needed to get the element as a string.
jQuery("#bob").get(0).outerHTML;
Which will give you something like:
<input type="text" id="bob" value="hello world" />
...as a string rather than a DOM element.
If you need to interact directly with the DOM element, why not just use document.getElementById since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.
But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.
UPDATE: Based on a comment:
Here is a post with a nice explanation: http://www.mail-archive.com/jquery-en#googlegroups.com/msg04461.html
$(this).attr("checked") ? $(this).val() : 0
This will return the value if it's checked, or 0 if it's not.
$(this).val() is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.

Categories