Angular 2 upload Image button is refreshing page - javascript

I have a html form with two buttons on it:-
[1] One button is used to upload an image file (.jpg)
[2] and the second one is to submit the form.
The problem is that the upload image button seems to be refreshing the page after the method for uploading the image has completed. Below is my html:-
<div class="m-b-18px">
<div class="col-m-12">
<a (click)="readRecipes()" class="btn btn-primary pull-right">
<span class="glyphicon glyphicon-plus"></span>Read Recipes
</a>
</div>
</div>
<div class="row">
<div class="col-md-12">
<form [formGroup]="create_recipe_form" (ngSubmit)="createRecipe()">
<table class="table table-hover table-responsive table-bordered">
<tr>
<td>
Name
</td>
<td>
<input name="name" formControlName="name" type="text" class="form-control" required />
<div *ngIf="create_recipe_form.get('name').touched && create_recipe_form.get('name').hasError('required')"
class="alert alert-danger">Name is required
</div>
</td>
</tr>
<tr>
<td>
Description
</td>
<td>
<textarea name="description" formControlName="description" class="form-control" required>
</textarea>
<div *ngIf="create_recipe_form.get('description').touched && create_recipe_form.get('description').hasError('required')"
class="alert alert-danger">
Description is required
</div>
</td>
</tr>
<tr>
<td>
Image
</td>
<td>
<input name="selectFile" id="selectFile" type="file" class="form-control btn btn-success" />
<button type="button" class="btn btn-primary" (click)="uploadImage($event)" value="Upload Image">Upload Image</button>
<input type='hidden' id='image_id' name='img_id' value="6" formControlName="image_id" />
</td>
</tr>
<tr>
<td></td>
<td>
<button class="btn btn-primary" type="submit" [disabled]="!create_recipe_form.valid">
<span class="glyphicon glyphicon-plus"></span> Create
</button>
</td>
</tr>
</table>
</form>
</div>
</div>
My code for the uploadImage method is below:-
uploadImage(e) {
let files = this.elem.nativeElement.querySelector('#selectFile').files;
let formData = new FormData();
let file = files[0];
formData.append('selectFile', file, file.name);
this._imageService.uploadImage(formData)
.subscribe(
image => {
console.log(image);
this.addImageIdToHtml(image)
e.preventDefault();
e.stopPropagation();
},
error => console.log(error)
);
}
As soon as the above method has finished running the page appears to refreshing causing my app to go back to the land page. This is not the behaviour I want. What I actually want is the form page to be retained until the Submit form button is pressed. Can anyone help me please?

Use div tags instead of form tag.
Change the button type as button.
<button type="button">Upload Image</button>
Modify the code as follows.
<div class="m-b-18px">
<div class="col-m-12">
<a (click)="readRecipes()" class="btn btn-primary pull-right">
<span class="glyphicon glyphicon-plus"></span>Read Recipes
</a>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div [formGroup]="create_recipe_form" (ngSubmit)="createRecipe()">
<table class="table table-hover table-responsive table-bordered">
<tr>
<td>
Name
</td>
<td>
<input name="name" formControlName="name" type="text" class="form-control" required />
<div *ngIf="create_recipe_form.get('name').touched && create_recipe_form.get('name').hasError('required')"
class="alert alert-danger">Name is required
</div>
</td>
</tr>
<tr>
<td>
Description
</td>
<td>
<textarea name="description" formControlName="description" class="form-control" required>
</textarea>
<div *ngIf="create_recipe_form.get('description').touched && create_recipe_form.get('description').hasError('required')"
class="alert alert-danger">
Description is required
</div>
</td>
</tr>
<tr>
<td>
Image
</td>
<td>
<input name="selectFile" id="selectFile" type="file" class="form-control btn btn-success" />
<button type="button" class="btn btn-primary" (click)="uploadImage($event)" value="Upload Image">Upload Image</button>
<input type='hidden' id='image_id' name='img_id' value="6" formControlName="image_id" />
</td>
</tr>
<tr>
<td></td>
<td>
<button class="btn btn-primary" type="button" [disabled]="!create_recipe_form.valid">
<span class="glyphicon glyphicon-plus"></span> Create
</button>
</td>
</tr>
</table>
</div>
</div>
</div>

You should not upload files on Angular folders like (Assets) , cuz it will recompile every time new file added to Angular environment and that will cause you the page refreshment you didn't want.

If you are using button tag inside the form tag, add type="button" inside the button tag.
<button type="button"></button>
This will work perfectly

Related

document.getElementById() on a value that is set through a Meteor template

