Create unique name for <input> in form - javascript

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)

Related

How do I make a form's values change a page's CSS in real-time (without having to refresh the page)?

I am attempting to change the CSS on the page as a user types values into a form using javascript. For example - if they type a color value into said field it turns said button to that color. Or changes size if they provide input in the size field. I have not been able to find any examples relating to this. If you could point me to any resources regarding this that would be awesome!
**This is my first post, please let me know if I am doing anything incorrectly.
this input receives code of colors. ff0 - for example
var btn = document.getElementById('btn');
function changeColor(input) {
btn.style.background="#"+input.value;
}
<form>
<input id="inp" type="text" onInput="changeColor(this);">
<button id="btn">Click</button>
</form>
Funny enough this is something I decided to do a few weeks ago, you just create a blank style in the head section of your html page, add an id and use jquery to set the content of the style upon keyup of what ever you decide to use to set the values, e.g.
<pre contenteditable></pre>
<script>
$(document).ready(function(){
$('pre').keyup(function(){
$('#yourstyletagid').html($(this).html());
});
});
</script>
Something like this?
var button = document.getElementById("button");
var b = button.offsetWidth;
function a(input) {
button.style.width = b + input.value + "px";
}
<form>
<input type="number" onchange="a(this);" min="5">
<button id="button">Hello World</button>
</form>

Converting text to lowercase/uppercase with a pending a radio button

I am writing a Javascript program that takes a users input text, then (pending a radio button check – lowerCase/UpperCase) converts the input text to either lowercase/upperCase and outputs the value back to the form.
Purely trying to learn on my own Javascript. I am moderately new (but savvy) to JS. Pretty solid on HTML, CSS, Java, but BRAND new with interacting with page elements.
I have dug around for two days to try and solve this. I have even checked out a few books at my local library. (Currently reading the text, Microsoft guide to CSS/HTML, and JS). What other books would you recommend in order to under JS more?
Here is the code below. Although I know one can use CSS in order to convert this and I have done this. I'm purely just wanting to figure out Javascript.
<!DOCTYPE html>
<html>
<head>
<title> Case Changer By: Elliot Granet</title>
<style>
function convert(){
var convertedText = document.test.input.value;
if(document.getElementById("lowerCase").checked = true){
var output = convertedText.toLowerCase();
}else {
output = convertedText.toUpperCase();
}
document.getElementById('outputText').value = output;
}
convert();
</head>
The rest -
<body>
<h3>Choose your Conversion method below:</h3>
<form action="getElementById">
<fieldset>
<input id="lowerCase" type="radio" name="case" value="lowerCase">Lower Case<br>
<input id ="upperCase" type="radio" name="case" value="upperCase">Upper Case<br><br>
</fieldset>
<fieldset>
<textarea id="inputText" name="input" form="inputText">Enter text here to be Converted...</textarea>
</fieldset><br>
<fieldset>
<textarea id ="outputText" name="output" form="outputText">Converted text will appear here...</textarea>
</fieldset>
<input type="button" value="Convert">
</form>
</body>
</html>
You need to make few changes to make this function work.
style is an invalid tag to put js code. You need to put it inside <script> tag
If you are writing this function inside header yo may come across error since before DOM is ready it will try to get value of textarea with id inputText.
document.getElementById(idName').value but not is right syntax to get the value of element using id
Attaching convert() with the button. So when you will click on button the function will execute.
5.document.getElementById("lowerCase").checked = true this is wrong.It mean that checkbox will get checked as = will assign the value . Instead you need to compare the value. So use == or ===
if you declare var output inside if loop it wont be available inside else. So you need to declare it outside the if-else loop
Hope this snippet will be useful
HTML
<input type="button" value="Convert" onclick="convert()">
JS
window.load =convert; // convert function will be called after window is ready
function convert(){
var output; //variable declaration outside if-else loop
var convertedText = document.getElementById('inputText').value; //document.getElementById
if(document.getElementById("lowerCase").checked == true){ // == comparision
output = convertedText.toLowerCase();
}
else {
output = convertedText.toUpperCase();
}
document.getElementById('outputText').value = output;
}
EXAMPLE

How to display page title in form field?

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>

Onchange Event in Javascript; How to input diffrent items

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"

JavaScript clear text box input not functioning properly

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.

Categories

Resources