I'm trying to take input from the user from a drop-down list. I've used javascript to take input of dynamic size and then stored the input in a variable using appendChild. Now I want to send this variable back to django views where I can perform some operations on it.
I've tried using getlist and get function in django but am not able to figure out how to get the variable.
<form method = "POST" name = "myForm" onsubmit = "return validateForm()">{% csrf_token %}
<p>Entry Condtion:</p>
<div id ="entry-parameters"></div>
<button type="button" onclick= "add_entry_parameter()" class="btn btn-primary m-t-15 waves-effect">Add a new Entry Condition</button>
<button type= "button" onclick= "remove_entry_parameter()" class= "btn btn-primary m-t-15 waves-effect">Remove Entry Condtion</button>
<br>
<p>Exit Condtion</p>
<div id = "exit-parameters"></div>
<button type="button" onclick= "add_exit_parameter()" class="btn btn-primary m-t-15 waves-effect">Add a new Exit Condition</button>
<button type= "button" onclick= "remove_exit_parameter()" class= "btn btn-primary m-t-15 waves-effect">Remove Exit Condtion</button>
<br>
<br>
<br>
<input type="submit" value="submit" >
</form>
<script>
var list = ['open' , 'close' , 'high', 'low'];
var addField = document.getElementById('addField');
parameters= document.getElementById('entry-parameters');
exit_parameters= document.getElementById('exit-parameters');
parameters.setAttribute("name" , "parameters" );
exit_parameters.setAttribute("name" , "exit_parameters");
function remove_entry_parameter()
{
parameters.removeChild(parameters.lastElementChild);
}
function add_entry_parameter()
{
var _form = document.body.appendChild(document.createElement('form')),
_input = _form.appendChild(document.createElement('input')),
_condition = _form.appendChild(document.createElement('input')),
_input2 = _form.appendChild(document.createElement('input')),
_datalist = _form.appendChild(document.createElement('datalist'));
_cond_list = _form.appendChild(document.createElement('datalist'));
_input.placeholder = "First Parameter";
_input.list = 'exampleList';
_input.setAttribute('list','exampleList')
_input.datalist_id = 'exampleList';
_input2.placeholder = "Second Parameter";
_input2.list = 'exampleList';
_input2.setAttribute('list','exampleList')
_input2.datalist_id = 'exampleList';
_condition.placeholder = "Condition";
_condition.list = 'conditionList';
_condition.setAttribute('list','conditionList')
_condition.datalist_id = 'conditionList';
_datalist.id = 'exampleList';
_cond_list.id = 'conditionList';
var list = ['open' , 'close' , 'high' , 'low' , 'vol'];
var cond_list = ['greater than', 'less than' , 'crossed above' , 'crossed below', 'equal to'];
for (var i = 0; i < list.length ; i++) {
var _option = _datalist.appendChild(document.createElement('option'));
_option.text =list[i];
};
for (var i = 0; i < cond_list.length ; i++) {
var _option = _cond_list.appendChild(document.createElement('option'));
_option.text = cond_list[i];
};
parameters.appendChild(_form);
}
// I've written a similar code for exit_parameters
</script>
def get_data(request):
if request.method == 'POST':
entry_data = request.POST.get('parameters')
exit_data = request.POST.get('exit_parameters')
print(entry_data)
print(exit_data)
return render(request, 'get_data.html' , {})
Your function add_entry_parameter starts by creating a new form on the page. You almost certainly want ONE form on the page -- no need to create new ones.
The selection made in the dropdown should be visible in the DOM (inspector) with a unique field name (it doesn't make sense for all fields on the form to have the same name, as you stated in a response above) -- all fields must have a unique name.
Once you've verified that the value in an existing, uniquely named field is updated when the user makes a selection, it should come through in the POST.
Related
In my index.html, I prompt the user to enter a name which creates a button with the name on it. When clicked, it leads to inside_goal.html
<script>
var counter = 0;
function createButton(){
var x = document.createElement("BUTTON");
x.className = "second";
x.id = "first";
var name = document.querySelector("#goal").value;
var t = document.createTextNode(name);
x.appendChild(t);
document.getElementById("space_holder").appendChild(x);
var insideclass = document.getElementsByClassName("second");
insideclass[counter].innerHTML = `<input type="button" onclick="location.href='/inside_goal'" value="${name}"/>`;
counter = counter+1;
document.querySelector("#goal").value = "";
};
</script>
</head>
<body>
<h1 id = "home_header" style = "font-family: optima; text-align: center"> Nancy Dong </h1>
<div id = "enter.goal">
<form action = /inside_goal id = "subBox" onsubmit = "createButton(); return false;">
<input name = "name", type = "text", id = "goal">
<input type = "submit", value = "Enter Goal">
</form>
</div>
inside_goal.html
<body>
<h1 id = "h1">
testing {{ name }} !!!
</h1>
</body>
My flask looks like
from flask import Flask, render_template, request, session
app = Flask(__name__)
#app.route("/")
def index():
return render_template("index.html")
#app.route("/inside_goal")
def names():
name = request.args.get('name')
return render_template("inside_goal.html", name = name)
I want inside_goal.html to have the same header as the button that was clicked on. However, the heading is currently returning "testing None". The get request couldn't get the name.
I also tried
var test = "";
$("button).click(function(){
test = $(this).val();
alert(test);
})
to test out if I could get button values that way, but only got the initialization value.
I'm fairly new to web development, so I might be missing some concepts. Any help is appreciated!
I wanted to change ID of textarea using onclick button. So I created two buttons across my field. Each on click run a function.
Issue: It just replace my id first time and second time when i click on second button it throws error saying "Uncaught TypeError: Cannot set property 'id' of null at ti_pos_fun (index.html:491)"
HTML code-
<div>
<label for="usr">ti:</label> <i class="glyphicon glyphicon-check" onclick="ti_pos_fun()"></i> <i class='glyphicon glyphicon-unchecked' onclick="ti_neg_fun()"></i>
</div>
I am trying to use two buttons- example
Now when you click check button- ti runs the onclick function "ti_pos_fun".
Function are as follows
function ti_neg_fun ()
{
var a = document.getElementById("jsel");
a.id = "ti_neg";
//$("#ti_neg").text('angry');
document.getElementById('ti_neg').innerHTML = 'angry';
}
function ti_pos_fun ()
{
var a = document.getElementById("jsel");
a.id = "ti_pos";
document.getElementById('ti_pos').innerHTML = 'hahahahaha';
//$("#ti_pos").text('hahahaha');
}
Textarea code where these ids are going & their text.
<div class="col-md-10">
<H3> textarea</H3>
<textarea id = "jsel"></textarea>
</div>
You click on button 1 - check button
It gets id and text in textarea
When you click on button 2- uncheck button
It fails
Its not working on 2nd click because you are overwriting the id of that element
//a.id = "ti_neg";
so on 2nd click there is no element with id jsel and below statement will return null and it will not work.
document.getElementById("jsel");
function ti_neg_fun ()
{
var a = document.getElementById("jsel");
//a.id = "ti_neg";
//$("#ti_neg").text('angry');
document.getElementById('jsel').innerHTML = 'angry';
}
function ti_pos_fun ()
{
var a = document.getElementById("jsel");
//a.id = "ti_pos";
document.getElementById('jsel').innerHTML = 'hahahahaha';
//$("#ti_pos").text('hahahaha');
}
<div>
<label for="usr">ti:</label> <i class="glyphicon glyphicon-check" onclick="ti_pos_fun()">1</i> <i class='glyphicon glyphicon-unchecked' onclick="ti_neg_fun()">2</i>
</div>
<div class="col-md-10">
<H3> textarea</H3>
<textarea id = "jsel"></textarea>
</div>
That's because the ID isn't jsel anymore you need something like this, if it can't find jsel check for the ID the other function set and visa versa. EDIT: added snip that works.
function ti_pos_fun ()
{
var a = document.getElementById("jsel");
if (a != null){
a.id = "ti_pos";
document.getElementById('ti_pos').innerHTML = 'hahahahaha';
//$("#ti_pos").text('hahahaha');
}else{
var a = document.getElementById("ti_neg");
a.id = "ti_pos";
document.getElementById('ti_pos').innerHTML = 'hahahahaha';
//$("#ti_pos").text('hahahaha');
}
}
function ti_neg_fun ()
{
var a = document.getElementById("jsel");
if(a != null){
a.id = "ti_neg";
//$("#ti_neg").text('angry');
document.getElementById('ti_neg').innerHTML = 'angry';
}else{
var a = document.getElementById("ti_pos");
a.id = "ti_neg";
//$("#ti_neg").text('angry');
document.getElementById('ti_neg').innerHTML = 'angry';
}
}
<div>
<label for="usr">ti:</label> <i class="glyphicon glyphicon-check" onclick="ti_pos_fun()">postitive</i> <i class='glyphicon glyphicon-unchecked' onclick="ti_neg_fun()">negative</i>
</div>
<div class="col-md-10">
<H3> textarea</H3>
<textarea id = "jsel"></textarea>
</div>
I have form which gets clone when user click on add more button .
This is how my html looks:
<div class="col-xs-12 duplicateable-content">
<div class="item-block">
<button class="btn btn-danger btn-float btn-remove">
<i class="ti-close"></i>
</button>
<input type="file" id="drop" class="dropify" data-default-file="https://cdn.example.com/front2/assets/img/logo-default.png" name="sch_logo">
</div>
<button class="btn btn-primary btn-duplicator">Add experience</button>
...
</div>
This my jquery part :
$(function(){
$(".btn-duplicator").on("click", function(a) {
a.preventDefault();
var b = $(this).parent().siblings(".duplicateable-content"),
c = $("<div>").append(b.clone(true, true)).html();
$(c).insertBefore(b);
var d = b.prev(".duplicateable-content");
d.fadeIn(600).removeClass("duplicateable-content")
})
});
Now I want every time user clicks on add more button the id and class of the input type file should be changed into an unique, some may be thinking why I'm doing this, it I because dropify plugin doesn't work after being cloned, but when I gave it unique id and class it started working, here is what I've tried :
function randomString(len, an){
an = an&&an.toLowerCase();
var str="", i=0, min=an=="a"?10:0, max=an=="n"?10:62;
for(;i++<len;){
var r = Math.random()*(max-min)+min <<0;
str += String.fromCharCode(r+=r>9?r<36?55:61:48);
}
return str;
} var ptr = randomString(10, "a");
var className = $('#drop').attr('class');
var cd = $("#drop").removeClass(className).addClass(ptr);
Now after this here is how I initiate the plugin $('.' + ptr).dropify().
But because id is still same I'm not able to produce clone more than one.
How can I change the id and class everytime user click on it? is there a better way?
Working Fiddle.
Problem :
You're cloning a div that contain already initialized dropify input and that what create the conflict when you're trying to clone it and reinitilize it after clone for the second time.
Solution: Create a model div for the dropify div you want to clone without adding dropify class to prevent $('.dropify').dropify() from initialize the input then add class dropify during the clone.
Model div code :
<div class='hidden'>
<div class="col-xs-12 duplicateable-content model">
<div class="item-block">
<button class="btn btn-danger btn-float btn-remove">
X
</button>
<input type="file" data-default-file="http://www.misterbilingue.com/assets/uploads/fileserver/Company%20Register/game_logo_default_fix.png" name="sch_logo">
</div>
<button class="btn btn-primary btn-duplicator">Add experience</button>
</div>
</div>
JS code :
$('.dropify').dropify();
$("body").on("click",".btn-duplicator", clone_model);
$("body").on("click",".btn-remove", remove);
//Functions
function clone_model() {
var b = $(this).parent(".duplicateable-content"),
c = $(".model").clone(true, true);
c.removeClass('model');
c.find('input').addClass('dropify');
$(b).before(c);
$('.dropify').dropify();
}
function remove() {
$(this).closest('.duplicateable-content').remove();
}
Hope this helps.
Try this:
$(function() {
$(document).on("click", ".btn-duplicator", function(a) {
a.preventDefault();
var b = $(this).parent(".duplicateable-content"),
c = b.clone(true, true);
c.find(".dropify").removeClass('dropify').addClass('cropify')
.attr('id', b.find('[type="file"]')[0].id + $(".btn-duplicator").index(this)) //<here
$(c).insertBefore(b);
var d = b.prev(".duplicateable-content");
d.fadeIn(600).removeClass("duplicateable-content")
})
});
Fiddle
This does what you specified with an example different from yours:
<div id="template"><span>...</span></div>
<script>
function appendrow () {
html = $('#template').html();
var $last = $('.copy').last();
var lastId;
if($last.length > 0) {
lastId = parseInt($('.copy').last().prop('id').substr(3));
} else {
lastId = -1;
}
$copy = $(html);
$copy.prop('id', 'row' + (lastId + 1));
$copy.addClass('copy');
if(lastId < 0)
$copy.insertAfter('#template');
else
$copy.insertAfter("#row" + lastId);
}
appendrow();
appendrow();
appendrow();
</script>
Try adding one class to all dropify inputs (e.g. 'dropify'). Then you can set each elements ID to a genereted value using this:
inputToAdd.attr('id', 'dropify-input-' + $('.dropify').length );
Each time you add another button, $('.dropify').length will increase by 1 so you and up having a unique ID for every button.
I have a button and when I click it, I want the html object (aka button) to be passed as a parameter to another javascript function. I want the javascript function to print the data-hi from the element in the button.
HTML BUTTON
<button type = "button" onclick = "whoIsRdns(this)" class="dns-information btn btn-xs btn-info pull-right" data-toggle="modal" data-target = "#whois_rdns_modal" data-path="{{ path( '_who_is_rdns', { 'peer': peer.number, 'ip': peer.mac } ) }}" data-hi = "hi2">
<i class="icon-search"></i>
</button>
JS FUNCTION(W/ JQUERY)
function whoIsRdns(thisButton){
//Enable jQuery properties from the param of the HTML object
var btn = $(thisButton);
var test = btn.data('hi');
console.log('Value is ' + test);
}
Why would test return as null?
Shouldn't var btn = $("thisButton"); be var btn = $(thisButton); (without quotes)
Just a typo
$("thisButton") !== $(thisButton);
drop the quotes so you are not looking for an element with a tag name thisButton
var btn = $("thisButton");
needs to be
var btn = $(thisButton);
I need to do the following (I'm a beginner in programming so please excuse me for my ignorance): I have to ask the user for three different pieces of information on three different text boxes on a form. Then the user has a button called "enter"and when he clicks on it the texts he entered on the three fields should be stored on three different arrays, at this stage I also want to see the user's input to check data is actually being stored in the array. I have beem trying unsuccessfully to get the application to store or show the data on just one of the arrays. I have 2 files: film.html and functions.js. Here's the code. Any help will be greatly appreciated!
<html>
<head>
<title>Film info</title>
<script src="jQuery.js" type="text/javascript"></script>
<script src="functions.js" type="text/javascript"></script>
</head>
<body>
<div id="form">
<h1><b>Please enter data</b></h1>
<hr size="3"/>
<br>
<label for="title">Title</label> <input id="title" type="text" >
<br>
<label for="name">Actor</label><input id="name" type="text">
<br>
<label for="tickets">tickets</label><input id="tickets" type="text">
<br>
<br>
<input type="button" value="Save" onclick="insert(this.form.title.value)">
<input type="button" value="Show data" onclick="show()"> <br>
<h2><b>Data:</b></h2>
<hr>
</div>
<div id= "display">
</div>
</body>
</html>
var title=new Array();
var name=new Array();
var tickets=new Array();
function insert(val){
title[title.length]=val;
}
function show() {
var string="<b>All Elements of the Array :</b><br>";
for(i = 0; i < title.length; i++) {
string =string+title[i]+"<br>";
}
if(title.length > 0)
document.getElementById('myDiv').innerHTML = string;
}
You're not actually going out after the values. You would need to gather them like this:
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;
You could put all of these in one array:
var myArray = [ title, name, tickets ];
Or many arrays:
var titleArr = [ title ];
var nameArr = [ name ];
var ticketsArr = [ tickets ];
Or, if the arrays already exist, you can use their .push() method to push new values onto it:
var titleArr = [];
function addTitle ( title ) {
titleArr.push( title );
console.log( "Titles: " + titleArr.join(", ") );
}
Your save button doesn't work because you refer to this.form, however you don't have a form on the page. In order for this to work you would need to have <form> tags wrapping your fields:
I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit
The new form follows:
<form>
<h1>Please enter data</h1>
<input id="title" type="text" />
<input id="name" type="text" />
<input id="tickets" type="text" />
<input type="button" value="Save" onclick="insert()" />
<input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>
There is still some room for improvement, such as removing the onclick attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).
I've also made some changes to your JavaScript. I start by creating three empty arrays:
var titles = [];
var names = [];
var tickets = [];
Now that we have these, we'll need references to our input fields.
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
I'm also getting a reference to our message display box.
var messageBox = document.getElementById("display");
The insert() function uses the references to each input field to get their value. It then uses the push() method on the respective arrays to put the current value into the array.
Once it's done, it cals the clearAndShow() function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.
function insert ( ) {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
This function, as previously stated, starts by setting the .value property of each input to an empty string. It then clears out the .innerHTML of our message box. Lastly, it calls the join() method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.
function clearAndShow () {
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}
The final result can be used online at http://jsbin.com/ufanep/2/edit
You have at least these 3 issues:
you are not getting the element's value properly
The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.
You can save all three values at once by doing:
var title=new Array();
var names=new Array();//renamed to names -added an S-
//to avoid conflicts with the input named "name"
var tickets=new Array();
function insert(){
var titleValue = document.getElementById('title').value;
var actorValue = document.getElementById('name').value;
var ticketsValue = document.getElementById('tickets').value;
title[title.length]=titleValue;
names[names.length]=actorValue;
tickets[tickets.length]=ticketsValue;
}
And then change the show function to:
function show() {
var content="<b>All Elements of the Arrays :</b><br>";
for(var i = 0; i < title.length; i++) {
content +=title[i]+"<br>";
}
for(var i = 0; i < names.length; i++) {
content +=names[i]+"<br>";
}
for(var i = 0; i < tickets.length; i++) {
content +=tickets[i]+"<br>";
}
document.getElementById('display').innerHTML = content; //note that I changed
//to 'display' because that's
//what you have in your markup
}
Here's a jsfiddle for you to play around.