Please check the link below:
http://jsfiddle.net/cT9kg/4/
As you can see its a search field with a button.
If you have trouble understanding what I mean below please just look at the "Title" input on the Ask a question page.
The input has autofocus on.
BUT
How can I have it so text is already in the input with autofocus on but as soon as someone types into the input the text disappears.
AND
When someone has entered text in the input but then deletes it, it goes back to the way it was at the beginning: on focus with text in it instructing the person what to type in the input.
Thanks!
James
You could define the default value.
On focus - empty value, if the value is default value.
When the element lose the focus, You could check, if it's empty, and if Yes - restore the default value.
I've tested this as working, just make sure you put the <script> part just before the </body> tag.
<input type="text" class="input1" autofocus="focus" id="search" value="Type here..." onKeyPress="checkValue()" />
----
<script type="text/javascript">
var searchEl = document.getElementById('search');
var defaultValue = searchEl.value;
function checkValue() {
if (searchEl.value == defaultValue) {
searchEl.value = "";
}
}
</script>
You could use the HTML placeholder attribute, but in the majority of browsers that won't achieve quite what you are after: as soon as the input is focused, the placeholder text disappears.
For functionality akin to iOS (found on sites such as Twitter as well), you need to use JavaScript. One example can be seen online here.
This similar question (and this one) have some useful alternatives and code examples.
You're correctly using autofocus, which is fine but has patchy browser support. You can add in a JS fallback, like this (taken from here):
<script>
window.onload = function () {
if (!("autofocus" in document.createElement("input"))) {
document.getElementById("s").focus();
}
}
</script>
Wow. I tried digging around in the source code for the Ask a question page. Talk about convoluted.
Here is the CSS File.
While it seems the relevant bits are thus, they don't seem to DO much more than format (other than the edit-field-overlay trick.
.form-item {padding:10px 0px 15px 0px;}
.ask-title {margin-bottom:-15px;margin-top:-10px;}
.ask-title-table {width:668px;}
.ask-title-field {width:610px;}
.ask-title-cell-value {padding-left:5px;}
.edit-field-overlay {display:none;}
HTML (some TD tags removed):
<div class="form-item ask-title">
<table class="ask-title-table">
<tr>
<td class="ask-title-cell-value">
<input id="title" name="title" type="text" maxlength="300" tabindex="100" class="ask-title-field" value="">
<span class="edit-field-overlay">what's your programming question? be specific.</span>
</td>
</tr>
</table>
</div>
But I totally could NOT figure out the relevant Javascript bits. As there are NO onEvent handlers for this form that I can see, the only reference to this field (title) would be in the prepareEditor function.
Anybody care to try and explain it to a relative newbie??
Related
I have an assigment, I don't understand it as i'm beginner.
Create a javascript script which will modify the DOM of a web-page.
The script must add a form with 4 elements: name, email, message(textarea) and submit button. Each element must contain a label with its name. For example, name field is input type, you must create still from javascript a label named "Name", same for the others except submit button. Also, each laber must have a colour added from javascript(red, blue, yellow). When you click submit button, it must have an alert: "Are you sure you want to send this message?".
Thank you in advance.
I need to use only Javascript for this and I can only find answers
that use HTML
Web applications use HTML to contain, render and display elements in the viewport (browser window).
Where do you intend to render the form and capture user input?
You can build the DOM structure using JavaScript alone, however, there will still be a HTML file, which will contain the HTML elements created using javascript.
Please provide clarity as to your desired goal and what type of application this is being used for.
My gut feeling, for simplicity, is that you will require to use HTML as your template file, and JavaScript for interactivity and manipulation of the HTML file.
The script must add a form with 4 elements: name, email, message(textarea) and submit button. Each element must contain a label with its name. For example, name field is input type, you must create still from javascript a label named "Name", same for the others except submit button. Also, each laber must have a colour added from javascript(red, blue, yellow). When you click submit button, it must have an alert: "Are you sure you want to send this message?". That's it.
This is a start, just to try to help you to understand the concepts.
I do, however, implore you to go and explore with confidence - you won't break anything, just give it a try!
I recommend you try taking a look at some of these articles, have a look at my (very rudimentary) code below, and feel free to ask any questions you have!
JS:-
W3 Schools JS and HTML reference
HTML:-
W3 Schools: HTML Forms
W3 Schools: Label Tag
W3 Schools: Text Area Tag (This has been left out of the solution on purpose - give it a try!!)
(function divContent() {
//Create a 'div' as a container for our form
var div = document.createElement('div');
// Perhaps you could style it later using this class??
div.className = 'row';
// I have used backticks to contain some more normal looking HTML for you to review, it's not complete though!!
div.innerHTML = `<form action="javascript:" onsubmit="alert('Your message here, or, run a function from your JavaScript file and do more stuff!!')">
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="Mickey Mouse">
<br>
<label for="email">Email:</label>
<input type="text" name="email" id="email" value="mickey#mouse.co.uk">
<br><br>
<input type="submit" value="Submit">
</form> `
// Get the body of the document, and append our div containing the form to display it on page
document.getElementsByTagName('body')[0].appendChild(div);
}());
<!DOCTYPE html>
<html>
<head>
<meta name="author" content="CoderYen | Wrangling with 0s & 1s Since The Eighties">
</head>
<body>
</body>
</html>
I have an HTML form where users are able to input their mobile number. See below:
<form class="formulario" action="signature_test.html" method="get" onsubmit="return signature_Alert()" >
Mobile (mgrs): <input type="text" name="mobile" id="mobile"><br>
<br>
<input type="submit" value="Generate Signature">
</form>
Whatever the user enters, is then populated in another HTML file. It innerHTML the text "Default":
<font color="#008080">Mobile: </font></b><font id="mobileInput">Default </font><br>
However, I would like that if the user leaves the mobile field blank, to have the "Mobile:" and the "Default" not displayed. Is that possible with Javascript?
By the way, this would be the Javascript that innerHTML the "Default" text.
<script>
var values = window.location.search.substring(1).split('&')
var mobile = values[3].split('=')[1]
document.getElementById('mobileInput').innerHTML = mobile;
</script>
Thanks.
Sure, just wrap the content in an element you can target and modify:
<span id="mobileInputContainer">
<font color="#008080">Mobile: </font></b><font id="mobileInput">Default </font><br>
</span>
Then just adjust that element's style similar to how you already adjust another element's content:
if (mobile.length < 1) {
document.getElementById('mobileInputContainer').style.display = 'none';
}
You'd of course want to double-check the actual value you're getting for mobile in your code. Make sure it doesn't have whitespace, etc. Or really tweak whatever your logic is for determining that no value is present to display. But the actual act of hiding the element is simple, just set the style to be hidden.
Additionally, I'd like to echo a comment above. <font> tags really shouldn't be used anymore. You'll find a little bit of an introduction to CSS styling can go a long way here. I recommend some introductory tutorials on the subject.
You also appear to have an errant </b> in your code. Perhaps you're not showing us the entire content. Either way, you'll want to double-check your HTML as well. Always start with valid and well-formed HTML before using any JavaScript or CSS, or behavior may not be what you expect.
i have an issue with innerHTML and getElementsById(); method but I am not sure if these two methods are the root of the issues i have.
here goes my code :
<script type="text/javascript">
function clearTextField(){
document.getElementsById("commentText").value = "";
};
function sendComment(){
var commentaire = document.getElementById("commentText").value;
var htmlPresent = document.getElementById("posted");
htmlPresent.innerHTML = commentaire;
clearTextField();
};
</script>
and my HTML code goes like this:
<!doctype html>
<html>
<head></head>
<body>
<p id="posted">
Text to replaced when user click Send a comment button
</p>
<form>
<textarea id="commentText" type="text" name="comment" rows="10" cols="40"></textarea>
<button id="send" onclick="sendComment()">Send a comment</button>
</form>
</body>
</html>
So theorically, this code would get the user input from the textarea and replace the text in between the <p> markups. It actually works for half a second : I see the text rapidly change to what user have put in the textarea, the text between the <p> markup is replaced by user input from <textarea> and it goes immediately back to the original text.
Afterward, when I check the source code, html code hasn't changed one bit, given the html should have been replaced by whatever user input from the textarea.
I have tried three different broswer, I also have tried with getElementByTagName(); method without success.
Do I miss something ? My code seems legit and clean, but something is escaping my grasp.
What I wanted out of this code is to replace HTML code between a given markup (like <p>) by the user input in the textarea, but it only replace it for a few milliseconds and return to original html.
Any help would be appreciated.
EDIT : I want to add text to the html page. changing the text visible on the page. not necessarily in the source. . .
There is no document.getElementsById, however there is a document.getElementById. This is probably the source of your problem.
I don't think there is any document.getElementsById function. It should be document.getElementById.
"To set or get the text value of input or textarea elements, use the .val() method."
Check out the jquery site... http://api.jquery.com/val/
I have a page where you can click a link that says "add a keyword" and an input will appear and you can enter the keyword, and then convert it into a span tag on blur or the "return" key. However, I've been adding onto it to allow for an "autocomplete" feature, so I'm trying to insert a
<ul></ul>
after my input in order to do a .load inside the list.
The relevant code I have is:
var addKeywordId = 0;
$('a.add_keyword').live('click', function(){
$(this).before('<input type="text" class="add_keyword" id="addKeyword'+addKeywordId+'" /><ul><li>hi</li></ul>');
$('.add_keyword').focus();
addKeywordId++;
});
The problem is, that my HTML structure ends up looking like this:
<ul><li>hi</li></ul>
<a class="add_keyword">+ add keyword</a>
<input id="addKeyword0" class="add_keyword" type="text />
INSTEAD OF
<input id="addKeyword0" class="add_keyword" type="text />
<ul><li>hi</li></ul>
<a class="add_keyword">+ add keyword</a>
Anybody know why my HTML is added out of the order I specified??
Thanks
EDIT: This seems to be working fine in Google Chrome, but not in Mozilla Firefox.. :(
This is likely due to the weird rejiggering of code Firefox does to try to display things even when there are errors. I've seen it where I miss a closing div, IE freaks out (as it should) and Firefox looks fine, as it ignores that you missed adding the ending div and guesses.
You could try a 2 stage thing. I would add an id to the ul tag, then add the input before it.
$(this).before('<ul id="ulid"><li>hi</li></ul>');
$('#ulid').before('<input type="text" class="add_keyword" id="addKeyword'+addKeywordId+'" />');
Happy haxin.
_wryteowl
I'm working on a .net website and I have a bit of a situation.
Say I have...
<input type="text" class="name" id="name">
<p></p>
<input type="text" class="surname" id="surname">
<p>Error!</p>
What Id like to do, using javascript, is detect that the second paragraph tag says 'Error!' and add a class to the input tag before it.
I know this seems like a bit of a strange way of working but any advice would be greatly appreciated!
Hi all, the adivce and answers i was given worked fine on a fresh page on jsfiddle only i cant seem to get them to work on my actual site.
My P and input tags are constructed like this....
<li class="yourdetli">
<label class="yourdet">Street Name</label>
<input type="text" id="ctl00_ContentPlaceHolder1_TB_SName" name="ctl00$ContentPlaceHolder1$TB_SName">
<span style="color: Red; display: none;" class="errorp" id="ctl00_ContentPlaceHolder1_RequiredFieldValidator6">
<p>You must complete this field</p></span>
</li>
and my JS is...
<script type="text/javascript">
$(document).ready(function() {
$('p:contains("You must complete this field")').prev('input').addClass('error');
});
</script>
only for some reason it doesnt seem to add my class, can anybody see why?
You can use
$('p:contains("Error")').prev('input').addClass('error');
Maybe try
$("p:eq(1):contains('Error!')").prev('input').addClass('error');
You can check the text value of the second <p> tag by using jQuery. You'll need a selector that finds it (in this example, it is the last <p> tag).
if ($("p").last().text() == "Error!") {
$("input#surname").addClass("myClass");
// do other stuff here
}
Try -
if ($("input#surname").next("p:contains('Error!')").length > 0) {
$("input#surname").addClass('yourclass');
}
I'd recommend adding the error css class to your validator's CssClass property so that its already rendered server side. This way if you change your error message, you won't have to change any javascript to display it.
<asp:RequiredFieldValidator ID="requiredValidator" CssClass="error" ControlToValidate="..." ErrorMessage="You must complete this field"/>
Or if you're looking to style all of your validators with the same class, you can add the following script to your master page.
$(document).ready(function()
{
if (Page_Validators != null)
{
for (i = 0; i < Page_Validators.length; i++)
{
Page_Validators[i].className = "error";
}
}
});
See http://www.jrummell.com/blog/index.php/2009/08/apply-the-same-css-class-to-all-validators-in-a-web-project/ for more information.