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

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.

Related

Clear a single form field in HTML

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 = ''
}

Two separate forms, with inputs that have same name and id

I have two forms on the same page with two labels with for attributes pointing to two checkboxes that have the same ID and name.
When I click one of the second form labels it checks the first form checkbox.
In this case the problem lies when you click the 'x name 2' label, it checks the 'x name' check box, even though they are in different forms:
.customCheckbox div label {
padding: 5px;
background-color: white;
border: 2px solid #aaaaaa;
background-image: none;
}
.customCheckbox div input {
margin: 8px auto;
padding: 5px;
text-align: left;
margin-left: -999999px;
float: left;
}
.customCheckbox input[type=checkbox]:checked ~ label,
.customCheckbox input[type=radio]:checked ~ label {
background-color: #117399;
color: #eeeeee;
}
.customCheckbox input[type=radio]:checked ~ label {
background-color: #117399;
color: #eeeeee;
}
<form style="margin:30px;">
<div class="customCheckbox">
<div>
<input id="x" name="x" type="checkbox"/><label for="x">x name</label>
</div>
<br/>
<div>
<input id="y" name="y" type="checkbox"/> <label for="y">y name</label>
</div>
</div>
</form>
<form style="margin:30px;">
<div class="customCheckbox">
<div>
<input id="x" name="x" type="checkbox"/><label for="x">x name 2</label>
</div>
<br/>
<div>
<input id="y" name="y" type="checkbox"/> <label for="y">y name 2</label>
</div>
</div>
</form>
I'd like to stay away from renaming the elements (as there are quite a few places this occurs)
I'd like to try to stay away from JavaScript (if possible)
Since I am using CSS for styling the labels and checkboxes I cannot nest the checkbox inside the label (because you can't style a parent element in CSS)
It is not legal to use the same id property twice on the same page. It does not matter at all if the elements are on the same form or different forms.
They can absolutely have the same name property. Names are what gets sent to your server. You can have fifty elements on the same form with the same name if you want.
But the whole purpose of IDs is that they absolutely must be unique on the page.
So simply make the first one ... id="x1" name="x" ... and the second ... id="x2" name="x" ... and then make your labels point to for="x1" or for="x2"
There's no problem when different input fields have the same name, as long as they're in a different form or they represent the same parameter (eg. in the case of radio buttons).
However, you should NEVER use the same id for different HTML elements.
From the HTML5 specs:
The id attribute specifies its element's unique identifier (ID).
If you make your ids unique, your labels will work as expected.

How to get span element with no id which is inside a div with no id

I have 2 span elements inside 2 div elements. Both span elements have no id and both div elements also have no id.
The 1st div has the 1st input element with an id (id_name) and then have the 1st span element after it.
The 2nd div has the 2nd input element with an id (id_password) and then have the 2nd span element after it.
I have a javascript function which I call on submit of form. Inside that function I can get the 1st input element in a variable element_id_name and the 2nd input element in a variable element_id_password. Now how can I get the 1st span element which comes after 1st input element? And how can I get the 2nd span element which comes after 2nd input element? Since I dont have id for span elements, I cannot use document.getElementById(). Is there a way to get 1st span element by reference to 1st input element?
This is my code:
<html>
<head>
<meta charset="ISO-8859-1">
<title>test</title>
<style type="text/css">
.error_noshow{
display: none;
}
.error_show{
color: red;
}
</style>
<script type="text/javascript">
function validate() {
var element_id_name = document.getElementById("id_name");
var element_id_password = document.getElementById("id_password");
return false;
}
</script>
</head>
<body>
<form id="form_login" method="post" action="" onsubmit="validate();">
<div>
<label for="id_name">User Name:</label>
<input type="text" id="id_name" name="txt_user_name">
<span class="error_noshow">Required field</span>
</div>
<div>
<label for="id_password">Password:</label>
<input type="password" id="id_password" name="txt_password">
<span class="error_noshow">Required field</span>
</div>
<button type="submit">Submit</button>
</form>
</body>
</html>
Thank you for reading my question.
var spans = document.getElementsByTagName('span');
span[0] is the first span, span[1] is the second span. However it's not the preferred way to do this. Use jQuery to make it easier or add an id or classname
To access next span element you can use nextElementSibling property.
<script type="text/javascript">
function validate() {
var element_id_name = document.getElementById("id_name");
var element_id_password = document.getElementById("id_password");
var firstSpan=element_id_name.nextElementSibling;
return false;
}
</script>
But keep in mind that nextElementSibling not working in all version of browsers so you can simulate this using nextSibling http://www.w3schools.com/dom/prop_node_nextsibling.asp;
You can use querySelector to find the elements by their attributes.
function validate() {
var element_id_name = document.querySelector("[name=txt_user_name]");
var element_id_password = document.querySelector("[name=txt_password]");
console.log(element_id_name, element_id_password);
return false;
}
.error_noshow{
display: none;
}
.error_show{
color: red;
}
<form id="form_login" method="post" action="" onsubmit="validate();">
<div>
<label for="id_name">User Name:</label>
<input type="text" id="id_name" name="txt_user_name">
<span class="error_noshow">Required field</span>
</div>
<div>
<label for="id_password">Password:</label>
<input type="password" id="id_password" name="txt_password">
<span class="error_noshow">Required field</span>
</div>
<button type="submit">Submit</button>
</form>
I'm not answering the question because someone already did, but it seems like you want to check if the user typed something in both field, you could skip the javascript and use the HTML5 tag "required" like so
<input type="text" require />.
The user will have an error message if he tries to submit. But keep in mind that old version of IE will skip this check.

Radio button and textbox

I am javascript learner and have been trying to do this
two radio buttons but1 but2
two text boxes box1 box2
What I need to do is
when but1 is selected, box1 should be editable and box2 should be readonly.
when but2 is selected, box2 should be editable and box1 should be readonly.
On page load both the text boxes should be readonly.
My code is as below
<style type="text/css">
.field-name {
color: #444;
font-family: verdana;
font-size: 0.85em;
line-height: 2em;
}
</style>
<script type="text/javascript">
function makeChoice() {
if (document.getElementById('but1').checked = true) {
document.getElementById('box2').readonly = true;
}
else if (document.getElementById('but2').checked = true) {
document.getElementById("box1").readonly = true;
}
}
</script>
<html>
<body>
<table>
<input type="radio" id="but1" name="vals" onclick="makeChoice()">
<input type="radio" id="but2" name="vals" onclick="makeChoice()">
<input type="text" id="box1" value="abcde">
<input type="text" id="box2" value="pqrst">
</table>
</body>
<html>
I do not want to disable the textboxes but make them readonly, so that on form submit i will have the textbox values that i can send to the server.
I do not know what mistake im doing here. Any help will be greatly appreciated. Thanks
You need to set the "readonly" attibute like this:
document.getElementById('box2').setAttribute('readonly','readonly')
and clear it like thisL
document.getElementById('box2').setAttribute('readonly','')
hope, this code would be of any help.
here is my try:
http://jsfiddle.net/ylokesh/AAAVp/1/
You're making a couple of mistakes.
First of all, your css and javascript code must be included into the <head> tag, which should be placed soon after <html>, before <body>.
Secondly your if statements are incorrect: with just one = sign you assign a value to a variable, you have to use two (or in this case three) of them to check the variables against a value, like this: if (something == value).
Lastly, you'd better use the functions setAttribute() and removeAttribute() to modify the values of the readonly attribute.
The complete code would be:
<html>
<head>
<style type="text/css">
.field-name {
color: #444;
font-family: verdana;
font-size: 0.85em;
line-height: 2em;
}
</style>
<script type="text/javascript">
function makeChoice() {
if (document.getElementById('but1').checked === true) {
document.getElementById('box2').setAttribute('readonly','readonly');
document.getElementById('box1').removeAttribute('readonly','');
}
else if (document.getElementById('but2').checked === true) {
document.getElementById('box1').setAttribute('readonly','readonly');
document.getElementById('box2').removeAttribute('readonly','');
}
}
</script>
</head>
<body>
<table>
<input type="radio" id="but1" name="vals" onclick="makeChoice()">
<input type="radio" id="but2" name="vals" onclick="makeChoice()">
<input type="text" id="box1" value="abcde">
<input type="text" id="box2" value="pqrst">
</table>
</body>
<html>
Basically, you're using = instead of == on your conditionals. Also, you always have to set readonly to false on the one of the boxes, or you'll end up with two readonly boxes after two clicks. Try this:
EDIT the attribute name is readOnly, not readonly. Code also edited to manipulate the attribute directly, instead of using setAttribute. See working version on jsfiddle:
function makeChoice() {
document.getElementById('box1').readOnly = document.getElementById('but2').checked
document.getElementById('box2').readOnly = document.getElementById('but1').checked
}
In your IF statements, you are setting a variable, not testing whether it is in one state or another. You need to use this:
if (document.getElementById('but1').checked == true) {
Note that there are two equals signs. This checks whether the two are the same. Basically, one equals sets, two equals compares. Of course change both IF statements to the two equals signs.
Also, you say that onload both should be readonly. To do this, add
readonly="readonly"
to the textboxes. And furthermore, you need to turn readonly off on the appropriate textbox when a radio button is clicked.
So, altogether:
<style type="text/css">
.field-name {
color: #444;
font-family: verdana;
font-size: 0.85em;
line-height: 2em;
}
</style>
<script type="text/javascript">
function makeChoice() {
if (document.getElementById('but1').checked) {
document.getElementById('box2').setAttribute('readOnly','readonly');
document.getElementById('box1').removeAttribute('readOnly','');
} else if (document.getElementById('but2').checked) {
document.getElementById('box1').setAttribute('readOnly','readonly');
document.getElementById('box2').removeAttribute('readOnly','');
}
}
</script>
<html>
<body>
<table>
<input type="radio" id="but1" name="vals" onclick="makeChoice()">
<input type="radio" id="but2" name="vals" onclick="makeChoice()">
<input type="text" id="box1" value="abcde" readonly="readonly">
<input type="text" id="box2" value="pqrst" readonly="readonly">
</table>
</body>
<html>

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