Create dynamic HTML form using javascript - javascript

I've been googling and googling but completely stuck on this.
I have a GET request that retrieves some JSON containing a list of users. However the list of users changes.
I want to generate a simple HTML form that contains the names of the users, and then an input field so that they can be given a rating. I then need to gather the ratings and send a POST request in JSON.
What would be the best way to approach this? I was thinking of looping through the users and just displaying them with a text input type but then I have no idea how I can use the form data to send the POST request!
Any help would be greatly appreciated

Populate UI base on JSON
HTML:
<form id="user_list">
<div>
</div>
<input type="submit"/>
</form>
JS:
var obj = {
users:[{name:"user 1"},{name:"user 2"}]
}
var user_list = $("#user_list>div");
obj.users.forEach(function(user,index){
user_list.append("<div>"+
"<h1>" + user.name + "</h1>"+
"<input type='text' id='user_"+ index +"'/>"+
"</div>");
});
Send selected values to server.
Option 1
If you make this page full post back when click on submit, you have to change text boxes as following
"<input type='text' name='[user_"+ index +"]'/>"+
In server request object, you will be give as array of key/values.
Option 2
If you are planing to make AJAX request, again you can loop though the text boxes and build the JSON format which you want in back-end and pass though the AJAX.
$("input[type='text']").each(function(input){
$(input).val();
});

Related

dynamically creates input box inside jsp and send to servlet