So I've been trying to build a website using Meteor and am quite new with it. I am trying to have javascript that will make use of the values on the page and then create a download from those values. These values differ depending on which page the user is on as the meteor template is loaded with specific information. The way I would think is would work is:
var thing = document.getElementById("tcpout").value;
but when I test this I get "undefined". Now if I don't do .value then do something like
console.log(document.getElementById("tcpout"));
the output in the console is this:
<td id="tcpout"> 50443</td>
where 50443 is the value that I want. Yet I can't seem to figure out how to get that into the javascript. I am using meteor and have tried a few things through meteor's project .js file, but can't seem to figure out how to incorporate dynamic fields into javascript. Essentially I just want to figure out the easiest and best way to work with the mongodb data on the client-side with javascript. Here is the template and the meteor js file.
<template name="profile">
{{#each iotdevice}}
<div class="container" style="margin-top:10px">
<div class="starter-template" align="center">
<h1>{{model}} {{manufacturer}} {{type}}</h1>
<p class="lead"></p>
<table class="table table-bordered">
<thead>
<tr>
<th>Ports</th>
<th>Outgoing</th>
<th>Incoming</th>
</tr>
</thead>
<tbody>
<tr>
<td>TCP</td>
<td id="tcpout"> {{tcpout}}</td>
<td id="tcpin"> {{tcpin}}</td>
</tr>
<tr>
<td>UDP</td>
<td id="udpout"> {{udpout}}</td>
<td id="udpin"> {{udpin}}</td>
</tr>
</tbody>
</table>
<table class="table table-bordered">
<thead>
<tr>
<th colspan="2">Domains</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{domains}}</td>
</tr>
</tbody>
</table>
</div>
<h4 align="center">Select Firewall</h4>
<div align="center">
<button style="margin-bottom:15px" type="button" class="btn btn-outline-danger" onclick="vyosformshow()">
VyOS
</button>
<button style="margin-bottom:15px" type="button" class="btn btn-outline-danger"
onclick="download('test.sh','hello\nworld')">IPTables
</button>
<button style="margin-bottom:15px" type="button" class="btn btn-outline-danger">FreePBX</button>
<button style="margin-bottom:15px" type="button" class="btn btn-outline-danger" onclick="dthings()">IPFire
</button>
<button style="margin-bottom:15px" type="button" class="btn btn-outline-danger">IPCop</button>
</div>
<div id="vyosform" style="display:none">
<form>
<div class="form-row">
<div class="form-group col-md-6">
<label for="exampleInputEmail1">firewall in name</label>
<input class="form-control" id="firein" placeholder="">
</div>
<div class="form-group col-md-6">
<label for="exampleInputPassword1">firewall out name</label>
<input class="form-control" type="text" id="fireout" placeholder="">
</div>
<div class="form-group col-md-6">
<label for="exampleInputPassword1">rule number</label>
<input class="form-control" id="rulenum" placeholder="">
</div>
<div class="form-group col-md-6">
<label for="exampleInputPassword1">device IP address</label>
<input class="form-control" id="ip" placeholder="">
</div>
<div align="center">
<button id="dostuff" class="btn btn-primary" style="margin-bottom:30px">Submit</button>
</div>
</div>
</form>
</div>
</div>
{{/each}}
</template>
JS
if (Meteor.isClient) {
//this code only runs on the client
var directory = Iron.Location.get().path;
var start = directory.lastIndexOf("/");
var stop = directory.search(".html");
var parseddir = directory.slice(start + 1, stop);
var search = directory.slice(start + 1);
var regexsearch = new RegExp(["^", search, "$"].join(""), "i");
console.log(search);
Template.iotprofiler.helpers({
'device': function () {
return DeviceList.find();
}
});
Template.profile.helpers({
'iotdevice': function () {
return DeviceList.find({model: parseddir});
}
});
Template.search.helpers({
'results': function () {
return DeviceList.find({$or: [{model: regexsearch}, {manufacturer: regexsearch}, {type: z}]});
}
});
}

Find Value of textarea from closest row of table

I have a button Update in One td I want to fetch value of both textarea of td from same tr.
There are lots of tr so I have to use closest() method to find element. I have tried to find element but it's not working.
HTML :-
<tr>
<td>
<div class="agenda-date">
<div class="dayofmonth color_font_date">2017-05-31</div>
<div class="dayofweek">
Wednesday
</div>
</div>
</td>
<td>
<div class="row margin_two_planner">
<button type="button" class="btn btn-sm btn-primary">AM </button>
<a data-toggle="modal" href="#add_apt_status" class=""><input type="number" value="3" name="" class="number_planner"></a>
<label class="control-label"> 6 </label>
</div>
<div class="row margin_two_planner">
<button type="button" class="btn btn-sm btn-primary">PM </button>
<a data-toggle="modal" href="#add_apt_status" class=""><input type="number" value="4" name="" class="number_planner"></a>
<label class="control-label"> 2 </label>
</div>
</td>
<td style="width: 20%;">
<textarea id="" class="form-control initial_cap appointment_note" required="required" rows="3" name="appointment_note" cols="50" aria-required="true" disabled=""> APT -1 </textarea>
</td>
<td style="width: 20%;">
<textarea id="" class="form-control initial_cap holiday_note" required="required" rows="3" name="holiday_note" cols="50" aria-required="true" disabled=""> Holiday - 1 </textarea>
</td>
<td>
<div class="text-right">
<button type="button" id="" class="btn btn-primary appointment_edit_button">Edit </button>
<button type="button" id="" onclick="planner_note_edit(1)" class="btn btn-md btn-primary appointment_update_button" style="display:none"> Update </button>
<button type="button" id="" class="btn btn-md btn-cancel appointment_cancel_button" style="display:none">Cancel </button>
</div>
</td>
</tr>
Jquery :-
function planner_note_edit(planner_note_id)
{
appointment_note = $(this).closest('td').find(".holiday_note").val();
alert(appointment_note);
}
But I'm not able to fetch value of textarea from closest td.
You should get the textarea from current row.
So, please use .closest('tr')
appointment_note = $(this).closest('tr').find(".holiday_note").val();
Also, you have to pass the clicked button object. this in your function is a reference to the window object.
function planner_note_edit(planner_note_id,event)
{
appointment_note = $(event.target).closest('td').find(".holiday_note").val();
alert(appointment_note);
}
HTML
<button type="button" id="" onclick="planner_note_edit(1,event)" class="btn btn-md btn-primary appointment_update_button" style="display:none"> Update </button>

how to submit a non-form element using angular2

<tbody>
<tr *ngFor="let gasType of staffConfig.gasTypes">
<td class="col-md-3">
<input class="gas-name form-control" type="text" [(ngModel)]="gasType.name" name="gasName"
[disabled]="!isStaffEnabled">
</td>
</tr>
</tbody>
</table>
</div>
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">
<h3 class="panel-title">
<img src="/assets/brand-icon.png">
<span>Brands</span>
</h3>
</div>
<!-- Table -->
<table class="table">
<tbody>
<tr *ngFor="let brand of staffConfig.brands;let i = index;">
<td>
<input class="form-control" type="text" [(ngModel)]="brand.name" name="brands"
[disabled]="!isStaffEnabled">
</td>
</tr>
</tbody>
</table>
</div>
</tab>
<button id="saveChangesBtn" type="button" class="btn btn-primary" disabled>Save Changes</button>
I want to bind the "save" button to a method in the component. So I changed:
<button id="saveChangesBtn" type="button" (ngSubmit)="registerUser(registrationForm.value) class="btn btn-primary" disabled>Save Changes</button>
but then, if that's not a <form> how do I bind the fields to a model?
In other words how can I send these fields to the server?
I have to read them from the component and then assemble an object.
But how can I access the non-form model like registrationForm.value?
If you are using ngModel outside of the <form> you must specify [ngModelOptions]={standalone:true}.
Template
<div class="not-a-form">
<input type="text" [(ngModel)]="model.foo" [ngModelOptions]="{standalone: true}" />
<input type="text" [(ngModel)]="model.bar" [ngModelOptions]="{standalone: true}" />
<button type="button" (click)="save(model)"> Send </button>
</div>
Component
#Component({
selector: 'selector',
...
})
class SomeComponent {
model: any = {};
save(data) {
console.log(data);
}
}

