Passing item value from model to JS - MVC C# - javascript

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

Related

Passing Variables Between Javascript and Python

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.

javascript: use getElementByID to populate multiple divs

is there a way to write the same thing clientside using javascript to multiple divs or multiple spots on a page?
I have a php script outputting rows from a database. To edit the contents, I would like to insert a checkbox before each row as with the iphone edit contacts and to do it quickly, I'm trying to use javascript to populate a div with a checkbox before each row using getElemenByID.
One problem is you cannot have more than one div of the same name on a page so I can't write once and have it populate multiple divs of the same name. If I give divs different names than I have to write multiple times which is not appealing especially as the number of rows may vary.
As a related question would checkboxes inserted using javascript even work?
Here is non working code:
js
function edit() }
var box = '<input type="checkbox name=num[]>';
var target = "checkbox";
document.getElementById(target).innerHTML = box;
return;
}//end function
html (generated by PHP from dbase)
<form action="edit.php" method="post">
<a href="javascript:void" onclick="edit()";>edit</a>
<div id="checkbox"></div>Row1 contents<br>
<div id="checkbox"></div>Row2 contents<br>
<form type = "submit" value="Edit">
</form>
Does anyone know a way to do this ie make boxes appear that can then be selected for submission?
Many thanks for any suggestions.
Should be generated using PHP instead, but...
HTML
I'm guessing that you want to use a span element (not a div) for your checkbox placeholder, otherwise you'd have a checkbox on one line, and then "Row1 contents" below the checkbox, versus having the checkbox next to the text.
[X]
Row 1 Contents
versus (span)
[X] Row 1 Contents
<form action="edit.php" method="post" name="frmRows" id="frmRows">
edit
<span class="checkbox"></span>Row1 contents<br>
<span class="checkbox"></span>Row2 contents<br>
<input type = "submit" value="Edit">
</form>
JavaScript
It's not recommended to use .innerHTML in JavaScript unless absolutely necessary (not supported in all browsers, and there are better ways to accomplish the same task.)
function edit() {
var newCb;
var i;
var checkboxList = document.getElementsByClassName( 'checkbox' );
for ( i = 0; i < checkboxList.length; i++ ) {
newCb = document.createElement( 'input' ); // Create a new input element
newCb.setAttribute( 'type', 'checkbox' ); // Set attributes for new element
newCb.setAttribute( 'value', 'SomeValueHere' );
newCb.setAttribute( 'name', 'checkboxName' );
newCb.setAttribute( 'id', 'checkbox-' + i );
checkboxList[i].appendChild( newCB ); // Add checkbox to span.checkbox
}
}
The ID attribute must be unique on each page. You could use the class attribute like this:
<div class="checkbox"></div>Row1 contents<br>
<div class="checkbox"></div>Row2 contents<br>
and then you can use
var check = getElementsByClassName('checkbox');
for (var i=0; i< check.length; i++) {
check[i].innerHTML = box;
}
But... this will not work in IE < 9. If you are using a framework like jQuery they already implemented a workaround for this but with pure JS you have to implement this yourself.
jQuery example
HTML
<div class="checkbox"></div>Row1 contents<br>
<div class="checkbox"></div>Row2 contents<br>
JS
var box = '<input type="checkbox" name="num[]" />';
$(".checkbox").html(box);
The HTML
The first thing to do is to update the generated HTML. In HTML element id attributes should be unique just like field names inside a form. To classify multiple elements as similar you should use the class attribute.
Here is an example of how you could structure the HTML.
<form action="edit.php" method="post">
edit
<div id="row1Identifier" class="editCheckbox"></div>Row1 contents</br>
<div id="row2Identifier" class="editCheckbox"><?div>Row2 contents</br>
<input type="submit" value="Submit">
</form>
The javascript
Using document.getElementsByClassName will return a list of elements with the matching class.
​function edit () {
// set up the variables used in this function
var checkboxDivs = document.getElementsByClassName('editCheckbox'),
i,
loopDiv;
// make the change to each div
for (i = 0; i < checkboxDivs.length; i += 1) {
loopDiv = checkboxDivs[i];
loopDiv.innerHTML = '<input type="checkbox" name="' + loopDiv.id + '">';
}
}​
Even if you could do it with a single line (using jQuery, for exemplo), you would actually be running a loop through all the divs (that's the only way to change something in various elements: change it in each one).
So you can do this with pure JavaScript using a loop to run the modifications in all the divs, getting them by id (the faster way):
for(var i = 0; i < numberOfDivs; i++){
document.getElementById("myElement" + i).innerHTML = box; //concatenating i to a base id
}
You could also use another slower techniques to get elements by tag name or class, or even use a lib such as jQuery.
If you use jquery:
function edit() {
// box = '<input type="checkbox name=num[]>';
var target = "checkbox";
$(".cb").html(box);
return;
}//end function
<form action="edit.php" method="post">
edit
<div class="cb" id="checkbox">aa</div>Row1 contents<br>
<div class="cb" id="checkbox">bb</div>Row2 contents<br>
</form>

Pass variable to HTML form Javascript

Please excuse my inexperience as I am not a programmer just someone who dabbles at trying to make something work. I'm not sure of the correct terminology and complicated explanations will go straight over my head!
In essence I am trying to get part of the URL of a web page passed to a simple Form that is linked to a shopping cart. i.e. how do I get the filename into the form where I have xxxxxxx. Is it possible in Javascript?
<script type="text/javascript">
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
document.write (filename);
</script>
<form action="http://www.mywebspace.com/cf/add.cfm" method="post">
<input type="hidden" name="userid" value="12345678">
<input type="hidden" name="product" value="xxxxxxx">
<input type="hidden" name="price" value="5.00">
<input type="Submit" value="Buy now!">
</form>
I've provided a snippet code that will work with your current HTML structure. Though I do suggest you give the product field an id to prevent the necessity to loop and search elements:
var url = window.location.pathname,
filename = url.substring(url.lastIndexOf('/')+1);
fields = document.getElementsByTagName('input');
for(var i = 0; i < fields.length; i++){
if(fields[i].name == 'product') {
fields[i].value = filename;
break;
}
}
If the form only exists once on a given page, this is an easy solution:
Change it to be:
<input type="hidden" id="productField" name="product" value="xxxxxxx">
In your javascript,
document.getElementById('productField').value = filename;
Yes this is possible.
Instead of doing document.write you need to update the form. Assuming your filename value is currently correct:
//js
document.getElementById( "name-of-file").value = filename;
<!- html -->
...
...

Pass some checkbox values from one JSP to another

I've been having problems passing parameters from one .jsp to another.
I have two .jsp (1 and 2). In 1 I get some data from a database and show the user a bunch of checkboxes (depending on the data I got before). The user has to check one or more of the checkboxes, the selected will be deleted in my database in 2. (It´s something like "Select the numbers you want to delete").
I don't know how to pass the selected checkboxes and the value from 1 to 2.
I tried with javascript/jQuery, trying to know if a checkbox is checked and its value, add the value to a hidden field and use the request in 2 to get it.
1.jsp
<%
HttpSession sesion = request.getSession();
Company company = (Company) sesion.getAttribute("company");
List<Phone> phones = company.getTelefonos();
%>
<form id="formulario" method="POST" action="desMul_Final.jsp">
<fieldset>
<legend>Numbers</legend>
<%
Iterator<Phone> it1 = phones.iterator();
while(it1.hasNext()){
Phone t = it1.next();
String number = t.getNumero();
%>
<p>
<input name=check id="t_<%=number%>" type=checkbox value="<%=number%>" /> <%=number%>.
</p>
<%
}
%>
</fieldset>
<p class="buttons">
<button type=submit onclick="javascript: pick();">Continue</button>
</p>
</form>
Javascript/jQuery
function pick(){
var counter = 0;
$("#formulario fieldset p").each(function(index){
var field;
$(this).children("input").each(function() {
if($this.is(':checked')){
field = $(this).val();
}
});
index = index + 1;
texto = "<input type=hidden name=phone_"+index+" value="+field+" />";
$("#formulario").append(texto);
counter = index;
});
cant = "<input type=hidden name=amount id=amount value="+counter+" />";
$("#formulario").append(cant);
}
2.jsp (here I only try to know if I have the info)
<%
int amount = Integer.valueOf(request.getParameter("amount"));
System.out.println(amount);
for(int i = 1; i <= amount; i++){
String s = request.getParameter("phone_"+i);
System.out.println(s);
}
%>
When I try to access to request.getParameter("amount") I get an java.lang.NumberFormatException: null so I think my Javascript/jQuery is wrong.
How can I solve this?.
Are you familiar with debugging web application in a client-side way?
Can you please insert console.log("$("#formulario")) and then a breakpoint after $("#formulario").append(cant);, to see how the form's content changed, and if the hidden input was added ?
use int[] amount= Integer.ValueOf(request.getParameterValues("amount")); instead of request.getParameter("amount");
Well, I finally found the solution and I didn't need any Javascript. Searching in the API I found a method of the request called getParameterNames() that returns an Enumeration of String objects containing the names of the parameters contained in this request.
And I understood that when you submit the form, the checkbox value will be sent if the control is checked. Otherwise, nothing will be sent. So with this information and the method, I changed the way the checkboxes were constructed and use the enumeration to get the values.
BEFORE
<input name=check id="t_<%=number%>" type=checkbox value="<%=number%>" /> <%=number%>.
NOW
<input name="<%=number%>" type=checkbox /> <%=number%>.
So in my second .jsp I get a Enumeration with the names of the selected checkboxes, which are the phone numbers.
java.util.Enumeration enu = request.getParameterNames();
java.util.List<String> numbers = new java.util.ArrayList<String>();
while(enu.hasMoreElements()){
String s = (String)(enu.nextElement());
System.out.println(s);
numbers.add(s);
}

Expanding HTML forms using Javascript

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.

Categories

Resources