using Javascript HTML Formular - javascript

I have mayn different question first and for all there is this pretty normal for who wants to know your firstname and lastname (its German but I hope this deosent matter)
<form name="formular" action="" onsubmit="">
<p>
<label for="vorname">Vorname:</label>
<input value="" type="text" name="vorname" id="vorname" size="25">
</p>
<p>
<label for="nachname">Nachname:</label>
<input type="text" name="nachname" id="nachname" size="25">
</p>
<p><input type="button" value="Absenden" onclick="doFunction();" /></p>
</form>
Then i want to use a function who gets the Name from the form and then shows all Names who ever fill out that form like a Guestbook. Until now i just made it to call an alert whon says "Hallo" but i dont even know how to use The form input as Variables.
I hope u can help me, pls only use JS and HTML.

You can capture the fields and add them to an array, and then print that array onto the page.
Here's a Fiddle containing my code. The existing add button appends to a ul element above the form and saves the name to a global array. I added clear and load buttons as well, so that you can see how to populate the list from the array.
<ul id="guestList">
</ul>
<form name="formular" action="" onsubmit="">
<p>
<label for="vorname">Vorname:</label>
<input value="" type="text" name="vorname" id="vorname" size="25"/>
</p>
<p>
<label for="nachname">Nachname:</label>
<input type="text" name="nachname" id="nachname" size="25"/>
</p>
<p>
<input type="button" value="Absenden" onclick="storeVals();" />
<input type="button" value="Clear List" onclick="clearList();" />
<input type="button" value="Load List" onclick="loadList();" />
</p>
</form>
And javascript:
var names = []; //global scope
function storeVals() //declare function to store the input
{
//document.getElementById finds the element with the
//corresponding ID. In this case I'm getting the objects
//behind each of the input boxes, and retrieving their value properties
//(the text entered in them). I'm also concatenating them together with
//the plus sign (+) operator, and adding a space between them with the ' '
//I'm storing the result of all that in a variable called name.
var name = document.getElementById('vorname').value + ' ' + document.getElementById('nachname').value;
//I'm accessing the names array I declared above. The elements in the
//array are accessed using an index which counts from 0.
//So to get the first element, I would do names[0].
//In this case I'm using names.length instead of a number, as it will return
//the number of elements currently in the array. When there are zero, it will return 0.
//When there is one, it will return 1, which happens to be the index for the second element.
//The means I'm always assigning the name to the element after the last existing one.
names[names.length] = name;
alert(names); //just to help see what's going on. Remove this when you don't need it anymore.
//Uses document.getElementById again, this time to get the object behind my ul list.
//And calls my appendToList function below, passing it my name variable and a
//reference to the list object.
appendToList(name, document.getElementById('guestList'));
}
function appendToList(name,ulist){
//this constructs a <li> object and stores it in a variable.
var li = document.createElement("li");
//this adds the text of the name inside the <li>
//so if name is equal to "john smith", I've built:
//<li>john smith</li>
li.appendChild(document.createTextNode(name));
//adds the li as a child of my existing list object.
//so:
// <ul id="guestList"><li>john smith</li></ul>
ulist.appendChild(li);
}
function clearList(){
//gets my ul list object with the id "guestList"
//sets its innerHTML (all of its contents) to an empty string
//so regardless of what's inside, it becomes <ul id="guestList"></ul>
document.getElementById('guestList').innerHTML = '';
}
function loadList(){
//got my ul list object by id again.
var list = document.getElementById('guestList');
//for loop - essentially this means start the variable i at 0
//keep looping while i < names.length, and increment i by 1
//each time we iterate through the loop.
for(i=0;i < names.length; i++){
//call the appendToList function above, and pass it names[i] and my list object
//so essentially, loop over every name in the array and call that function with
//it to add the name to the list.
appendToList(names[i],list);
}
}
Here are some specific reference materials for some of things I've done.
Arrays
ul DOM object
the document object
document.getElementById
But you need to be aware, if you're just using client-side javascript, this data is not going to survive a page refresh, and it will not be available if the page is accessed from another browser.

What you want to do is implement the JavaScript function to get the name. Here's an example:
function doFunction()
{
var name = document.getElementById('vorname').value;
alert("hallo " + name);
}
<form name="formular" action="" onsubmit="">
<p>
<label for="vorname">Vorname:</label>
<input value="" type="text" name="vorname" id="vorname" size="25">
</p>
<p>
<label for="nachname">Nachname:</label>
<input type="text" name="nachname" id="nachname" size="25">
</p>
<p><input type="button" value="Absenden" onclick="doFunction();" /></p>
</form>
Now you can do something with the name. Maybe you can store it as a global variable like so:
var name = "Guest";
function doFunction()
{
name = document.getElementById('vorname').value;
//do something here
}
And then you change the content of the website on the same page. But you must not navigate from that page; otherwise you may want to use local storage or a server-sided scripting language.

