Read data on server side from dynamically generated inputs - javascript

In my case i have
<input type="text"/>
And button, that on click add additinal inputs to page.
To add inputs i use this JavaScript:
var myBtn = document.getElementById('myBtn');
var qtyOfAdds = 0;
myBtn.addEventListener('click', function (event)
{
addField();
});
var form = document.getElementById('form1');
function addField()
{
var input = document.createElement('input');
input.id = qtyOfAdds;
input.name = qtyOfAdds;
input.type = "Text";
form.insertBefore(input, myBtn);
qtyOfAdds++;
document.getElementById('AddedFieldsCount').value = qtyOfAdds;
}
On server side i read post data, to get all field data input.
Using this C# code:
var context = HttpContext.Current;
List<string> fieldsList = new List<string>();
string hiddenFieldData = context.Request["AddedFieldsCount"];
int addedFieldsCount = 0;
Int32.TryParse(hiddenFieldData, out addedFieldsCount);
for (int i = 0; i < addedFieldsCount; i++)
{
fieldsList.Add(context.Request[i.ToString()]);
}
So, and html on .aspx page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link href="StyleSheet.css" rel="stylesheet" />
<script src="JavaScript.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<input type="text"/>
<button type="button" id="myBtn">ADD</button>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
<br />
<input id="AddedFieldsCount" name="AddedFieldsCount" type="hidden" />
</form>
<script src="JavaScript.js"></script>
</body>
</html>
Tell me please, can you advice more better way?