Not able to take data from table and set to bootstrap modal

I am working on a piece of code and since I dont have too much experience with jquery or javascript I need your help. I want to take the data from the row when button EditBtn is clicked and set those values to modal. I tried the code below but It was not working.
Below is my code
Table :
<table id="example" class="table table-bordered table-hover">
<thead>
<tr>
<th>Ödeme Türü</th>
<th>Ödeme Başlığı</th>
<th>İçerik</th>
<th>Son Ödeme Tarihi</th>
<th>Tutarı</th>
<th>Ödeme Durumu</th>
<th>Düzenle</th>
</tr>
</thead>
<tbody>
#foreach (OdemeList item in Model)
{
<tr id="#item.Odeme.OdemeID">
<td>#item.Odeme.OdemeType</td>
<td>#item.Odeme.OdemeTitle</td>
<td>#item.Odeme.OdemeContent</td>
<td>#item.Odeme.SonOdemeTarih</td>
<td>#item.Odeme.OdemeTutar</td>
#if (#item.KullaniciOdeme.isPay == true)
{
<td>Odendi</td>
}
else
{
<td>Odenmedi</td>
<td>
<form>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_6pRNASCoBOKtIshFeQd4XMUh"
data-amount="#item.Odeme.OdemeTutar"
data-name="#item.Odeme.OdemeTitle"
data-image="/Content/LoginCssJs/pay.png"
data-locale="auto">
</script>
</form>
</td>
#*<td>
<a data-toggle="modal" data-target=".bootstrapmodal3"><button class="btn btn-success">Öde</button></a>
</td>*#
}
<td>
<a data-toggle="modal" id="EditBtn" class="btn edit" data-target=".bootstrapmodal"><img src="#Url.Content("~/Content/Icons/edit.png")" alt="Düzenle" /></a>
</td>
<td>
<a data-toggle="modal" data-target=".bootstrapmodal2"><img src="#Url.Content("~/Content/Icons/Delete.png")" alt="Sil" /></a>
</td>
</tr>
}
</tbody>
</table>
My modal:
<div class="modal fade bootstrapmodal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button data-dismiss="modal" class="close"><span>×</span></button>
<div class="modal-title">
<h3>Ödeme Düzenle</h3>
</div>
</div>
<div class="modal-body">
<form>
<label>Ödeme Türü</label>
<select class="form-control" id="OdemeTuru">
<option>Aidat</option>
<option>Isınma</option>
<option>Bina Gideri</option>
</select><br />
<div class="form-group">
<label for="odemebasligi">Ödeme Başlığı</label>
<input type="text" class="form-control" id="odemebasligi" placeholder="OdemeTitle">
</div>
<div class="form-group">
<label for="comment">Ödeme içeriği</label>
<textarea class="form-control" rows="5" id="comment" placeholder="-OdemeContent"></textarea>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Tutar</label>
<div class="input-group">
<div class="input-group-addon">TL</div>
<input type="text" class="form-control" id="exampleInputAmount" placeholder="OdemeTutar">
<div class="input-group-addon">.00</div>
</div>
</div>
<div class="form-group">
<label for="odemetarihi">Son Ödeme Tarihi</label>
<input type="text" class="form-control" id="odemetarihi" placeholder="SonOdemeTarih">
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary">Kaydet</button>
<button class="btn btn-danger" data-dismiss="modal"> Vazgeç</button>
</div>
</div>
</div>
</div>
Script:
<script>
$('a.edit').on('click', function() {
var myModal = $('.bootstrapmodal');
//// now get the values from the table
//var OdemeTuru = $(this).closest('tr').find('td.OdemeType').html();
var OdemeBaslik = $(this).closest('tr').find('td.OdemeTitle').html();
var OdemeIcerik = $(this).closest('tr').find('td.OdemeContent').html();
var OdemeTutar = $(this).closest('tr').find('td.SonOdemeTarih').html();
var SonOdemeTarihi = $(this).closest('tr').find('td.OdemeTutar').html();
//// and set them in the modal:
//$('#', myModal).val(OdemeTuru);
$('#odemebasligi', myModal).val(OdemeBaslik);
$('#comment', myModal).val(OdemeIcerik);
$('#exampleInputAmount', myModal).val(OdemeTutar);
$('#odemetarihi', myModal).val(SonOdemeTarihi);
// and finally show the modal
myModal.modal({ show: true });
return false;
});
</script>
In script you are targeting <td> class .find('td.OdemeTitle') and in table there are no class defined <td>#item.Odeme.OdemeTitle</td> what you only need is define class which you are targeting e.g
For
var OdemeBaslik = $(this).closest('tr').find('td.OdemeTitle').html();
HTML
<td class="OdemeTitle">#item.Odeme.OdemeTitle</td>
follow above example and set all <td> classes and you will be all set.
minimal fiddle example