Related

Why isn't a single form element is not returning value in the controller?

In my Form 3 fields including a hidden.and the rest of the values are perfectly returns in controller ,But the value in the hidden field is not getting .
the value in the hidden field is passing from an anchor tag using java script.
The value for the hidden field is passing from here
<a href="#" onclick="func(#c.vid)" data-toggle="modal" data-target="#myModal3" class="modalLink">
Javascript code to pass the value is
function func(vd){
document.getElementsByClassName("hiddenid").value = vd;
}
Form is look like
<form action="/Home/AddToCart" method="post">
<input type="hidden" id="vid" name="vid" class="hiddenid" />
<div class="styled-input agile-styled-input-top">
<input type="text" placeholder="Name" name="name" id="name"required>
</div>
<div class="styled-input">
<input type="text" placeholder="Star Name" onclick="showsss()" name="star" id="star" required>
</div>
<input type="submit" value="Add To Cart">
</form>
Controller
[HttpPost]
public ActionResult AddToCart(cart data)
{
userService.AddToCart(data);
ViewBag.p = userService;
return RedirectToAction("Temple");
}
The value is passing to the hidden field perfectly.i checked using an alert box.am attaching a screen shot of what am getting in the controller.
getElementsByClassName return an array.
function func(vd){
document.getElementsByClassName("hiddenid")[0].value = vd;
}
getElementsByClassName returns an array. Access single element using array index.
document.getElementsByClassName("hiddenid")[0].value = vd;
Instead of className you can use id as it is present on your hidden field i:e vid.
document.getElementsById("vid").value = vd;
or you can use document.querySelector which will retrieve first match element.
document.querySelector('.hiddenid').value = vd;
or
document.querySelector('#vid').value = vd;
Since you are using byclass its return an array. try this
document.getElementsByClassName("hiddenid")[0].value = vd;
But if you have a multiple products then do you have a add to cart button better to used id like vid-unique_number

Javascript Dynamic Form Field

