I'd like to display the page title in a form input field using plain javascript.
I've tried this but it doesn't work. What am I doing wrong?
<input type="text" value="javascript:document.title;"/>
Also, how can I check if the input field is actually there and do nothing if so. I'd like to do this check to avoid JS errors.
No, it would not. value is never executed. Try this instead:
<title>title text here</title>
<!-- ... -->
<input type="text" id="titleinput">
<script>
var theInput = document.getElementById('titleinput')
if (theInput) {
theInput.value = document.title;
}
</script>
EDIT: Shown how to test for existence of the input, and removed the arcane way of finding title since there is a better way. Although, in this case, you might know that you've created the input field, and take it as granted that it is there (your program should make an error if it's not, just like it should make an error if you delete a line from the code itself. I would only have such a check on HTML that I do not control. It might be a personal choice though, I know I don't do enough defensive programming.
EDIT2: jasonscript has a point, but I thought it would confuse the OP even more. If you want a best-practices answer though, you'd do some variety of this, to avoid global variables:
(function(theInput) {
if (theInput) {
theInput.value = document.title;
}
})(document.getElementById('titleinput'));
value attribute is a string, it wouldn't execute if you place some JS in it.
You would set its value with JS after the input is ready in DOM:
<input type="text" value="">
<script>
document.querySelector('input').value = document.title;
</script>
Whereas querySelector will give you the first input element in the DOM.
Specificly, you can pass any css selectors to the method, e.g. ID selector in following code. Please note different parameter querySelector is using:
<input type="text" value="" id="titleInput">
<script>
document.querySelector('#titleInput').value = document.title;
</script>
More on querySelector, visit selectors api spec.
This would work:
HTML:
<title>awesome site</title>
<input type="text" id="textinput" value=""/>
JAVASCRIPT:
<script>
var title = document.title;
var textinput = document.getElementById('textinput');
if (textinput) {
textinput.value = title;
}
</script>
or shorter:
<script>
document.getElementById('textinput').value = document.title;
</script>
Related
Okay, first thing, I had a lot of trouble thinking of a title for this, and also of what to search for in Google. So that may just be me being stupid, but here is what I would like you help with.
I have a form, that has a button that will add additional input fields, but I would like the the name of the field to iterate everytime the button is pressed. E.g. the first time it will be:
<input type="textfield" name="field1" value=""/>
Then the second time it is pressed, it will be:
<input type="textfield" name="field2" value=""/>
I also have a small example of what I currently have here: http://jsfiddle.net/5gh75/14/
Please let me know if you can help me, or if you require more info thanks :)
The best way to handle this is to name them all field[].
When handled by the server-side code, it will build an array for you. For instance, in PHP you would get $_POST['field'][0], $_POST['field'][1] and so on.
For your example:
JQuery
var i=0;
$('span.add').click(function () {
$('<input>').attr({
type: 'textfield',
name: 'program'+i
}).appendTo('#addsoftware');
i++;
});
JSFiddle.
But #Kolink-s answer is much better.
Edit: I just saw the previous posts after sending this. Using an array would definitely be better, and JQuery is always nice :).
Just use some javascript:
<HTML>
<HEAD>
<TITLE>Dynamically add Textbox, Radio, Button in html Form using JavaScript</TITLE>
<SCRIPT language="javascript">
idx = 0;
function add() {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", "textfield");
element.setAttribute("name", "field" . idx);
element.setAttribute("value", "");
idx++;
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<H2>Dynamically add element in form.</H2>
Select the element and hit Add to add it in form.
<BR/>
<INPUT type="button" value="Add" onclick="add()"/>
<span id="fooBar"> </span>
</FORM>
</BODY>
</HTML>
I took this example from: Add more text fields dynamically in new line (html)
I recently received help on this site towards using querySelector on a form input such as select but as soon as I took <select> out it completely changed what had to be done in the function.
HTML:
<form onsubmit="return checkForm()">
Password: <input type="text" name="pwd">
<input type="submit" value="Submit">
</form>
Javascript:
<script language="Javascript" type="text/javascript">
debugger;
function checkForm() {
var form = document.forms[0];
var selectElement = form.querySelector('');
var selectedValue = selectElement.value;
alert(selectedValue);
</script>
Before, I had ('select') for the querySelector, but now I'm unsure what to put there.
I've tried multiple things as well as querySelectorAll but I can't seem to figure it out.
To be clear I'm trying to pull the name="pwd".
How could I do this?
You can try 'input[name="pwd"]':
function checkForm(){
var form = document.forms[0];
var selectElement = form.querySelector('input[name="pwd"]');
var selectedValue = selectElement.value;
}
take a look a this http://jsfiddle.net/2ZL4G/1/
I know this is old, but I recently faced the same issue and I managed to pick the element by accessing only the attribute like this: document.querySelector('[name="your-selector-name-here"]');
Just in case anyone would ever need this :)
1- you need to close the block of the function with '}', which is missing.
2- the argument of querySelector may not be an empty string '' or ' '... Use '*' for all.
3- those arguments will return the needed value:
querySelector('*')
querySelector('input')
querySelector('input[name="pwd"]')
querySelector('[name="pwd"]')
Note: if the name includes [ or ] itself, add two backslashes in front of it, like:
<input name="array[child]" ...
document.querySelector("[name=array\\[child\\]]");
So ... you need to change some things in your code
<form method="POST" id="form-pass">
Password: <input type="text" name="pwd" id="input-pwd">
<input type="submit" value="Submit">
</form>
<script>
var form = document.querySelector('#form-pass');
var pwd = document.querySelector('#input-pwd');
pwd.focus();
form.onsubmit = checkForm;
function checkForm() {
alert(pwd.value);
}
</script>
Try this way.
I understand this is an old thread. However, for people who stepped upon this like me, you may utilize the following code.
select the input using elements collection
form.elements['pwd']
or using namedItem method under elements collection
form.elements.namedItem('pwd')
These examples seem a bit inefficient. Try this if you want to act upon the value:
<input id="cta" type="email" placeholder="Enter Email...">
<button onclick="return joinMailingList()">Join</button>
<script>
const joinMailingList = () => {
const email = document.querySelector('#cta').value
console.log(email)
}
</script>
You will encounter issue if you use this keyword with fat arrow (=>). If you need to do that, go old school:
<script>
function joinMailingList() {
const email = document.querySelector('#cta').value
console.log(email)
}
</script>
If you are working with password inputs, you should use type="password" so it will display ****** while the user is typing, and it is also more semantic.
querySelector() matched the id in document. You must write id of password in .html
Then pass it to querySelector() with #symbol & .value property.
Example:
let myVal = document.querySelector('#pwd').value
form.elements.name gives better perfomance than querySelector because querySelector have to look for in entire document every time. In case with form.elements.name computer directly gets inputs from form.
I am fairly new to javascript and I am 13. So I am new to events in javascript. I would like help on this code:
<head>
<script>
function myFunction()
{
var x=document.getElementById("fname");
if (x=="Kyle")
{
document.write("Correct!");
}
else
{
document.write("Incorrect!")
}
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" onchange="myFunction()">
</body>
I want it to say correct when I type my name. Please help. Thanks
the line
if (x=="Kyle")
should read
if (x.value=="Kyle")
x represents the element, not the element's value.
I hope this helps. Feel free to ask if you have any other problems.
First create a div tag below your form and give it an id of something like "messageBox"
so:
<div id="messageBox"></div>
then replace
document.write("Correct!");
with
document.getElementById('messageBox').innerHTML = "Correct!";
and the same for incorrect.
All this does is create a div tag so that the javascript has somewhere to output the success/failure message.
You were oh so very close. You get the DOM element (getElementById), but you need to get the actual value of the element. Use x.value == "Kyle"
I'd like to refer to a variable ("special") in field later in the same script. I've gotten the variable to display with alert boxes and document.write, but don't now how to make to apply its value to the value field in
var special=(10000-health);
var health=(100);
<input style="background:#FF7777;" readonly="readonly" type="text" value="special" id="special" />
this just writes "special" to the box, when I would like the value instead.
You have to set the value explicitly:
document.getElementById('special').value = special;
Note: You can only access the element after it was parsed in the DOM. To be sure, you can insert this part of the script after the element in the HTML. Often JavaScript code is added just before the closing body tag or is only executed when the load event fires. For more information, see Where to place JavaScript in a HTML file.
Update: Here is an example:
<body>
<input style="background:#FF7777;" readonly="readonly" type="text" value="special" id="special" />
<script type="text/javascript">
var health = 100;
var special = 10000 - health;
document.getElementById('special').value = special;
</script>
</body>
References: getElementById, DOM
MDC's JavaScript Guide is also worth reading.
document.getElementById('special').value = special;
you have to use some kind of DOM manipulation. One of the more popular libraries is JQuery.
using jQuery you'd write something like
$('#special').val(special);
var input = document.getElementById('special');
input.value = special;
I know that this is an embarassingly easy question, but I can't figure out the problem, and that's why I'm asking the question, so please don't reiterate this point.
Anyway, I'm just working on something here, and when I tested my page to see how things were going, I realized that my calculate() method isn't clearing text input like I want it to.
Here is the markup and the script:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Root Finder</title>
<script>
function calculate(){
var valuea = document.form1.variablea.value;
var valueb = document.form1.variableb.value;
var valuec = document.form1.variablec.value;
document.form1.variablea.value = "";
document.form1.variableb.value = "";
document.form1.variablec.value = "";
}
</script>
</head>
<body>
<form name="form1">
a:<input name="variablea" value="" type="text">
<br/>
b:<input name="variableb" value="" type="text">
<br/>
c:<input name="variablec" value="" type="text">
<br/>
<input name="calculate" value="Calculate!" type="button" onClick="calculate()">
</form>
</body>
</html>
Please tell me if you see anything.
You might want to try using another name. I tried to call the "calculate" function but it keeps on giving me an error saying "calculate" is not a function. But when I call the function "calculateQuad" and change the onClick event to call "calculateQuad" it works.
Not very sure, but if you don't want to move to jQuery here's what you could try:
function calculate() {
var inputa = document.getElementById('inputa');
inputa.value = '';
}
Just test this, having an id "inputa" on one of the input boxes. I only know how to get elements by id, name or tag in raw Js. Of course, you could then extend your code to what you want using one of these methods to get your form elements.
Inside the onclick method is there a reference to the item you clicked. It is named the same as the name you put on the item, "calculate". This results in that "calculate" does not refer to the function, but the input tag.
To resolve this by either typing
onclick = "window.calculate()"
or rename the name of either the input-tag or the function.
change the name of the input button to something else:
<input name="calcul" value="Calculate!" type="button" onClick="calculate()">
and it works. Since the calculate function is residing directly under the global object, I have a weird feeling your name attribute is somehow overwriting it.
Just throwing this out there. I will take a deeper look at why this is happening though.