How do I retrieve information stored in a js file? I assume I am labelling my node elements in HTML incorrectly
I'm hoping to gain a better understanding of how to retrieve a function node from localStorage
Below are the key factors I am trying to get using getElementById into local storage from post HTML.
This is not everything in my listing.html document, I have excluded everything but what I think are essential elements
<div class="listing">
<div class="container-form">
<div class="mySlides fade">
<div class="numbertext">1 / 3</div>
<img class="img" value(src)="1" id="img" src="images/4.JPG" alt="img1">
</div>
<div class="infoBox">
<h5 post="weight" id="weight" value="7.00">7.00 : Under - 16 oz</h5>
</div>
<div class="column-bottom">
<div class="add-button">
<div class="add-button" method="post">
<p><input type="submit" onclick="addListing()" class="btn"></input></p>
<div class="buy-button">
<span class="price" post="price" id="price" value="60">$60</span>
<button type="button" class="btn" onclick="window.location.href='cart.html'" onclick="addListing()"
;>BuyMe</button>
</div>
</div>
</div>
</div>
</div>
</div>
I am trying to use the function below to store each element from the post HTML
function addlisting() {
let listing = ['listings'];
if (localStorage.getItem('listings')) {
listing = JSON.stringify(localStorage.getItem('listings'));
alert("added!");
}
listing.push({ 'listingId': listingId + 1, image: '<imageLink>' });
listingsId = listingsId + 1;
var listingsName = document.getElementById('name').innerHTML;
var listingsPrice = document.getElementById('price').getAttribute('data- value');
var listingsImage = document.getElementById("img").src;
var listingsWeight = document.getElementById('weight').getAttribute('data- value');
value = parseFloat(listingsPrice, listingsWeight).toFixed(2);
localStorage.getItem('name', 'price', 'img', 'weight', JSON.stringify(listingsName, listingPrice, listingsImage, listingsWeight));
}
here is the $(document).ready(function(){ function I'm hoping to implement into my code, I got this from another Stack Overflow page as it was the most fitting however I am yet to understand each component.
$(document).ready(function () {
$('#Btn').load(function () {
let listings = [];
if (localStorage.getItem('listings')) {
listings = JSON.parse(localStorage.setItem('listings'));
}
listings.push({ 'listingId': 1, image: '<imageLink>' });
});
});
my question again is how do I then execute this function using onload Onto a separate HTML, called cart.html. I did not display my cart.html file because there is nothing pertaining to this question on it. And furthermore how to go about styling Onload events that retrieve information from localStorage.
P.S.
There is an alert function within my first .js excerpt addListing(), that does not fire when clicked. probably a sign of bad programming. I've just never found a straightforward answer
I'm trying to insert modal window html code dynamically upon user click on which item otherwise i load all of the items' modal window code in the html. I also have some inputs in the modal window loading from Flask/Sql and i want to let user update any of them so i need to send data back to python on submit button clicked. But right now because of i have too many modal windows (even though they have separate ids) i couldn't find a way to achieve this
Here is my code:
routes.py
#app.route('/viewApart', methods=['GET', 'POST'])
def viewApart():
apts = []
getApts = db.engine.execute("SELECT * FROM apartments")
for a in getApts:
apts.append((a))
rooms = []
getRooms = db.engine.execute("SELECT * FROM rooms")
for r in getRooms:
rooms.append((r))
return render_template('apartments.html', title=_('Apartments'), apts=apts, rooms=rooms)
apartments.html
....
<section class="container">
<div class="row">
.. below some gallery code to show individual items from apts ..
{% for apt in apts %}
<div class="col-md-3">
<a href="javascript:void(0);" class="widget__v2 apt-widget rounded-corners box-shadow__v1 white" data-anchor="modalwindow" data-target="edit-apartment{{ apt[0] }}" id="apt{{ apt[0] }}">
<div class="widget-header">
<figure class="image h-180">
<img src="{{url_for('static', filename='_assets/img/apt/{{ apt[0] }}.jpg')}}" alt="" class="image__scaledown">
</figure>
.. below model window ..
<div id="edit-apartment{{ apt[0] }}" class="modal large">
<div class="modal-wrapper">
<div class="modal-inner">
<div class="modal-header">
<h3 class="title">{{ _('Edit Apartment') }}</h3>
</div>
<div class="modal-content">
<div class="row medium-gutter">
<div class="col-md-6">
<div class="row medium-gutter">
<div class="col-md-8">
<div class="form-group">
<div class="form-group-title clearfix">
<label for="apt_display_name">{{ _('Display Name') }}</label>
<div class="lh-24 text__default-grey pull-right" data-tooltip="true" data-tooltip-direction="up" data-multiline="true"
data-content="..">
<i class="icofont-question-circle"></i>
</div>
</div>
<input id="apt_display_name" type="text" class="form-control" value="{{ apt[1] }}">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="apt_number">{{ _('Apt. Number') }}</label>
<input id="apt_number" type="text" class="form-control" value="{{ apt[2] }}">
</div>
</div>
</div>
.. and so on...
.. and submit button ..
{{ _('Save Changes') }}
</div>
</section>
Right now even with multiple model windows, i can display the current data in modal window, so what i want to achieve this upon clicking on btnSubmit button i need to send all input values back to python so i can update my sql or insert new one. Please let me know if more code is needed..
Thanks
If I am understanding your question correctly - a skeleton version of your page would be something like this
<!DOCTYPE html>
<html>
<body>
<p>INTRODUCING MY AWESOME SITE AND 2 DIVS YOU CAN CLICK</p>
<div id="apt_1_modal">
<input id="apt_1_text"></input>
<a onclick="myFunction(event)">Submit</a>
</div>
<div id="apt_2_modal">
<input id="apt_2_text"></input>
<a onclick="myFunction(event)">Submit</a>
</div>
</body>
</html>
You will need JavaScript to handle the user interaction - the script would look something like this. You can either append this script directly to your render_template output or you can append it as a file.
The script will do 2 things - first capture what your user is inputting and second, send that data over to flask
<script>
function myFunction(e) {
//FIRST WE CAPTURE THE VALUE THAT THE USER INPUTS
let userInput = {toSend: e.currentTarget.previousElementSibling.value}
//THEN WE SEND IT TO THE FLASK BACKEND USING AJAX (Fetch API)
fetch("/api/path/to/flask/route", {
method: 'POST',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userInput)
}
</script>
Now you need a function that can handle the userInput data
Backend
from flask import Flask, request #import main Flask class and request object
#app.route('/api/path/to/flask/route', methods=['POST'])
def capture_userinput():
req_data = request.get_json()
recd_data = req_data['toSend']
your_code_to_push_data_to_db(recd_data) #Depends on your ORM/DB
I hope I have given you an idea of how to go about - You will most certainly have to change the way to capture userInput, tweak the fetch call and send/capture additional data in your flask api.
So I wanna print an object to my page and I have no idea how to write the code in JS so that on my page it prints multiple divs for each object.
What I wanna do is insert this
<div class="cv-block">
<div id="parent_div_1">
obiect.firstn
obiect.lastn
</div>
<div id="parent_div_2">
obiect.date
</div>
obiect.message
</div>
into this java script function
function afisare (lista) {
var randuri = "";
lista.forEach(function (obiect) {
randuri += ;
});
$("#obiect").html(randuri);}
Thank you in advance for your time.
best way to do this is using template literal which is supported by ES6.
if you want to use it in older browser you should use babel.
$("#obiect").html(`<div class="cv-block">
<div id="parent_div_1">
${obiect.firstn}
${obiect.lastn}
</div>
<div id="parent_div_2">
${obiect.date}
</div>
${obiect.message}
</div>`)
also there is ES5 code for it.
$("#object").html("<div class=\"cv-block\">\n <div id=\"parent_div_1\">\n obiect.firstn\n obiect.lastn\n </div>\n\n <div id=\"parent_div_2\">\n obiect.date\n </div>\n\n obiect.message\n\n </div>");
I would like a directive that dynamically knows if I'm following the user in my App.
I have a resource to get the currentUser
this.following = function () {
var defer = $q.defer();
var user = $cookies.getObject('currentUser');
UserResource.get({id: user.id}).$promise.then(
function (data) {
defer.resolve(data.following);
});
return defer.promise;
};
This is in one of my services. It returns all users that I'm following.
When instantiating my controller I fetch the users I follow within my app:
UserService.following().then(
function (data) {
$scope.following = data;
});
I would like to move that into a directive so that I can easily reuse it somewhere else in my app.
This is the HTML I am using right now (and it's not really beautiful) :
<div class="item" ng-repeat="user in users">
<div class="right floated content">
<div ng-show="isFollowing(user)" class="ui animated flip button" tabindex="0"
ng-click='unFollow(user)'>
<div class='visible content'>
Following
</div>
<div class="hidden content">
Unfollow
</div>
</div>
<div ng-hide="isFollowing(user)" ng-click="follow(user)" class="ui button">Follow</div>
</div>
</div>
But instead something like :
<div class="item" ng-repeat="user in users">
<um-follow-button um-user="user"></um-follow-button>
</div>
then depending if I'm following the user or not then render one of the two options.
I don't know if I will have to use a controller in my directive.
I have looked at : https://gist.github.com/jhdavids8/6265398
But it looks like a mess.
Hello I am new to angular js , I need some help that i have one edit form in angular js when user click on edit it redirect to edit form but i am getting some issues that my json result look like :
[{"0":"3",
"1":"The only people for me are the mad ones",
"2":"“The only people for me are the mad ones, the ones who are mad to live, mad to talk, mad to be saved, desirous of everything at the same time, the ones who never yawn or say a commonplace thing, but burn, burn, burn like fabulous yellow roman candles exploding like spiders across the stars.”",
"3":"2015-05-08 13:01:58",
"id":"3","title":"The only people for me are the mad ones",
"description":"“The only people for me are the mad ones, the ones who are mad to live, mad to talk, mad to be saved, desirous of everything at the same time, the ones who never yawn or say a commonplace thing, but burn, burn, burn like fabulous yellow roman candles exploding like spiders across the stars.”",
"created_on":"2015-05-08 13:01:58"
}]
I want to know how to print my title , description in view.
Here is my controller file: where i get the data from database:
var myApp = angular.module("blogapp",[]);
myApp.config(['$routeProvider',function($routeProvider){
$routeProvider
.when('/home',{
templateUrl:'home.html',
controller:'blogcontroller'
})
.when('/list',{
templateUrl:'list.html',
controller:'blogcontroller'
})
.when('/add',{
templateUrl:'add.html',
controller:'addcontroller'
})
.when('/edit/:Blogid',{
templateUrl:'edit.html',
controller:'editcontroller'
})
.otherwise({
redirectTo:'/home'
});
}]);
myApp.controller('blogcontroller',function ($scope,$http){
$http({method: 'GET' , url: 'getallblog.php'}).success(function(data){
$scope.allblog = data;
console.log(data);
});
// DELETE blog HERE
$scope.removeRow= function(id){
$http.post("removeblog.php",{'id' : id}).success(function(data,status,headers,config){
window.location='index.html';
console.log("Deleted Successfully");
});
};
// delete blog code ends here
});
myApp.controller('addcontroller',function ($scope,$http){
/// New Post Here
$scope.new_post =function(){
$http.post("addblog.php" ,{'title' : $scope.title ,'description' : $scope.description }).success(function(data,status,headers,config){
window.location='index.html';
console.log("inserted Successfully");
});
};
// New Post ends Here
});
myApp.controller('editcontroller',function ($scope,$http,$routeParams){
$scope.Blogid = $routeParams.Blogid;
$http.post("getblog.php",{'id' : $scope.Blogid}).success(function(data){
$scope.editit = data; /// here i get the resuly want to pass it t view
console.log(data);
});
});
My edit html form : edit.html
<!-- Page Content -->
<div class="container">
<div class="row">
<!-- Blog Entries Column -->
<div class="col-md-6">
<h1 class="page-header">
Angular Blog
</h1>
<div >
<form class="form-signin">
<h2 class="form-signin-heading">Modify // want to print title here </h2>
<div class="row">
<div class="col-md-12">
<label for="posttitle" class="sr-only">Email address</label>
<input type="text" id="posttitle" class="form-control" ng-model="{{title}}" required="" value=""><br>
<span>Title : // want to print title here</span>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<label for="postdetails" class="sr-only">Password</label>
<textarea id="postdetails" class="form-control" ng-model="description" required=""></textarea>
<br>
<span>Blog Description: // want to print description here</span>
</div>
</div>
<br>
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<button class="btn btn-lg btn-primary btn-block" type="button" ng-click="edit_post()" name="editblog">Modify Now</button>
</div>
<div class="col-md-3"></div>
</div>
</form>
</div>
</div>
<div class="col-md-2"></div>
<!-- Blog Sidebar Widgets Column -->
<div ng-include="'includes/sidebar.html'">
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container -->
to print your title, you first need to replace this line in JS:
$scope.allblog = data;
with
$scope.allblog = data[0];
Now, you can write in HTML the following statement:
{{allblog.title}}
Something like this:
<span>Blog Description: {{allblog.description}}</span>
Or
<span>Blog Description: <span ng-bind-html ="allblog.description"></span></span>
if your allblog is an array use allblog[0]