I am attempting to pass the value of an integer from within a javascript function to a server side python script. I have tried to find a way to pass this value directly from the javascript to python but have not yet been successful, so instead I have tried to create a hidden element which contains the value of my int within my html form with the javascript function. Then using the action 'POST' with the Python Bottle framework I have tried to copy the value to my python script. However, the int is being processed as being of NoneType, rather than an int, and so I cannot use it within the processing script. The part of my JS function which creates the element with the int named instance is as follows
function newItem(){
instance++;
var oldInput = document.getElementById("itemInfo");
var parent = oldInput.parentNode;
var newDiv = document.createElement("div");
var item = document.createElement("INPUT");
var qty = document.createElement("INPUT");
var color = document.createElement("INPUT");
var count = document.createElement("HIDDEN");
item.name = "item" + instance;
qty.name = "qty" + instance;
color.name = "color" + instance;
count.value = instance;
newDiv.appendChild(item);
newDiv.appendChild(qty);
newDiv.appendChild(color);
newDiv.appendChild(count);
The HTML form with the 'POST' method
<form method ="post" class="form" action = "/newguest" method = 'post'>
Name: <input type="text" name="name"/>
<p>Item: <input type="text" name="item"/>
Qty: <input type="text" name="qty"/>
Color: <input type="text" name="color"/></p>
<div class="itemInfo" id="itemInfo"></div>
<input type ="button" value="Add Item" onclick="newItem();"/>
<p>Phone: <input type="text" name="phone"/>
Email: <input type="text" name="email"/>
Artwork: <input type="file" name="file"/>
<p>Quote: <input type="text" name="quote"/></p>
</p>
<p>Notes: <textarea cols="40" rows="10"></textarea>
</p>
<input type="submit" value='Add Order'/>
</form>
And finally the python script on the server side
#bottle.route('/newguest', method = 'POST')
def insert_newguest():
name = bottle.request.forms.get("name")
email = bottle.request.forms.get("email")
item = bottle.request.forms.get("item")
qty = bottle.request.forms.get("qty")
color = bottle.request.forms.get("color")
count = bottle.request.forms.get(count)
itemDict = dict()
qtyDict = dict()
colorDict = dict()
for num in range(1, count):
itemkey = "item" + str(num)
qtyKey = "qyt" + str(num)
colorKey = "color" + str(num)
itemDict[itemKey]= bottle.request.forms.get("item"+str(num))
qtyDict[qtyKey] = bottle.request.forms.get("qty"+str(num))
colorDict[colorKey] = bottle.request.forms.get("color"+str(num))
When attempting to add information with the 'POST' method, I receive the following error:
You are probably getting this message because your hidden field hasn't been created correctly.
Firstly, I can't see you actually adding the newDiv to the DOM in your code above.
Secondly - is the HTML form you have provided hard coded? If so then why are you hardcoding a form and then creating the fields again in javascript? This seems a bit weird.
Thirdly and most importantly, as a hidden field is just an <input>, you need to replace
var count = document.createElement("HIDDEN");
With:
var count = document.createElement("INPUT");
count.setAttribute('type', 'hidden');
count.setAttribute('name', 'count');
count.setAttribute('value', my_count_variable);
See this answer and an example jsFiddle. Now when you submit the form your count field should be populated in the Python script.
As an aside, this kind of request is often handled by AJAX. The idea is the same its just that you don't need to refresh the browser to send your count to the Python server. You can see an example of how to do this without jQuery here.
Related
Im working on a project with MVC and i'd like to know if there's a way to store the id of an input, which is a value received from one of my model items, into one of my JS variables
here's how the id of the input is being adressed
#foreach (var item in Model) {
<input type="hidden" value="#item.id" id="#item.id">
<input type="hidden" value="#item.nome" id="#item.nome">
<input type="hidden" value="#item.preco" id="#item.preco">
}
and here's what i been trying to do in my .JS file
var id = document.getElementById('#item.id').value;
var nome = document.getElementById('#item.nome').value;
var preco = document.getElementById('#item.price').value;
You can use css class to mark elements where you want to store the id
select all elements with that css class using js
read id attribute for each element using loop
store it the way you need, eg. an array
Well, if you try this you see that your values are saved.
let id = document.getElementById('Id').value;
let name = document.getElementById('Name').value;
let price = document.getElementById('Price').value;
console.log(id);
console.log(name);
console.log(price);
but i somehow fail to use them in html. This doesn't work for example.
<script>
document.getElementById('Id').innerHTML = id;
document.getElementById('Name').innerHTML = name;
document.getElementById('Price').innerHTML = price;
</script>
<h1 id="Id"></h1>
<h1 id="Name"></h1>
<h1 id="Price"></h1>
It's maybe because the input is hidden.
Method 1
Well you can just expose that item ID directly to JavaScript
<script>
// this must be in the .html file, using window makes the variable global
// most rendering frameworks don't do conditional/server side rendering on static js files
window.ITEM_DATA = {
itemId: "#item.id"
}
</script>
<input type="hidden" value="#item.id" id="#item.id">
<input type="hidden" value="#item.nome" id="#item.nome">
<input type="hidden" value="#item.preco" id="#item.preco">
Method 2
Alternatively, you can give each input a class and select all of the classes (or all of the inputs with type hidden)
<input type="hidden" value="#item.id" id="#item.id" class="item-data">
<input type="hidden" value="#item.nome" id="#item.nome" class="item-data">
<input type="hidden" value="#item.preco" id="#item.preco" class="item-data">
// this could be in its own file because we aren't relying on the server
// this is client-side js
const [itemId, itemNome, itemPreco] = document.querySelectorAll(".item-data")
// this could also fit a narrow use case
// document.querySelectorAll("input[type='hidden']")
Edit: added clarification to method 2
you can access model directly in razor page like #ModelName.objectname but you should import model like
#model ModelName
example : #Model.id
I'm trying to create a function such that, when the form is submitted the details filled by the user (ie his/her name and email id) is appended to a list/array. And then the list/array is displayed.
For example...
When I fill in the credentials for the first time:
Name - A
Email - something#abc.com
The output on submitting the form should be:
[["A", "something#abc.com"]]
When I fill in the credentials for the second time:
Name - B
Email - someone#xyz.com
The output on submitting the form should be:
[["A", "something#abc.com"], ["B", "someone#xyz.com"]]
But when I tried this, I am not getting the output of the list/array.
Here's what I tried...
const info = [];
function display(){
var nm = document.getElementById("nm").value;
var em = document.getElementById("em").value;
var data = [nm, em];
info.push(data);
var text = document.createElement("h2");
text.innerHTML = info;
}
<body>
<script src="script.js"></script>
<form onsubmit="return(display())">
<input type="text" placeholder="Name" id="nm">
<input type="email" placeholder="Email" id="em">
<input type="submit" value="Submit">
</form>
</body>
The reason it's not displaying the data is for two reasons.
Everytime you submit the form, it refreshes the page. To prevent this you have to prevent the default action of the button submission. Which can be done using the function preventDefault() via an event. Better explained in the code.
You have not appended the created element to anything element, so it is not displaying anywhere on the webpage.
Both can be resolved by checking the code and it's explanation below!
const info = [];
function display(e){ // the `e` parameter is the event passed in.
e.preventDefault(); // We run the function preventDefault to prevent the page from reloading.
var nm = document.getElementById("nm").value;
var em = document.getElementById("em").value;
var data = [nm, em];
info.push(data);
var text = document.createElement("h2");
text.innerHTML = info;
document.body.appendChild(text); // You haven't appended the information to
// anything, here I append the created Element to the Body so it displays, but do note, that this displays
// the full list, you may want to change this to display only the newer data
// or perhaps append to a element that prints out each time a new user is added.
//console.log(info); You can see that the array now updateds in the console.
}
<script src="script.js"></script>
<!-- Pass the event of submitting a form as an argument -->
<form onsubmit="display(event)">
<input type="text" placeholder="Name" id="nm">
<input type="email" placeholder="Email" id="em">
<input type="submit" value="Submit">
</form>
in the Name of God
hello.
I have a page that calls another page [answr.php] and it returns some objects like <input type=number>.
the problem is that I create those objects with a dynamic name. so I do not know the name of those objects. how can I guess them?
here is a simple code as like as my code:
Page 1:
I used a part of this function to separate the data in the object's ID.
this func is not important and just shows how can I separate my data from an object's ID
<script language="javascript">
function checknumber(theid){
.
.
.
var strObjName = theid.id.toString();
var strDateExt = strObjName.substring(5, 13);
var strIndexExt = strObjName.substring(13, 14);
document.getElementById("testOut").innerHTML = "Object's Name >" + theid.id.toString();
document.getElementById("testOut").innerHTML += "</br> the Date >" + strDateExt;
document.getElementById("testOut").innerHTML += "</br> the Index >" + strIndexExt;
}
and this is ans.php that answers over ajax and creates objects dynamicly:
$strShrtDate=sAddDateNoSlash($strDate,1);//this func returns a date string without slashes like 20161213
$strIdNumber="numId".$strShrtDate."0";
$strOut="<input id=$strIdNumber type='number' onchange = 'checknumber($strIdNumber);'>";
echo $strOut;
echo "<input name='btnSaveTmrow' type='button' value='Save' onClick='fnSaveTmrow();'>";
this creates a number object with the name "numId201612130" and a button.
that code creates a HTML tag like this:
<input type="number" is="numId201612130" onchange = 'checknumber(numId201612130);'>
<input name='btnSaveTmrow' type='button' value='Save' onClick='fnSaveTmrow();'>
numId sayes it is a number input and it's data is for date 2016/12/13 and the special code is 0.
Now I want to get the names like that [ numId201612130 , numId201612131 , numId201612140 , numId201612141 ,...] for processing some thing and insert into DataBank. how can I do it?
this is my fnSaveTmrow() function is JS:
function fnSaveTmrow(){
url = "SaveTmrow.php";
var vars = "mID="+i_ID+"&tmrowDate="; // <-- I want to send that data here to send by ajax again after that 'ans.php' code who dynamicly created the number input tag
fnDoAll(); // this is ajax code
}
I want to send the date inserted in the objects IDs and their value Like this:
var strObjName = document.getElementById("numId201612130").toString();
var strDateExt = strObjName.substring(5, 13); // contains 20161213
var strIndexExt = strObjName.substring(13, 14); // contains 0
var value = document.getElementById("numId201612130").value;
but I do not have munId201612130 ID because it created dynamicly and I have to retrive it dynamicly too.
I may have a function to returns me those IDs like munId201612130 or munId201612141 or munId201612152
Use document.querySelectorAll to get a list of every <input type="number"> that has an id.
var inputs = document.querySelectorAll('input[type=number][id]')
Then, call Array#map on this list to convert each element to its id:
function getAllDynamicIds() {
var inputs = document.querySelectorAll('input[type=number][id]')
return [].map.call(inputs, function (e) {
return e.id
})
}
console.log(getAllDynamicIds())
<input type="number" id="numId201612130" onchange = 'checknumber(numId201612130);'>
<input type="number" id="numId201612131" onchange = 'checknumber(numId201612131);'>
<input type="number" id="numId201612140" onchange = 'checknumber(numId201612140);'>
<input name='btnSaveTmrow' type='button' value='Save' onClick='fnSaveTmrow();'>
So what I'd like tot do is have a list of forms that show up based on what the user picked in a page before. Now after entering the information in the first form, I would like to give the option of repeating that information for the additional forms . Ex.:
activity 1
Name 1
Name 2
Email
activity 2
Name 1
Name 2
Email
You can see how it can become redundant and tedious if you sign up for many activities. How would I do this in django if possible or javascript if i need to or even html5.
You could do this with just HTML5 and JavaScript (I have no idea what Django is, but this'll be easier if Django is a server-side language that can access form data).
I would make the action attribute of the <form> element in the first webpage lead to the second webpage so that the second webpage would have the GET parameters of that form data, and then in the JavaScript of the second webpage, use those GET parameters to put in data into the form. Here's an example:
tester1.html:
[...]
<form action = "tester2.html">
<input name = "realname" />
<input name = "screenname" />
<input type = "submit" />
</form>
[...]
tester2.html:
[...]
<script>
var form;
window.onload = function() {
var url = document.location.href;
var keys = url.substring(url.indexOf("?")+1, url.length).split("&");
form = document.getElementsByTagName("form")[0];
for (var i = 0; i < keys.length; i++) form[keys[i].substring(0, keys[i].indexOf("="))].value = decodeURIComponent(keys[i].substring(keys[i].indexOf("=")+1, keys[i].length));
};
</script>
[...]
<form>
<input name = "realname" />
<input name = "screenname" />
<input type = "password" name = "password" />
<input type = "submit" />
</form>
[...]
I have a simple HTML form that asks a user to input their name, SKU, quantity, and comments. This is for a simple inventory request system.
<html>
<body>
<form id="myForm" method="post">
<input type="submit">
<br>Name: <input type="text" name="form[name]">
<br>SKU: <input type="text" name="form[SKU1]">
<br>Quantity: <input type="text" name="form[quantity1]">
<br>Comment: <input type="text" name="form[comment1]">
</form>
Add item
<script>
var num = 2; //The first option to be added is number 2
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
newOption.name = "form[SKU"+num+"]"; // form[varX]
newOption.type = "text";
theForm.appendChild(newOption); //How can I add a newline here?
optionNumber++;
}
</script>
</body>
</html>
Currently I can only get it working where it will add a single form value. I would like to recreate the entire myForm except for the name field with a single click.
Your post is very old, so presumably you've found an answer by now. However, there are some things amiss with your code.
In the JavaScript code you have
var num = 2;
This is the number that is incremented to keep track of how many "line-items" you will have on the form. In the function addOption(), though, instead of incrementing num you have
optionNumber++;
You never use optionNumber anywhere else. Your code works once, when you add the first item, but since you increment the wrong variable, you are effectively always adding option 2.
Oh, and adding the newline: you need to append a <br> element.