I created a jsp which has a script that adds input boxex dynamically, the problem is I don't know how am I supposed to throw it on the servlet in order to save the data to the database from those dynamic input boxes. Please help me.
var i = 1;
<form id="add_pname" name="add_pname"><table class="table table-bordered" id="dynamic_field">
<tr>
<td><select name="txtProduct" id="txtProduct" class="form-control name_list" ><option value="">- Product -</option><%=obj.getProductOpt("")%></select></td>
</tr></table></form>
//adding input boxes
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><select name="txtProduct" id="txtProduct" class="form-control name_list" ><option value="">- Product -</option><%=obj.getProductOpt("")%></select></td><td><input type="text" name="txtQty" id="txtQty'+i+'" class="form-control"/></td><td><input type="button" name="remove" value="X" id="'+i+'" class="btn btn-danger btn_remove"/> </td></tr>');
});
//removing input boxes
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
I want to pass all added input boxes to servlet and save it to the database. pelase help me
Well, there are different ways to solve that, let's describe two of them.
Client-side approach
I would add a submission handler to the form (submit="myHandler()"), where I would cycle through all the table rows, get the drop-down value (txtProduct) and the text value (txtQty), combine them into an object, add this object into an array, and afterwards send the array to the servlet, either via standard POST form submit (e.g. stringified as a hidden form field), or via AJAX call.
The servlet then needs to deserialize the data and create their Java representation to store it into the database.
Server-side approach
When adding the input fields dynamically, don't use the same name, but rather add a counter, so you will have table rows with txtProduct1 and txtQty1, then txtProduct2 + txtQty2, and so on. Then simply send the form to the servlet, using normal form submission.
The servlet then needs to iterate the request parameters (see e.g. https://stackoverflow.com/a/2595272/3511123) get all the txtProductX and txtQtyX parameters and their values, combine them (because thanks to that numbers it is clear which Qty belongs to what Product), and store into the DB.
Sorry for no code, but with code examples it would be an article / tutorial, not a simple answer. If you need some help with particular steps, feel free to ask a new question (after you do the obvious googling).

How can i get element by id in node.js

How can i get element id: <input type="number" name="1" id="cant1" style="width:60px;" required/> in node.js?
Actually i've got this: var cant = req.param("cant1"); but i get the name's input and i need the id.
Thanks for help me.
The ID is only used client side. The name is used to generate the form data that is sent to the server.
If you need the ID then you'll need to encode it in the form data somehow. Possible approaches include:
Just using that value as the name instead of 1
Using JavaScript to copy the ID value on top of the name or the value when the form is submitted
Generate a set of hidden inputs that map the name and id values (e.g. <input name="the_id_for_1" value="cant1">)
Generate some complex data structure in JSON and post it with Ajax instead of using a regular form submission

JavaScript/Ajax to Dynamically Update WTForms Select Field

OK. I know this has been tackled many times but I can't find an answer with a useful example of javascript to use.
Say I have this form:
class MyForm(Form):
category = SelectField("Category")
issue = SelectField("Issue")
What I need is for whatever is selected in 'category' at runtime to determine what the user sees in the issue dropdown without a POST of any kind ocurring. I know how to dynamically create the choices in the view from my database query. I even have gone so far as to create a dictionary of "issue choices" based off of category choices.
I just can't for the life of me figure out the javascript I need so that on select of something from the category drop down determines whats in the issue dropdown.
I found the info I needed by looking at the example at Flask jQuery AJAX Example -
- it is a minimal working example, almost a
GIST or a book chapter.
I came up with an example very close to jsbueno's implementation. You can find the Gist here. The .py file is a standalone example.
In your html template use jquery to register an ajax request when you click the select field. If the request is a success the html for the select field gets updated with the new select options (send as a response from the server). Look at the actual HTML generated by the template to see how the select field looks like.
<form action="" method="post" id="selectDevice" name="device">
Nummber of Devices: {{ form.selectAmount(size=1) }}
Select device: {{form.deviceAddress() }}
</form>
<script type="text/javascript" charset="utf-8">
$("#deviceAddress").click(function(){
$.ajax({
url: '/selectform',
type: 'POST',
data: $('#selectDevice').serialize(),
success: function(selectOptions){
$("#deviceAddress").empty();
for (var i = 0; i < selectOptions.length; i++){
$("#deviceAddress").append(
$("<option></option>")
.attr("value", selectOptions[i][0])
.text(selectOptions[i][1])
);
}
}
});
});
</script>
On the server side, use a route for the ajax post request.`As example this route changes the options depending on another form field (the information got send over with the data tag in the ajax request). In WTForms the select field options is a list of tuples containing an ID and name, I kept this the same on the python side.
#app.route('/selectform', methods=['POST'])
def updateselect():
deviceAmount = int(request.form.get('selectAmount'))
choices = [('device{}'.format(i), i) for i in range(deviceAmount)]
response = make_response(json.dumps(choices))
response.content_type = 'application/jsons'
return response`
Only one remark: the ajax request is performed on dropping down and on collapsing. The last part is not necessary of course, there is probably a way to structure the jquery so it only requests on dropdown.

Get random data from database,

I have a little problem, I've got this database with these fields.
Table Data{
ID
Name,
Text,
Location,
imagepath
}
And now I want the put these values into my fields, the data is just strings.
<h3><!-- Text value here --> - <!-- Name value here --></h3>
<p> <!-- Location data here --> </p>
And I also got this JS script that generates new fields, when the user clicks on a button.
$('.Next').click(function(e) {
e.preventDefault();
Slide.appendSlide('<!-- HTML DATA HERE NAME AND TEXT & LOCATION VALUES -->')});
I want the ID to be random, and I don't want the user to get the same data twice.
How should i approach this? I've tried a getdata.php but failed.
Thank you so much! Happy holidays!
Honestly i would look at saving the page id to $_session['visited']. Then each time they view a page append that to the session variable comma separated
$_session['visited'] .= ",".$page_id;
Then your sql will be.
EDITED
Ok so let make this code safe
$ph = explode(",",$_session['visited']);
foreach($ph as $check){
if (!isnumeric($check)){
echo "Not numeric, possible injection";
exit;
}
}
$parmcount=count($ph);
$inclause=implode(',',array_fill(0,$parmcount,'?'))
$sql='SELECT * FROM table WHERE ID NOT IN (%s)';
$preparesql=sprintf($sql,$inclause);
$st=$db->prepare($preparesql);
$st->execute($parms);
Or alternative just save all viewed ids as an array in the first place.

jquery cant read textfield value

I got a problem today with some codes regarding reading textfield value.
the value is returned back to the page as the result of a query from a php file:
//the first text filed with event calling a php file to query the name's order in the list.
<label for=name>Name</label>
<input id=name name=name type=text placeholder="Individual / Company Director" required onblur="getOrderInList();" >
the function getOrderInList() does a query and sends the result back to the caller page using javascript
parent.document.getElementById('customerorder')=document.getElementById('query_result');
the query result which is an integer, is supposed to be back to the main page where the name text field is in a specific hidden text box customercode
using jQuery i need to show it on the page using an alert for example. but seems to be undefined.
can anyone help me with this.
your code is in javascript and you are mentioning jquery in your question. its a bit confusing but my guess is you need your javascript code to be corrected
parent.document.getElementById('customerorder').value = document.getElementById('query_result').value;
In JavaScript:
parent.document.getElementById('customerorder').value = document.getElementById('query_result').value;
In jQuery:
$('#customerorder').val( $('#query_result').val() )

Categories