I am having difficulty with a javascript that I need some help with. I have a form which sends to a php the exact amount of inputs to be filled, now I want to create a preview using jQuery/javascript but how can I catch all the fields dynamically.
Here is a portion of my form for reference:
<td>
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-pencil"></i></span>
<input class="form-control" id="task" type="text" name="task" placeholder="Task Title">
</div>
</td>
<td>
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-pencil"></i>
</span>
<input class="form-control" id="description" type="text" name="description" placeholder="Task Description">
</div>
</td>
So, I added in PHP the name field + the number, this way I can get different names ie: task1, task2,...etc.
Now what I need to do is get the values using jQuery/javascript.
My thoughts so far is to declare the var (variable) inside a for() (loop)
var task = $('input[name=task]').val();
How can I get all values task1, task2. No one knows how many task fields the user will submit so I need to get the number of fields
Any help direction so I can figure this out
First of all, you don't need to give your input fields names like task1, task2, etc to distinguish among them on the server-side i.e on the PHP. You just need to give all of them a name attribute value like tasks[] And notice the brackets [] so you may have something like the following:
<input class="form-control" id="tasks[]" type="text" name="tasks[]" placeholder="Task Title">
...
<input class="form-control" id="tasks[]" type="text" name="tasks[]" placeholder="Task Title">
Like that automatically values in those fields will be posted as an array to the PHP and it is going to be received like the following in PHP script:
$tasks = $_POST['tasks'];
foreach ($tasks as $task){
echo $task;
}
Second By this way you will easily able to collect your inputs data using Javascript inorder to generate the preview by using getElementsByName method as follows:
function preview(){
output = "";
tasks = document.getElementsByName('tasks[]');
for (i=0; i < tasks.length; i++){
output += "<b>Title</b>: "+tasks[i].value+"<hr />";
}
panel = document.getElementById('panel');
panel.innerHTML = output;
}
Of course you can expand this solution to any number of fields in your form such as descriptions[].
A javascript DEMO: http://jsbin.com/kiyisi/1/
Using the Attribute Starts With Selector [name^="value"] and jQuery.each()
var tasks = $('input[name^=task]').val();
$.each(tasks,function(index, value){
//do something with the value
alert($(this).val());
});
edit
var tasks = $('input[name^=task]');
$.each(tasks,function(index, value){
//do something with the value
$('#Preview').append($(this).val());
});
Q: now I want to create a preview using jquery/javascript but how can I catch all the fields dinamically:
If you give them a class, you can get all fields with each:
$(".className").each(function() {
do something
Next, "catch" all fields... I'm assuming you may want the values of these fields too? Check this example for details, here is a snippet which loads the key:value pairs (form field name : value of field) into a map:
var map = {};
$(".activeInput").each(function() {
map[$(this).attr("name")] = $(this).val();
});
Print all values inside div (Here, I'm assuming you're talking about children values of div):
<div>
<span>Hi</span>
<span>Hello</span>
<span>Hi again</span>
</div>
$("div").children().each(function () {
console.log($(this).text());
});
OR
$("div span").each(function () {
console.log($(this).text());
});

Is there a way to capture the value of a variable in each iteration of a for loop in javascript?

I am a student learning javascript, it is only week 3 so I am not familiar with any advanced topics or code. This is for a graded assignment so I am not looking for answers but any help or suggestions to accomplish this would be great. I have been stuck for several hours and I really don't even know what direction to head in.
What I need to do is use a for loop to grab the value of upto 3 different id tags that a user can enter into an html page. it has to be done in a for loop and use a counter to change the name of the id sequentially.
I am able to do this, however every time the loop runs it grabs the data and of course sets the variable to the latest iteration of the loop.
Is there a way to capture the returned value in each loop and store it for use later after the loop has run? I should be able to generate 3 separate values and then display them together.
Edit: this is the HTML:
<!DOCTYPE html>
<body>
<h1>Assignment 2</h1>
<p>
Enter First Name:
<input id="firstname" type="text">
<span id="firstname_error">*</span>
</p>
<p>
Enter Last Name:
<input id="lastname" type="text">
<span id="lastname_error">*</span>
</p>
<p>
How Many Pets do you have? (0-3):
<input id="numpets" maxlength="1" size="1" type="text">
<span id="numpets_error">*</span>
</p>
<p>
List your Pet's names:
<input id="pet1" type="text">
<input id="pet2" type="text">
<input id="pet3" type="text">
</p>
<p>
<input onclick="processInfo()" type="button" value="Submit Information">
</p>
<p id="message">*</p>
</body>
</html>
You can use a separate variable to cumulatively store the value from each iteration. Make sure to define this variable before the loop and to add the data to the variable at each iteration, instead of overwriting it.
For example with a string variable:
var str = '';
for (i=0; i < 3; i++) {
str += i+' '; // Note the usage of the += operator to append the value
}
//
console.log(str);
Or with an array variable:
var arr = [];
for (i=0; i < 3; i++) {
for (i=0; i < 3; i++) {
arr.push(i);
}
//
console.log(arr.toString());
Note that for the sake of the example we're just storing the values of the loop's counter, i.

get name of hidden form

What i want to do is get the name of the hidden form which in this case is named:6ca3787zz7n149b2d286qs777dd8357b, the problem is, that form name always changes, the only thing that is the same is its value, which is 1, well 99% of the time, the only thing that is 100% the same that i guess could be somehow used to retrieve the form name is:L2ZvcnVtcy8 which is just above it. I am also attempting to do this via running javascript manually on the browser (chrome), so having that in mind where the javascript code is run through the url bar like this javascript:codegoeshere, how can i get the form name, -->(6ca3787zz7n149b2d286qs777dd8357b)?
<form action="index.php?feature=xxxxxx" method="post" name="login">
<input type="submit" name="submit" class="button" value="Logout" />
<input type="hidden" name="option" value="username" />
<input type="hidden" name="task" value="logout" />
<input type="hidden" name="return" value="L2ZvcnVtcy8=" />
<input type="hidden" name="6ca3787zz7n149b2d286qs777dd8357b" value="1" /> </form>
</li>
Check all the solutions below in this fiddle.
Some possibilities:
Assuming there is only one element with the name login and that element is the <form>, you can use:
document.getElementsByName('login')[0].getElementsByTagName('input')[4].name
If the return <input> has a fixed name attribute, then this should work (the additional .nextSibling is because there is a text node between them):
document.getElementsByName('return')[0].nextSibling.nextSibling.name
If any other of of those <input>s has a fixed name, you can use (in the example I take the <input> with name=task):
document.getElementsByName('task')[0].parentNode.getElementsByTagName('input')[4].name);
If all you really have is that fixed value, you'll have to use a for loop through all the <input>s:
var lastResortName = (function () { for(var i=0, ipts = document.getElementsByTagName('input'), n = ipts.length; i < n; i++) { if (ipts[i].value === "L2ZvcnVtcy8=") return ipts[i+1].name; } })();
Note: If there are duplicated values for the mentioned name attributes, test with the index ([0], [1], [2] and so on) until you find the expected elements.
That's really easy if you use JQuery:
$('input[type="hidden"]:eq(3)').attr('name')
Here your code running:
http://jsfiddle.net/7CHYa/

How do I replace part of the value of attributes for a set of elements in jQuery?

I am trying to replace a series of 'for' attributes of labels based on their current contents.
The application is using AJAX to add an item to an invoice without refreshing the page. Upon receiving notification of a successful item add, my script should replace all the labels in the form whose 'for' attribute ends with '-new' with the same attribute minus the '-new' and adding ('-' + itemValue), where itemValue is the item Id of the invoice item that was added.
I know how to select all the labels I want to change at once:
jQuery('label[for$=new]')
I know how to get their 'for' attribute:
jQuery('label[for$=new]').attr('for')
I tried the JavaScript replace method:
jQuery('label[for$=new]').attr('for').replace(/-new/,itemValue)
But that appears to select each label's 'for' attribute, replace the text, and pass the replaced text back (to nothing), since I don't know how to identify the labels that have the 'for' attribute I want to replace.
Here's some sample HTML:
<form id="InvoiceItemsForm-1" action="<?=$_SERVER['PHP_SELF'];?>" method="post" name="InvoiceItemsForm-1" onsubmit="return false">
<div id="InvoiceItem-new-1" class="InvoiceItem">
<label for="InvoiceItemNumber-new">New Invoice Item Number: </label>
<input id="InvoiceItemNumber-new" class="InvoiceItemNumber" type="text" value="" name="InvoiceItemNumber-new">
<label for="InvoiceItemDescription-new">Item Description: </label>
<input id="InvoiceItemDescription-new" class="InvoiceItemDescription" type="text" value="" name="InvoiceItemDescription-new">
<label for="InvoiceItemAmount-new">Item Amount: </label>
<input id="InvoiceItemAmount-new" class="InvoiceItemAmount" type="text" value="" name="InvoiceItemAmount-new">
<input id="addInvoiceItem-1" width="25" type="image" height="25" src="/payapp/images/greenplus.th.png" alt="Add New Invoice Item" onclick="addInvoiceItemButtonPushed(this)" value="invoiceItem">
</div>
<button id="CloseInvoice-1" onclick="closeInvoice(this)" type="button">Close Invoice</button>
</form>
Once I get this to work, I'm going to replace all the ids for all the inputs. Same problem. I imagine the solution looks something like this:
jQuery('input[id$=new]').attr('id').replace(/-new/,itemValue)
I just cannot figure out the syntax for this at all.
No need to use .each() ... the .attr() method accepts a function as the second parameter that returns the new value to be used as replacement
jQuery('label[for$=new]').attr('for', function(index, currentValue){
return currentValue.replace(/-new/,'-' + itemValue);
});
If I may, why not just put the input tag inside the label tag? That way, you won't need a for attribute inside the label tag.
Next, a better way to accomplish what you're trying to do would be to use the invoice ID number as the ID for the surrounding div, and add a 'new` class for "new" invoice entries.
So your form would look something like this:
<form id="InvoiceItemsForm-1" action="<?=$_SERVER['PHP_SELF']" method="post" name="InvoiceItemsForm-1" onsubmit="return false">
<div class="InvoiceItem new">
<label>New Invoice Item Number: <input class="InvoiceItemNumber" type="text" value="" name="InvoiceItemNumber"></label>
<label>Item Description: <input class="InvoiceItemDescription" type="text" value="" name="InvoiceItemDescription-new"></label>
<label for="InvoiceItemAmount-new">Item Amount: <input class="InvoiceItemAmount" type="text" value="" name="InvoiceItemAmount-new"></label>
<input id="addInvoiceItem-1" width="25" type="image" height="25" src="/payapp/images/greenplus.th.png" alt="Add New Invoice Item" onclick="addInvoiceItemButtonPushed(this)" value="invoiceItem">
</div>
<button id="CloseInvoice-1" onclick="closeInvoice(this)" type="button">Close Invoice</button>
</form>
You'll still have all the targetability you need to get the new invoice item field data, but now, you only have two things to do to convert from a "new" invoice row to an "existing" invoice item row: add an id attribute to the div and remove the new class, both of which jQuery will let you do quite easily.
Not sure I get the question, but something like:
var oldFor = $('label[for$=new]').attr('for');
var newFor = oldfor.replace(/-new/,itemValue);
$('label[for$=new]').attr('for', newFor);
.attr( attributeName, value )
attributeName = The name of the attribute to set.
value = A value to set for the attribute.
When selecting multiple elements, you will need to iterate:
$('label[for$=new]').each(function(index) {
$(this).attr('for', $(this).attr('for').replace(/-new/, '-' + itemValue));
});

Categories