Clear a single form field in HTML - javascript

I am creating a simple HTML login page, but if I enter data into the fields it stays there when I refresh the page. I have tried
function pageInit(ID) {
this.browserbot.getCurrentWindow().document.getElementById(ID).value = '';
}
but this doesn't do anything (I placed it into onLoad on the inputs of the login.)
HTML:
`
<title>Login</title>
</head>
<body>
<form>
<fieldset>
<legend><h3>Please Login:</h3></legend>
<input type="text" placeholder="Username" name="userId" id="userId" onLoad="pageInit('userId');"><br>
<input type="password" placeholder="Password" name="passwd" id="passwd" onLoad="pageInit('passwd');"><br>
</fieldset>
</form>
</body>
CSS:
<style>
html {
font-family: sans-serif;
text-align: center;
}
a {
font-weight: normal;
}
a:hover {
font-weight: bold;
}
#userId, #passwd {
width: 30%;
height: 40px;
text-align: center;
}
</style>
JS:
<script>
function pageInit(ID) {
this.browserbot.getCurrentWindow().document.getElementById(ID).value = '';
}
</script>

As far as I can tell, the previous answers to not cover the full extent of the question. The original question requests a function to be called to clear the field. However, I'm going to address this in several different ways.
This can be achieved with no JavaScript at all, but simply setting the value attribute as below:
<input type="text" placeholder="Username" name="userId" id="userId" value="" />
<input type="password" placeholder="Password" name="passwd" id="passwd" value="" />
The above will ensure that the fields are clear when the page is loaded, but using only HTML. To do this via JavaScript, multiple things have to be taken into consideration. First, a function should be defined, which needs to be called when the page is loaded.
function clearValue(id) {
document.getElementById(id).value = "";
}
This will simply set the value to blank. However, this gets us back to the original issue. Setting onload for each element does not work, instead we must use window.onload.
window.onload = function() {
clearValue("userID");
clearValue("passwd");
}
This will clear each value one-by-one. However, there is an even better way to do this. JavaScript has built-in functions that make it easy to clear the entire form, or access the elements of the form by their name, even if they are the child of another element within the form. However, keep in mind that only valid input (includes textarea, etc...) fields can be accessed in this way.
So, assuming that the form's ID is myform, this would clear the entire form, no matter how many fields:
document.getElementById("myform").reset();
It's that simple. Using the form element, you can also access the fields by name, as mentioned above.
var f = document.getElementById("myform").elements;
f["userId"].value = "";
f["passwd"].value = "";
Using the above code makes it much quicker, especially if you have more fields.
Putting the JS together, it might look like this:
window.onload = function() {
// using function
clearValue("userID");
clearValue("passwd");
// or, reset entire form
document.getElementById("myform").reset();
// or, clear each field one-by-one
var f = document.getElementById("myform").elements;
f["userId"].value = "";
f["passwd"].value = "";
}

May be it will help you.
<input type="text" value="initial" id="field">
<button id="reset">reset</button>
<script type="text/javascript">
document.getElementById('reset').onclick= function() {
var field= document.getElementById('field');
field.value= field.defaultValue;
};
</script>

Set the input value to " " - in other words, nothing.
This way, the value will be cleared when the page loads.
Implment this like so:
<input value="">
If you'd rather use JS, add this to your onload event:
window.onload = myOnloadFunc;
function myOnloadFunc() {
document.getElementById('userId').value = ''
}

Related

How can I code multiple text boxes in html/css/javascript faster?

I need to make 30 different text inputs slightly farther from one another. How could I do this? There are only three below, but I can't just go through and do all 30.
<!DOCTYPE html>
<html>
<head>
<title>Worksheet</title>
<style type="text/css">
.center {
display: block;
margin-left: auto;
margin-right: auto;
width: 50%;
}
input::placeholder{
color: #d9faa7;
}
</style>
</head>
<body>
<img src="A.png" class = "center">
<form>
<input type="text" id="fname" name="fname" size="2" style='position:absolute;top:210px;left:389px'>
<input type="text" id="fname" name="fname" size="2" style='position:absolute;top:210px;left:446px'>
<input type="text" id="fname" name="fname" size="2" style='position:absolute;top:210px;left:503px'>
</form>
</body>
</html>
the id should be unique, so better apply the attribute of class with the same name to all input fields, which can be used to style them.
also using loop in JS you can solve this problem.
let form = document.querySelector("form");
let node;
let textInputId;
for(let i=0;i<30;i++)
{
node = document.createElement('input');
textInputId= 'fname'+i;
node.setAttribute('id',textInputId);
node.setAttribute('type',"text");
node.setAttribute('name',"fname");
node.setAttribute('size',"2");
form.appendChild(node);
}
If you are going to be using the input elements to perform a certain action you need to make sure the id and the name of each of these elements are different.
And on the other hand, about making 30 different text inputs you can try using dynamic text input in the event that you want to enter text with the same id and name over and over again. Try researching on looping.
If you want to change the way something appears and just its appearance, just use some simple CSS...
input {
display: block,
margin: 5px,
}
The margin here is 5px, you can change as needed. In the end, you may decide to go with a better selector, i.e., <input type="text" ... class="myinputclass">, then your style selector would be: .myinputclass instead of just input.

Javascript onclick fails to send value while onfocus of text input

If a user clicks the save button as the next action after typing street data the onblur action intercepts the onclick and does not trigger the save. However, if you add some padding (30px) and click above the word save it works but below the word Save it does not work, the same as with no padding. I'm certain users will go right from typing text in the input field then click Save which will fail unless they first click somewhere else and then click Save. I’ve provide html and javascript example below. Is there a way using javascript to solve this issue?
<html>
<script>
function showstreet() {
var x = document.getElementById('street').value;
alert(x);
}
function focused() {
document.getElementById('title').style.display='';
document.getElementById('street').value='';
}
function blured() {
document.getElementById('title').style.display='none';
if (document.getElementById('street').value == '') {
document.getElementById('street').value='street';
}
}
</script>
<style>
.pad5 { padding:5px; }
.pad30 { padding:30px; }
</style>
<body>
<div id="title" class="pad5" style="display:none;">STREET NAME</div>
<div>
<input id="street" type="text" name="street" value="street" class="pad5"
onfocus="focused()" onblur="blured()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="showstreet()">
</div>
</body>
</html>
I converted this to jsfiddle but I'm not doing something right (newbie) https://jsfiddle.net/eyo63mav/26/
use onMouseDown instead of onClick in your save button. Then onMouseDown will be fired before onBlur
below is working code
function showstreet() {
var x = document.getElementById('street').value;
alert(x);
}
function focused() {
document.getElementById('title').style.display = '';
document.getElementById('street').value = '';
}
function blured() {
document.getElementById('title').style.display = 'none';
if (document.getElementById('street').value == '') {
document.getElementById('street').value = 'street';
}
}
<div id="title" class="pad5" style="display:none;">STREET NAME</div>
<div>
<input id="street" type="text" value="street" class="pad5" onfocus="focused()" onblur="blured()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="showstreet()">
</div>
Styling rarely makes a difference with events -- now, while that's a blanket statement and in lots of cases we find the styling of an inline element such as a link or a paragraph becoming problematic with inline events such as OnClick and OnFocus, in your case, adding thirty pixels to the size of a button is not your problem.
The problem with your code is that the variable you're assigning your #title's value to is local (it's inside the scope of showstreet(), of which can only be accessed by aforementioned function) -- nevermind that, it's never used again. You save a value to it, it alerts the user, and that's it -- it's never reassigned nor reused, so while it'll forever stay as the street name they entered, you'll never see it unless you apply it to something.
It took me a while to figure out what exactly you're trying to save, but I think I've managed it.
Here's the code I've created:
var streetValue = "Your street will appear here.";
function clickedField() {
// Init title
document.getElementById('title').innerHTML = streetValue;
// Reset field
document.getElementById('street').value = '';
}
function saveValue() {
// Reassign streetValue
streetValue = document.getElementById('street').value;
// Checking if value was left empty
if (streetValue === '') {
document.getElementById('title').innerHTML = "Error: No Street Entered!";
} else {
document.getElementById('title').innerHTML = streetValue;
}
}
(I'm not entirely sure what you had onblur for, but it should be very easy to insert back. If you need some help with that, comment on my reply, I'll be happy to.)
Now if we update the HTML with the approprate functions:
<div id="title" class="pad5" style="">STREET NAME</div>
<div>
<input id="street" type="text" name="street" value="street" class="pad5"
onfocus="clickedField()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="saveValue()">
</div>

Is there anyway to transfer html elements from one client to another with keeping of every entered values like in textboxes?

Let's say I have a page with some html elements.
Those elements are textboxes ,checkboxes ,radiobuttons and other user responsive things.
I need a possibility to transfer whole page from client1 to client2, so client2 will see everything that client1 has set into html elements.
I use WebSocket technology for that, but I don't know how to transfer that elements. If I transfer document.body.innerHTML then client2 see blank elements, instead of filled ones.
On the page could be any amount of any html elements. Is it possible to do something like clonning elements but over websocket? Like I serialize whole document.body and transfer it to another client?
The page are simple html ones. No any server side script are used. I use self made http + websocket server that is working on same port.
I started something that could help you.
You make a loop to get element by Tag (to get all input)
You process them according to the type: text, checkbox, radio,... by saving the value in an attribute (in my exemple, I update the defaultvalue using the value)
then you send it the way you want to. In my example, i show the content using alert; but use your socket.
Maybe you need to add some processing on the the receiving page.
The Text input will show the default value, but you may have to set checkbox 'checked' from the 'value' attribute. I would use a document.onload, with a for each (get element by tag)
Here is the example:
Javascript get Body content into variable
<body>
<p class="first">Hello World Dude</p>
<label for="search_field">my text:</label>
<input type='text' id ='myinput' class='MyIntputField' />
<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>
</body>
<p id="demo" onclick='myFunction()'>Click me to send Data.</p>
<script>
function myFunction() {
inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
switch (inputs[index].type){
case "text":
inputs[index].defaultValue = inputs[index].value;
break;
case "checkbox":
inputs[index].value = inputs[index].checked;
break;
}
}
var $mybody = $("body").html();
}
</script>
You need to use outerHTML instead of innerHTML, however that wont set your input values so you have to do that manually.
// To send your html via websocket
//var ws = new WebSocket('ws://my.url.com:PORT');
//ws.onopen = function(event) { // Make sure it only runs after the web socket is open
document.querySelector('button').addEventListener("click", function() {
var inputs = document.querySelectorAll('input');
Array.prototype.forEach.call(inputs, function(el, i) {
el.setAttribute('value', el.value);
});
document.querySelector('button').setAttribute('data-button', true); // Attributes are rememebered
var HTML = document.querySelector('section').outerHTML;
document.querySelector('#result').innerHTML = HTML;
document.querySelector('#resulttext').textContent = HTML;
//ws.send(HTML);
});
//};
html,
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
div {
background: orange;
border: 3px solid black;
}
<section>
<div>
<input />
</div>
<div>
<input />
</div>
<div>
<input />
</div>
<div>
<input />
</div>
<div>
<input />
</div>
<div>
<button>Generate</button>
</div>
</section>
<p id="resulttext"></p>
<p id="result"></p>

jQuery autocomplete for innerHTML generated textbox

I realize similar questions have been asked thousands times and yet it doesn't seem to work for me. I have a textbox called "movieTitle", it is generated via Javascript by clicking a button. And I'm calling jQueryUI autocomplete on that textbox just like in the official example http://jqueryui.com/autocomplete/#remote.
It works well if I hardcode "movieTitle" in the original page; however it just fails when I create "movieTitle" by changing the innerHTML of the div "formsArea". searchMovies.php is the same with search.php from the example. I had tried many answers from internet and from here. I learned that I would have to use .on() to bind the dynamic element "movieTitle". Still it doesn't seem to work. Even the alert("hahaha") works. Thanks for your time. :) Here's my script:
$(function()
{
$(document).on('focus', '#movieTitle', function(){
//alert("hahaha");
$("#movieTitle").autocomplete({
source: "../searchMovies.php",
minLength: 2
});
}
);
window.onload = main;
function main()
{
document.getElementById("movieQuery").onclick = function(){showForms(this.value);};
document.getElementById("oscarQuery").onclick = function(){showForms(this.value);};
// displays query forms based on user choice of radio buttons
function showForms(str)
{
var heredoc = "";
if (str === "movie")
{
heredoc = '\
<h1>Movie Query</h1>\
<form action="processQuery.php" method="get">\
<div class="ui-widget">\
<label for="movieTitle"><strong>Name: </strong></label>\
<input type="text" id="movieTitle" name="movieTitle" />\
<input type="submit" name="submitMovie" value="Submit" />\
</div>\
</form>';
//document.getElementById("formsArea").innerHTML = heredoc;
//$("#formsArea").append(heredoc);
$("#formsArea").html(heredoc);
}
else if (str === "oscar")
{
heredoc = '\
<h1>Oscar Query</h1>\
<form action="processQuery.php" method="get">\
<strong>Name: </strong>\
<input type="text" name="oscarTitle" />\
<input type="submit" name="submitOscar" value="Submit"/>\
</form>';
document.getElementById("formsArea").innerHTML = heredoc;
}
}
}
});
The HTML is:
<form action=$scriptName method="get">
<label for="movieQuery"><input type="radio" name="query" id="movieQuery" value="movie" />Movie Query</label>
<label for="oscarQuery"><input type="radio" name="query" id="oscarQuery" value="oscar" />Oscar Query</label>
</form>
<div id="formsArea">
<b>Please choose a query.</b>
</div>
You should check for the URL you're sending an AJAX request to. The paths in script files are relative to the page they're being displayed in. So albeit your script is in /web/scripts/javascripts/js.js, when this file is included in /web/scripts/page.php, the path to /web/scripts/searchMovies.php should be searchMovies.php instead of ../searchMovies.php because your script is being used in /web/scripts/.
Good ways to avoid such confusion is to
a. use absolute URL
b. the URL that're relative to root of your domain (that start with a /),
c. or define your domain's path in a variable, var domain_path = 'http://www.mysite.com/' and use it in your scripts.
I hope it clarifies things :)
Relative Paths in Javascript in an external file

How to show/hide a div with javascript

I'm currently making a registration page for a site and need to show a typical password confirmation message. How would I make a script to hide and show a div?
This is as far as I've got:
<html><head>
<script language="javascript">
function correctpassword()
var password="password"
var confirmpassword="confirmpassword"
if (password1 != password2)
{
showcss="unconfirmed"
}
else
{
showcss="confirmed"
}
</script>
</head>
<body>
<form>
<u>Personal Details</u>
First Name: <input type="text" id="firstname">
Last Name: <input type="text" id="lastname">
Date of Birth:
Gender: Male Female
<u>Login Details</u>
Email Adress:<input type="text" id="email">
Username:<input type="text" id="username">
<!--check avalibility-->
Password:<input type="text" id="password">
Confirm Password:<input type="text" id="confirmpassword">
<!--Javascript if "password" doesnt equal "confirm password" showcss passwords don't match-->
<button type="button" onclick="correctpassword()">Display Date</button>
</form>
</body>
</html>
PS:The variables may be wrong.
Assuming you are talking about hiding / showing a div, spanor other similar element in HTML, you can use the jQuery JavaScript framework. For example:
$('#element_to_show').show();
$('#element_to_hide').hide();
You can trigger the hide / show via events, e.g. key press or user leaving the input element, in jQuery as well.
Control your styles and appearance with className property that applied to class markup attribute.
Try to avoid .style property of the elements and add/remove some classes instead. It will give you more control and simplify maintenance in the future.
in css:
.show{
display:block;
}
.box{
display:none;
}
in html:
<div id="passConfirm"></div>
<div id="box"></div>
in your script:
var confirmEl,
confirmBox;
confirmEl = document.getElementById('passConfirm');
confirmBox = document.getElementById('box');
confirmEl.addEventListener('click', showBox, false);
function showBox () {
confirmBox.className += ' show';
}
As mentioned, you can use some libraries that helps to work with DOM or write your own functions helping to add and remove some classes, check for hasClass method etc.
I'm on my phone, hence the short answer.
Easiest way is to get the id of the element like document.getElementById and place that into a variable.
Then use the style property like
Obj.style.display = "none";
To hide it.

Categories