In my case using jQuery and Asp.Net MVC I'd approach it as follows (note, this is untested so there may be a few mistakes), I'm also unsure as to what the text boxes will be used for and what text they'll support.
Client side
$(document).ready(function(){
$('#myBtn').click(function(){
var $this = $(this),
$form = $('#form1'),
$inputs = $('input.tb');
$newInput = $('<input/>', { type: 'text', name: 'tb' + $inputs.length, class: 'tb' }),
$inputs.last().after($newInput);
}
});
Server side
HttpContext context = HttpContext.Current;
// Retrieve all keys
List<string> keys = from key in context.Request.Form.AllKeys
where key.StartsWith("tb")
select key;
Without knowing your exact requirements and end use there are as always many ways to achieve what you want and the way you've currently handled it is fine but the way above could also be used.

Related

Save value in reload page javascript

I want to save data in the input when the page reloading and I don't
know why my code doesn't work. This is my html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<label>nom:</label> <input type="text" value=""/></br>
<label>prenom:</label><input type="text" value=""/>
<script type="text/javascript">
window.onbeforeunload = function(){
localStorage.setItem(nom, document.getElementsByTagName('input')[0].value);
localStorage.setItem(prenom, document.getElementsByTagName('input')[1].value);
}
document.addEventListener("DOMContentLoaded",function(){
var nom = localStorage.getItem(nom);
var prnom = localStorage.getItem(prenom);
if(nom!==null&&prenom!==null) {
document.getElementsByTagName('input')[0].value = nom;
document.getElementsByTagName('input')[1].value = prenom;
}
});
</script>
</body>
</html>
Make sure to use quotes for the variable name:
localStorage.setItem('nom', document.getElementsByTagName('input')[0].value);
Or you can use this which is simpler:
localStorage.nom = document.getElementsByTagName('input')[0].value;
Your code was setting the localStorage values when the page was loaded which means it set it to be no text so the code won't save.
Use the below code:
window.onbeforeunload = function() {
var nom = localStorage.nom;
var prnom = localStorage.prenom;
if (nom !== null && prenom !== null) {
document.getElementsByTagName('input')[0].value = nom;
document.getElementsByTagName('input')[1].value = prenom;
}
};
<label>nom:</label> <input type="text" onchange="localStorage.nom = document.getElementsByTagName('input')[0].value" /></br>
<label>prenom:</label><input type="text" onchange=" localStorage.prenom = document.getElementsByTagName('input')[1].value" />
IMPORTANT: use the code on your computer because localStorage doesn't work on stack overflow snippets

Javascript reusing forms

I want to get the names of the n (say n==5) children of a given person, by using the same form each time.
I can't seem to be able to produce javascript code that will accomplish this simple task.
for (var i = 0; i<5; i++){
<form id="child_form">
Child name:
<input type="text" id="child_name" name="child_nm" size="40">
<br>
<input type="button" value="Submit" onclick="myFunction()">
</form>
}
<script language="javascript">
<script>
function myFunction() {
add_child_to_array();
}
var array_of_children = [];
function add_child_to_array(){
var input_string = document.getElementById("child_name").value;
alert(input_string);
array_of_inputs.push(input_string);
}
</script>
But clearly one can't do that.
I've tried taking the data out of the form and then resetting the form. It turns out you can do either but not both.
I haven't found a website that deals with this problem.
Help would be greatly appreciated.
You have multiple options to accomplish this task. I would prefer to use the HTML5 template element functionality.
You could alternatively create and append the DOM Elements by yourself.
This is certainly a bit of a mess. Assuming I understand correctly, you need to create the form in javascript, so it can be dynamically added as many times as you want. I have written a generalised way of doing this. You may want to change / simplify it. I have made sure all elements are dynamic so that can be accessed properly. Also, I have used JQuery which I highly suggest.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
$(function(){
var allForms = document.getElementById("all-forms");
for(var i = 0;i<5;i++){
form = document.createElement("div");
form.id = "form-" + i.toString();
if(i!=0){
form.style.display = "none";
}
input = document.createElement("input");
input.id = "child_name"+i;
input.placeholder = "input"+i;
submit = document.createElement("button");
submit.innerHTML = "go"+i;
submit.id = "submit-"+i;
submit.className = "buttons";
form.appendChild(input);
form.appendChild(submit);
allForms.appendChild(form);
}
$(".buttons").click(function(){
var id = $(this).attr("id").substring(7);
$("#form-"+id).hide();
var nextID = (parseInt(id)+1).toString();
$("#form-"+nextID).show();
});
});
</script>
</head>
<body>
<div id = "all-forms"></div>
</body>
</html>

How to detected Control is clicked OnClientClick in ASP.NET C#?

I have an Image Button with OnClientClick event to load Ajax.
I want to detect that my Image Button is clicked. I'll try so hard but no luck.
This is my code:
ImageButton imgbtn = new ImageButton();
imgbtn.Height = 25;
imgbtn.CssClass = "light";
imgbtn.ID = "led" + i;
imgbtn.OnClientClick = "Turnon('" + table.Rows[i]["Url"].ToString() + "');";
//If i can detected that my imgbtn is clicked
//I will do something
Sorry if my question is unclear, but i'm try best to show you my idea.
Thanks!
Here's the solution
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function Turnon(url)
{
alert(url);
}
</script>
</head>
<body>
<form id="form1" runat="server">
</form>
</body>
</html>
You need to add control to your form or any place holder on aspx page.
Code behind:
ImageButton imgbtn = new ImageButton();
imgbtn.Height = 25;
imgbtn.CssClass = "light";
imgbtn.ID = "led";
imgbtn.OnClientClick = "Turnon('" + "www.google.com" + "');";
form1.Controls.Add(imgbtn); //

How to create an Object with all attributes of a html tag?

Here is my test code, extracted from a form I'm building:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script>
function ini(){
console.log("Element dump:");
var elem = document.querySelector('form[name="form"] input[name="dataNasc"]');
for(var i in elem){
console.log(i+":"+elem[i]);
}
console.log("Form element dump:");
var Form = document.forms["form"];
var input = Form.dataNasc;
for(var i in input){
console.log(i+":"+input[i]);
}
}
</script>
<title>Untitled Document</title>
</head>
<body onload="ini();">
<form name="form" action="" method="post">
<label for="dataNasc">Data Nasc.</label>
<input type="text" name="dataNasc" maxlength="10" required="required" tipo="data" value="{dataNasc}" />
</form>
</body>
</html>
In both cases that I pick the input tag (ini function), the attribute "tipo" is not listed. The property returns "undefined". It seams an object is created using the information in the tag, not a conversion "tag to object". Using outerHTML, I can do it manually (hope this property is cross-browser), but I'm wondering if there is a way using JavaScript resources... How can I do it?
Once you have a reference to the element, you can iterate over its attributes NamedNodeMap to discover all of its attributes. So for example and assuming there will only be one matching element matching your selector...
var elt=document.querySelector('form[name="form"] input[name="dataNasc"]'),
attrs=elt ? elt.attributes : [];
for(var i=0; i<attrs.length; i++) {
console.log('attr "'+attrs[i].name+'" contains "'+attrs[i].value+'"');
}
try this:
function ini(){
console.log("Element dump:");
var elem = document.querySelector('form[name="form"] input[name="dataNasc"]');
for(var i in elem){
console.log(i+":"+elem[i]);
}
console.log("Form element dump:");
var Form = document.forms["form"];
var input = Form.dataNasc;
var myObj = {};
for(var i in input){
myObj[i] = input[i];
}
}

Javascript/JSON error: not well formed

I am testing putting a text editor on my page and storing it as part of a JSON object.
HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://tinymce.cachefly.net/4.0/tinymce.min.js" type="text/javascript"> </script>
<script type="text/javascript">
tinymce.init({
selector: "textarea"
});
</script>
<link rel="stylesheet" href="/jquery.mobile-1.3.2.min.css"/>
<script src="/jquery-1.9.1.min.js"></script>
<script src="/jquery.mobile-1.3.2.min.js"></script>
</head>
<body>
<form method="post" action="formSubmit.js">
<textarea name ="editor"></textarea>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
JS
$(document).ready(function () {
var text = $("editor").val();
var name = "project name";
var id = 5;
var item = new item(name, text, id);
var itemArray = localStorage.items;
if (itemArray == undefined) {
itemArray = [];
} else {
itemArray = JSON.parse(itemArray);
}
itemArray.push(item);
localStorage.items = JSON.stringify(itemArray);
});
I want to be able to store item in a JSON object. When I run this I receive a "not-well formed" error at line 1 of the Javascript. It's a very simple program I'm running and can't seem to pinpoint what is causing the error. Is the JSON done incorrectly or are scripts in my HTML header causing issues?
$("editor") is looking for an html tag called 'editor'. you probably want to attach an id attribute to your and do $('#editor')

Categories