How can I make the options appear in a select dynamically? - javascript

I am trying to load the following options in my html, generated in javascript.
HTML:
<button type="submit" onClick="input(data)">Add</button>
<select id="processSelect" name="process">
</select>
Javascript:
function input(input){
//my code
createOptionsSelectProcess(arrayResponse);
}
function createOptionsSelectProcess(arrayResponse){
var html = '';
var arrayLength = arrayResponse.length;
for (var i = 0; i < arrayLength; i++) {
html += '<option value="'+ arrayResponse[i] +'">' + arrayResponse[i]
+ '</option>';
}
document.getElementById("processSelect").innerHTML = html;
}
However, the result I have observed in debug is that the options are generated in the select, but they disappear when the execution is finished. Does anyone know what the reason may be?

button type submit will submit the form and refresh the page, use
<button type="button" onClick="input(data)">Add</button>
Also by default button is of type submit so if you don't put it it will still submit the form.

You don't need the function input(input). You can use the event listener submit to submit the form.
document.addEventListener('submit', () => createOptionsSelectProcess(data))
function createOptionsSelectProcess(arrayResponse) {
var html = '';
var arrayLength = arrayResponse.length;
for (var i = 0; i < arrayLength; i++) {
html += '<option value="'+ arrayResponse[i] +'">' + arrayResponse[i] + '</option>';
}
document.getElementById("processSelect").innerHTML = html;
}
<form>
<button>Add</button>
<select id="processSelect" name="process"></select>
</form>
You could use <button>Add</button> or <input type="submit" value="Add">. They will both submit the form without an onClick attribute.

Related

JS: Calling function on Submit