form submit don't recognize dynamically added input (using JavaScript)

I have html code with form:
<tr>
<form action="/some_action/" method="POST" id="send_form" class="test-form">
{% csrf_token %}
</div>
<button type="button" class="btn-add btn btn-info" aria-label="Left Align">
add <span class="glyphicon glyphicon-plus-sign"/>
</button>
</td>
<td>
<div class="courier-date-from-data">
</div>
</td>
<td>
<div class="courier-date-to-data">
</div>
</td>
<td>
<div class="start-km-data">
</div>
</td>
<td>
<div class="end-km-data">
</div>
</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-options btn-default dropdown-toggle" data-toggle="dropdown"></button>
<ul class="dropdown-menu" role="menu">
<li type="submit" class="btn-options-save"><a onclick="">save</a></li>
<li class="btn-options-cancel"><a onclick="">cancel</a></li>
</ul>
</div>
</td>
</form>
and input templates on the bottom:
<input type="number" class="form-control start-km-template" style="display: none;" name="" id="">
<input type="number" class="form-control end-km-template" style="display: none;" name="" id="">
JavaScript:
var selector2 = "start-km-0";
$( ".start-km-template" )
.clone()
.removeClass("start-km-template")
.css("display","block")
.addClass(selector2)
.attr("id", selector2)
.attr("name", selector2)
.appendTo(".start-km-data");
When I want to submit request (using just input with type="submit"), form don't recognize new input field in form tag.
How to fix this ?

Categories

Resources