Hello everyone I'm still new to JS, so I want to ask about calling a function when form is submitted.
[update] Form
<div id="dashboard-side">
<form id="report" class="form-horizontal" method="post" action="<?= site_url('api/load_report') ?>"> <!-- onsubmit="location.reload()" -->
<fieldset>
<div class="control-group center_div">
<label class="control-label">Sales Name</label>
<div class="controls">
<input type="text" name="sales_name" class="form-control input-xlarge txt-up" value="<?php echo set_value('cust_name'); ?>" placeholder="Enter Customer Name" style="height: 30px;"/>
</div>
</div>
<div class="control-group center_div">
<div class="controls form-inline">
<input id="get_report" type="submit" class="btn btn-success btn-inline " value="Get Report" style="width:110px; margin-left: -155px;"/>
</div>
</div>
<table border="1" width="100%" style="background-color: #dfe8f6;">
<tr>
<td width="154px"><strong>Customer Name</strong></td><td width="128px"><strong>Activity</strong></td>
<td width="244px"><strong>Detail</strong></td><td width="141px"><strong>Start Time</strong></td>
<td width="142px"><strong>Finish Time</strong></td><td width="39px" style="text-align:center"><strong>Note</strong></td>
<td style="margin-left: 50px"><strong>Action</strong></td>
</tr>
</table>
<!------------------------------------------------------------------------------------->
<div id="xreport" class="table-hover" style="background-color: #EAF2F5"></div>
</fieldset>
</form>
</div>
Controller
public function load_report() {
$this->db->where('user_id', $this->input->post('sales_name'));
$query = $this->db->get('activity');
$result = $query->result_array();
$this->output->set_output(json_encode($result)); }
JS
var load_report = function() {
$.get('api/load_report', function(o){
var output = '';
for (var i = 0; i < o.length; i++){
output += Template.dodo(o[i]);
}
$("#xreport").html(output);
}, 'json');
};
If I call the function on form load it works fine, but I want to call it on form submit, how to do that?
Here is what I tried
var load_report = function () {
$("#report").submit(function(){
$.get('api/load_report', function(o){
var output = '';
for (var i = 0; i < o.length; i++){
output += Template.dodo(o[i]);
}
$("#xreport").html(output);
}, 'json');
});
};
Instead of assigning the array into my #div, it shows the array data in the new blank tab like this:
my current result so far
any help would be appreciated, thanks.
Update: New calling function
var load_report = function () {
$("#report").submit(function (evt) {
evt.preventDefault();
var url = $(this).attr('action');
var postData = $(this).serialize();
$.post(url, postData, function (o) {
if (o.result == 1) {
var output = '';
Result.success('Clocked-in');
for (var i = 0; i < o.length; i++) {
output += Template.dodo(o[i]); //this data[0] taken from array in api/load_report
console.log(output);
$("#xreport").html(output);
}
} else {
Result.error(o.error);
console.log(o.error);
}
}, 'json');
});
};
with this new calling function I'm able to retrieve data from api/load_report without getting stuck on e.preventDefault or even open a new tab, I console.log and the result show correctly in the console, but it doesn't show on the div somehow.
my template.js (if needed)
this.dodo = function(obj){
var output ='';
output +='<table border=1, width=100%, style="margin-left: 0%"';
output += '<tr>';
output += '<td width=120px>' + obj.user_id + '</td>';
output += '<td width=120px>' + obj.cust_name + '</td>';
output += '<td width=100px>' + obj.act_type + '</td>';
output += '<td width=190px>' + obj.act_detail + '</td>';
output += '<td width=110px>' + obj.date_added + '</td>';
output += '<td width=110px>' + obj.date_modified + '</td>';
output += '<td style="text-align:center" width=30px>' + obj.act_notes + '</td>';
output += '</tr>';
output +='</table>';
output += '</div>';
return output;
};
Result (note, user_id = form.sales_name)
result preview
First off, I would advise against using onclick or onsubmit directly on the dom like so.
<form onsubmit="myFunction();"></form>
The biggest reason for me is that it negatively impacts readability and sometimes even future maintenance of the project . It is nice to keep html and javascript separate unless you are using a framework that provides templating features/functionality such as angularjs.
Another big one is that you can only have one in-line event present and it is easy to accidentally overwrite, which can lead to confusing bugs.
The reason it is going to a new tab is because of the .submit(). This will call your function, but then proceed with internal jQuery event handling which includes refreshing the page. There are two solutions I see most viable here.
1st Solution:
Add a event.preventDefault(); at the start of your function to stop jQuery from refreshing your page.
$("#report").submit(function(e) {
e.preventDefault();
});
2nd Solution (Likely better):
You are making an ajax call with $.get(...). You could add an event listener on a button (probably on the button used to submit the form) that fires your ajax call. Here is an example that assumes the submit button has the id of loadData.
$("#loadData").click(function(){
$.get('api/load_report', function(o){
var output = '';
for (var i = 0; i < o.length; i++){
output += Template.dodo(o[i]);
}
$("#xreport").html(output);
}, 'json');
}
You could alway do the following:
function myFunction() {
alert("Hello! I am an alert box! in a function");
}
<form>
<input type="text" />
<input type="submit" value="submit" onclick="return myFunction();"/>
</form>
P.S. This question might be answered in this question already, add onclick function to a submit button
Try to prevent form to get submit by using preventDefault()
$("#report").submit(function(e){ //add param "e"
e.preventDefault(); //to prevent form to submit
//further code....
});
Ok just try
function mysubmit(){
$.get('api/load_report', function(o){
var output = '';
for (var i = 0; i < o.length; i++){
output += Template.dodo(o[i]);
}
$("#xreport").html(output);
}, 'json');
}
as your script and
<form id="report" class="form-horizontal" onsubmit="event.preventDefault(); mysubmit();" method="post" action="<?= site_url('api/load_report') ?>">
as your form

How to enable actions on toggle selected items

I'm developing an Admin Panel on a website (Python + Flask) and I came across with an issue while trying to implement a Select All toggle.
The table looks like the following:
The toggle itself has been implemented but now I want to make it useful.
Upon clicking the 'SELECTED' button I want to be able to delete each and every selected item (flag) but I'm not exacly sure how I can pull it off.
Each flag can be individually deleted by clicking on the glyphicon-trash according to the following Python/HTML:
<button onclick="deleteSelected('politician')">SELECTED</button>
{% for flag in flags %}
<tr>
<!-- Check box -->
<td style="width: 60px;"><input type="checkbox" name="politician" value="bar1"></td>
<!-- First Name -->
<td class="col-title">{{flag.flagtitle}}</td>
<!-- Last Name -->
<td class="col-description">{{flag.flagreason}}</td>
<!-- Details -->
<td>
<a href="/flag/{{ flag.idflag }}">
<span class="glyphicon glyphicon-info-sign"></span>
</a>
</td>
<!-- Edit icon -->
<td class="list-buttons-column">
<a href="/politician/{{ flag.politician }}">
<span class="glyphicon glyphicon-pencil"></span>
</a>
</td>
<!-- DELETE ITEM/FLAG -->
<td class="col-delete">
<form action ="/delete_flag/{{ flag.idflag }}" method="POST">
<button onclick="return confirm('Are you sure you want to delete this flag?');">
<span class="fa fa-trash glyphicon glyphicon-trash"></span>
</button>
</form>
</td>
</tr>
{% endfor %}
My idea was to develop a JavaScript function to delete the selected content but I'm not sure how I can get the flag.idFlag, which is the flags' id's associated.
I thought it would look something like this:
function deleteSelected(elem) {
checkboxes = document.getElementsByName(elem);
for(var i=0, n=checkboxes.length;i<n;i++) {
if (checkboxes[i].checked) {
delete((checkboxes[i].getSelectedFlag).idFlag)
}
}
}
Obviously the code above doesn't work, it was just meant to give you an idea of what I'm looking for.
Is there a way I can do this? Thanks in advance.
EDIT:
Ok so I figured it out. Considering I had to submit multiple forms where action="/delete_flag/flag.idFlag", I added a column to the table where the flag's id would be visible. Like the following:
For that matter, I created a JS function to retrieve the first value of each row (ID) and store it in an array of IDs so that I could create and submit a form for each one of them.
For each ID of the array I create a form where form.action = "/delete_flag/" + retrievedID. See code below.
function deleteRecords() {
var arrayOfIDs;
arrayOfIDs = $('#table-style').find('[type="checkbox"]:checked').map(function(){
return $(this).closest('tr').find('td:nth-child(2)').text();
}).get();
var delFlagForm = document.createElement("form");
var action;
var formID;
var submitFormStr;
for (var i = 0; i < arr.length; i++) {
action = "/delete_flag/" + arr[i];
formID = 'form' + i;
delFlagForm.setAttribute("id", formID);
delFlagForm.setAttribute("method", "post");
delFlagForm.setAttribute("action", action);
delFlagForm.submit();
}
}
This sounded good in my head until I realised multiple form submissions will only work asynchronously. So I made the following changes and this is where I'm stuck right now. The forms simply won't be submitted, nothing happens:
function deleteRecords() {
var arraryOfIDs;
arraryOfIDs = $('#table-style').find('[type="checkbox"]:checked').map(function(){
return $(this).closest('tr').find('td:nth-child(2)').text();
}).get();
var delFlagForm = document.createElement("form");
var action;
var formID;
var submitFormStr;
for (var i = 0; i < arr.length; i++) {
action = "/delete_flag/" + arr[i];
formID = 'form' + i;
delFlagForm.setAttribute("id", formID);
delFlagForm.setAttribute("method", "post");
delFlagForm.setAttribute("action", action);
if (i != 0) submitFormStr += ' #' + formID;
else submitFormStr = '#' + formID;
}
$('submitFormStr').submit();
return false;
}
The variable submitFormStr updated within the loop stores the id for each form created like the following: #form0 #form1so for this reason I don't understand why the piece of code $('submitFormStr').submit(); which is equivalent to $('#form0 #form1').submit(); is not working.
Is there anything I'm doing wrong?
Ok so I figured it out. Considering I had to submit multiple forms where action="/delete_flag/flag.idFlag", I added a column to the table where the flag's id would be visible. Like the following:
For that matter, I created a JS function to retrieve the first value of each row (ID) and store it in an array of IDs so that I could create and submit a form for each one of them.
For each ID of the array I create a form where form.action = "/delete_flag/" + retrievedID. See code below.
function deleteRecords() {
var arrayOfIDs;
arrayOfIDs = $('#table-style').find('[type="checkbox"]:checked').map(function(){
return $(this).closest('tr').find('td:nth-child(2)').text();
}).get();
var delFlagForm = document.createElement("form");
var action;
var formID;
var submitFormStr;
for (var i = 0; i < arr.length; i++) {
action = "/delete_flag/" + arr[i];
formID = 'form' + i;
delFlagForm.setAttribute("id", formID);
delFlagForm.setAttribute("method", "post");
delFlagForm.setAttribute("action", action);
delFlagForm.submit();
}
}
This sounded good in my head until I realised multiple form submissions will only work asynchronously. So I made the following changes and this is where I'm stuck right now. The forms simply won't be submitted, nothing happens:
function deleteRecords() {
var arraryOfIDs;
arraryOfIDs = $('#table-style').find('[type="checkbox"]:checked').map(function(){
return $(this).closest('tr').find('td:nth-child(2)').text();
}).get();
var delFlagForm = document.createElement("form");
var action;
var formID;
var submitFormStr;
for (var i = 0; i < arr.length; i++) {
action = "/delete_flag/" + arr[i];
formID = 'form' + i;
delFlagForm.setAttribute("id", formID);
delFlagForm.setAttribute("method", "post");
delFlagForm.setAttribute("action", action);
if (i != 0) submitFormStr += ' #' + formID;
else submitFormStr = '#' + formID;
}
$('submitFormStr').submit();
return false;
}
The variable submitFormStr updated within the loop stores the id for each form created like the following: #form0 #form1so for this reason I don't understand why the piece of code $('submitFormStr').submit(); which is equivalent to $('#form0 #form1').submit(); is not working.
Is there anything I'm doing wrong?

populating a dynamic form with javascript

I am trying to get a forloop with input elements to run between a form and create a form dynamically with javascript
1: in scenario one , the form in the script is getting closed before the input elements populate.
2: in scenario two , when i put the for loop variable between the form ,the error that comes is undefined .
PLEASE HELP
SCENARIO ONE
<form>
No of Feilds <input type="text" id= "numberoffeilds">
<input type="button" value = "Create Feilds" onclick= "addfeilds1();">
</form>
<div id= "div4" style= "color:gray"></div>
<script>
function addfeilds1()
{
var totalfeilds = document.getElementById("numberoffeilds").value;
var i;
document.getElementById("div4").innerHTML += '<form action= "issue.html" method = "POST">';
for(i=0;i<totalfeilds;i++)
{
document.getElementById("div4").innerHTML += '<input type = "text">';
}
document.getElementById("div4").innerHTML += '<input type = "submit" value="submit" name="submit">';
}
</script>
SCENARIO TWO
<form>
No of Feilds <input type="text" id= "numberoffeilds">
<input type="button" value = "Create Feilds" onclick= "addfeilds2();">
</form>
<div id= "div4" style= "color:gray"></div>
<script>
function addfeilds2()
{
var totalfeilds = document.getElementById("numberoffeilds").value;
var i;
function forloop()
{
for(i=1 ;i<totalfeilds;i++)
{
document.getElementById("div4").innerHTML += '<input type = "text">';
}
}
var loopvar = forloop();
document.getElementById("div4").innerHTML += '<form action= "issue.html" method = "POST">'+
'<input type = "text">'+
loopvar + // it shows the loop as undefined
'<input type = "text">'+
'<input type = "text">'+
'<input type = "submit" value="submit" name="submit">';
}
</script>
You need to build the HTML elements in a string first and add them to the div as a last step.
Fixed scenario 1:
function addfeilds1()
{
var totalfeilds = document.getElementById("numberoffeilds").value;
var i;
var htmlString = "";
htmlString += '<form action= "issue.html" method = "POST">';
for(i=0;i<totalfeilds;i++)
{
htmlString += '<input type = "text">';
}
htmlString += '<input type = "submit" value="submit" name="submit">';
document.getElementById("div4").innerHTML = htmlString;
}
This prevents the form tag from being closed before it's populated with inputs.
Fixing scenario 2:
function forloop()
{
var htmlString = "";
for(i=1 ;i<totalfeilds;i++)
{
htmlString += '<input type = "text">';
}
return htmlString; // now forloop returns a string that can be added to the element. It no longers returns undefined.
}
Actually scenario 2 was fixing scenario 1, but you didn't include a return in your function. If you expect a function to create some text and concat that into a string you need your function to return a string.
Third example (advanced)
function addfeilds1()
{
var totalFields = parseInt(document.getElementById("numberoffeilds").value); //parse integer from value
if (isNaN(totalFields) || totalFields < 1)
{
//check if the input is valid, if not alert.
alert("Value is not a valid number or lower than 1.");
}
var container = document.getElementById("div4");
//create the form
var form = document.createElement("form");
form.setAttribute("action", "issue.html");
form.setAttribute("method", "POST");
for(var i=0; i<totalFields; ++i)
{
var node = document.createElement("input");
node.setAttribute("name", "field[]"); //this sends a array to the request page containing all input field values.
form.appendChild(node); //add the fields to the form.
}
//create the submit button.
var button = document.createElement("input");
button.setAttribute("type", "submit");
button.setAttribute("value", "submit");
button.setAttribute("name", "submit");
form.appendChild(button);
container.appendChild(form); //append the form to the div.
}

Div contents disappears about milliseconds of appearing

HTML:
<form id='pool_play'>
<?php
$PLAYERS = 8;
for ($i=1; $i <= $PLAYERS; $i++) {
print $i . ' <input type="text" class="initial_players" autofocus> <br/>';
}
?>
<br>
<button type="submit" class="random"> Randomize bracket</button>
</form>
<p class="debug"></p>
js:
$("#pool_play").submit(function(event) {
var participants = $('.initial_players').map(function() {
return $(this).val();
}).get();
for (var i = 0; i < participants.length; i++) {
$('p.debug').append(participants[i] + " ");
}
});
I'm basically trying to do is that when the form of #pool_play is submitted, print the contents of the input boxes in the .debug paragraph tag.
What happens is that it appears for a few milliseconds and then disappears. My guess is when the page is submitted, the old data(meaning the content of the .debug paragraph after it gets filled) gets thrown away. Tips?
You need to prevent the submit action or the page will just reload without your changes to the page.
$("#pool_play").submit(function(event) {
var participants = $('.initial_players').map(function() {
return $(this).val();
}).get();
for (var i = 0; i < participants.length; i++) {
$('p.debug').append(participants[i] + " ");
}
event.preventDefault();
return false;
});
It may be a better idea however to change your button to a button instead of a submit
<button type="button" class="random"> Randomize bracket</button>
You can prevent the page from submitting using event.preventDefault()
$("#pool_play").submit(function(event) {
var participants = $('.initial_players').map(function() {
return $(this).val();
}).get();
for (var i = 0; i < participants.length; i++) {
$('p.debug').append(participants[i] + " ");
}
event.preventDefault();//stops submit
});
Look at code. You catching submit event, getting data printing them... And then you go out from your function, so default action for submit event are executed by browser, because you don't stop it. Thats why you see this content only in miliseconds - browser is refreshing page.
You should use event.preventDefault() function to prevent browser from submiting form after execution your function.

Add a checkbox for the innerHTML in javascript

I have a page which contains a 10 items(formatted list).Here in this page I need to add check box for each item and add the item as the value to each check box.when the user click on the check box the selected value should be passed to a new page.Can anyone help me how to add a check box for the innerHTML in java script.
Code:
var newsletter=document.getElementById("block-system-main");
var districolumn=getElementsByClassName('view-id-_create_a_news_letter_',newsletter,'div');
if(districolumn!=null)
{
var newsletterall=newsletter.getElementsByTagName('li');
alert(newsletterall[0].innerHTML);
var all=newsletter.innerHTML;
newsletter.innerHTML="<input type='button' onclick='changeText()' value='Change Text'/>";
}
function changeText()
{
alert("dfgsdg");
}
I don't exactly understand what each part of your code is doing, but i'll try and give a general answer:
In your HTML, do something like this:
<form id="myForm" action="nextPage.com">
<div id="Boxes"></div>
</form>
Change the above names to wherever you want your checkboxes to be written.
And your function:
function changeText()
{
for(var i=0 ; i < newsletterall.length ; i++)
{
var inner = document.getElementById("Boxes").innerHTML;
var newBox = ('<input type="checkbox" name="item[]" value="' + newsletter[i] + '>' + newsletterall[i]);
document.getElementById("Boxes").innerHTML = inner + newBox;
}
document.getElementById("myForm").submit();
}
The last line of code submits the checkboxes automatically. If you don't want that, remove that line, and add a submit button to the form myForm.
​
$('ul​​​#list li').each(
function() {
var me = $(this),
val = me.html(),
ckb = $('<input type="checkbox" />');
ckb.click(function() {
var where=val;
window.location.href='http://google.com/?'+where;
});
me.html('');
me.append(ckb).append($('<span>'+val+'</span>'));
}
);​​​​

Categories