Trigger Jquery on an element immediately after it gets populated - javascript

I have a text area which gets populated after click of a button .
<textarea rows="4" cols="50" id="4321">
{{ data.classi}}
</textarea>
Now i want something to happen after it gets populated . I have tried onchange and a few other options but they only work after the textarea is populated an we change its content .
I want it to happen right after the textarea is populated with json from back-end . How can this be done
$('#4321').on('change', function() {
alert( this.value ); // or $(this).val()
});
This doesn't work
I am pasting the entire code here in case it helps
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="js/main.js"></script>
<script src="jquery.json-view.js"></script>
<link href="jquery.json-view.css" rel="stylesheet"></link>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body ng-controller="DebugController">
<div>
<input type="text" ng-model="query" placeholder="Search Query">
<input type="text" ng-model="pog" placeholder="Enter No of POGs">
<button ng-click="onSearch()" class="button" id ="abcd">Search</button>
</div>
<textarea rows="4" cols="50" id="abc">
{{ data.classi}}
</textarea>
<div>
<h4>Parameters</h4>
<table>
<tr ng-repeat="x in data.p ">
<td>{{ x[0] }}</td>
<td>{{ x[1] }}</td>
</tr>
</table>
</div>
<div>
<h4>Classifier Scores</h4>
<table>
<tr>
<th>Category URL</th>
<th>Additive Boost</th>
</tr>
<tr ng-repeat="x in data.classifier">
<td>{{ x[0] }}</td>
<td>{{ x[1] }}</td>
</tr>
</table>
</div>
<div>
<h4>Product Groups (POGs)</h4>
<table>
<tr>
<th>Id</th>
<th>Details</th>
<th>Score</th>
<th>HPSA Score</th>
<th>BF Score</th>
<th>Word Match</th>
<th>Classifier Score</th>
<th>QUL Score</th>
</tr>
<tr ng-repeat="x in data.items | limitTo: limit " >
<td><a href="{{ x.get }}">{{ x.id }}</td>
<td>
<p><b>{{ x.name[0] }}</b></p>
<p><u>Brand</u>: {{ x.Brand }}; <u>Category URL</u>: {{ x.mlnURL }};<u>Price</u>: Rs {{x.Price}} </p>
</td>
<td>
<p><b>{{ x.score }}</b></p>
Classifier Score: {{ x.cscore }} <br>
Document Score: {{ x.sscore }} </p>
</td>
<td>
<p><b> {{ x.hpsaScore_default }} </b></p>
</td>
<td>
<p><b> {{ x.bf_value }} </b></p>
</td>
<td>
</td>
<td>
<p> <b> {{ x.cscore }} </b></p>
</td>
<td>
</td>
</tr>
</table>
</div>
<div>
<h4>Solr Query</h4>
<p>{{ data.query }}</p>
</div>
<script>
var pog;
$(function() {
$('#abc').on('input', function() {
alert("hi");
});
});
</script>
</body>
</html>
The controller of the page
var app = angular.module('myApp', []);
app.controller('DebugController', function($scope, $http) {
$scope.onSearch = function () {
$scope.data = {}
number = $scope.pog
$scope.limit = number
$http.get('/search?q=' + $scope.query)
.then(function(response) {
console.log(response)
params = []
urls = []
for (p in response.data.params) {
params.push([p, response.data.params[p]])
}
for (i in response.data.bf_value) {
for(j in response.data.bf_value[i]) {
}
}
for( t in response.data.items ) {
p =""
for ( s in response.data.bf_value ) {
p+=response.data.bf_value[s][t]
}
response.data.items[t].bf_value = p
}
console.log(response.data.bf_value);
$scope.data = response.data
$scope.data.classi = response.data.classify
$scope.data.p = params
$scope.data.u = urls
});
}
});

Use the input event. (mdn)
$('#hello').on('input', function() {
console.log($(this)[0].value) // console logs the value of the textarea
});

$("#4321").change(function(){
alert("The text has been changed.");
});
This should work.

Related

How to select the closest element with contains selector jquery

I want to replace the "{{my_name}}" and "{{my_email}}" with a string, but the program is not working, what should i do?
Thanks.
$(".notes *:contains('{{')").text(function() {
var rawkey = $(this).text().match(/{{(.*?)}}/i)[0]; // Output (console.log) : {{my_name}} or {{my_email}}
var key = $(this).text().match(/{{(.*?)}}/i)[1]; // Output (console.log) : my_name or my_email
if (key.indexOf('name') > -1) {
$(this).text($(this).text().replace(rawkey, "Tony"));
} else if (key.indexOf('email') > -1) {
$(this).text($(this).text().replace(rawkey, "tonyhawk#gmail.com"));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="notes">
<h4>{{my_name}}</h4>
<table>
<tr>
<td>
<p>{{my_name}}, {{my_email}}</p>
</td>
</tr>
</table>
</div>
Set the result after replacing back to the element's textContent:
$(".notes *:contains('{{')").text(function() {
var rawkey = $(this).text().match(/{{(.*?)}}/i)[0];
var key = $(this).text().match(/{{(.*?)}}/i)[1];
if (key.indexOf('name') > -1) {
$(this).text($(this).text().replace(rawkey, "Tony"));
} else if (key.indexOf('email') > -1) {
$(this).text($(this).text().replace(rawkey, "tonyhawk#gmail.com"));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="notes">
<h4>{{my_name}}</h4>
<table>
<tr>
<td>
<p>{{my_email}}</p>
</td>
</tr>
</table>
</div>
You can do like this.
var $content=$('.notes').html();
var finalContent=$content.replaceAll("my_name","Tony").replaceAll("my_email","tonyhawk#gmail.com").replaceAll("{{","").replaceAll("}}","");
$(".notes").html(finalContent);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="notes">
<h4>{{my_name}}</h4>
<table>
<tr>
<td>
<p>{{my_name}},{{my_email}}</p>
</td>
</tr>
</table>
</div>

Add more button in JavaScript not working

I am trying to add rows in my django template using JavaScript but it is not working like it's supposed to:
HTML
<html>
<head>
<title>gffdfdf</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/static/jquery.formset.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form id="myForm" action="" method="post" class="">
{% csrf_token %}
<h2> Team</h2>
{% for field in form %}
{{ field.errors }}
{{ field.label_tag }} : {{ field }}
{% endfor %}
{{ form.player.management_form }}
<h3> Product Instance(s)</h3>
<table id="table-product" class="table">
<thead>
<tr>
<th>player name</th>
<th>highest score</th>
<th>age</th>
</tr>
</thead>
{% for player in form.player %}
<tbody class="player-instances">
<tr>
<td>{{ player.pname }}</td>
<td>{{ player.hscore }}</td>
<td>{{ player.age }}</td>
<td> <input id="input_add" type="button" name="add" value=" Add More " class="tr_clone_add btn data_input"> </td>
</tr>
</tbody>
{% endfor %}
</table>
<button type="submit" class="btn btn-primary">save</button>
</form>
</div>
<script>
var i = 1;
$("#input_add").click(function() {
$("tbody tr:first").clone().find(".data_input").each(function() {
if ($(this).attr('class')== 'tr_clone_add btn data_input'){
$(this).attr({
'id': function(_, id) { return "remove_button" },
'name': function(_, name) { return "name_remove" +i },
'value': 'Remove'
}).on("click", function(){
var a = $(this).parent();
var b= a.parent();
i=i-1
$('#id_form-TOTAL_FORMS').val(i);
b.remove();
$('.player-instances tr').each(function(index, value){
$(this).find('.data_input').each(function(){
$(this).attr({
'id': function (_, id) {
var idData= id;
var splitV= String(idData).split('-');
var fData= splitV[0];
var tData= splitV[2];
return fData+ "-" +index + "-" + tData
},
'name': function (_, name) {
var nameData= name;
var splitV= String(nameData).split('-');
var fData= splitV[0];
var tData= splitV[2];
return fData+ "-" +index + "-" + tData
}
});
})
})
})
}
else{
$(this).attr({
'id': function (_, id) {
var idData= id;
var splitV= String(idData).split('-');
var fData= splitV[0];
var tData= splitV[2];
return fData+ "-" +i + "-" + tData
},
'name': function (_, name) {
var nameData= name;
var splitV= String(nameData).split('-');
var fData= splitV[0];
var tData= splitV[2];
return fData+ "-" +i + "-" + tData
}
});
}
}).end().appendTo("tbody");
$('#id_form-TOTAL_FORMS').val(1+i);
i++;
});
</script>
</body>
</html>
the above code creates a form with three fields i.e player name, highest score and age with a add more button
but according to this it should create the following :
<!-- First row of the table -->
<tr>
<td><input type="text" name="form-0-name" id="id_form-0-name" /></td>
<td>
<input type="number" name="form-0-quantity" id="id_form-0-quantity" />
</td>
<td><input type="number" name="form-0-price" id="id_form-0-price" /></td>
<td>
<input
id="input_add"
type="button"
name="add"
value=" Add More "
class="tr_clone_add btn data_input"
/>
</td>
</tr>
<!-- Second row of the table -->
<tr>
<td><input type="text" name="form-1-name" id="id_form-1-name" /></td>
<td>
<input type="number" name="form-1-quantity" id="id_form-1-quantity" />
</td>
<td><input type="number" name="form-1-price" id="id_form-1-price" /></td>
<td>
<input
id="remove_button"
type="button"
name="remove_button1"
value=" Remove "
class="tr_clone_add btn data_input"
/>
</td>
</tr>
<!-- more inline formset are going to rendered here -->
But when I create another row in the form it creates another row with same name and id.
See:
<tbody class="player-instances">
<tr>
<td><input type="text" name="form-0-pname" id="id_form-0-pname"></td>
<td><input type="number" name="form-0-hscore" id="id_form-0-hscore"></td>
<td><input type="number" name="form-0-age" id="id_form-0-age"></td>
<td> <input id="input_add-0-undefined" type="button" name="add-0-undefined" value=" Add More " class="tr_clone_add btn data_input"> </td>
</tr>
<tr>
<td><input type="text" name="form-0-pname" id="id_form-0-pname"></td>
<td><input type="number" name="form-0-hscore" id="id_form-0-hscore"></td>
<td><input type="number" name="form-0-age" id="id_form-0-age"></td>
<td> <input id="remove_button-1-undefined" type="button" name="name_remove1-1-undefined" value="Remove" class="tr_clone_add btn data_input"> </td>
</tr></tbody>
Why does it not add the row with updated name and id ?
Update:
Models.py
class Player(models.Model):
pname = models.CharField(max_length=50)
hscore = models.IntegerField()
age = models.IntegerField()
def __str__(self):
return self.pname
class Team(models.Model):
tname = models.CharField(max_length=100)
player= models.ManyToManyField(Player)
def __str__(self):
return self.tname
Views.py
def post(request):
if request.POST:
form = TeamForm(request.POST)
print("form", form)
form.player_instances = PlayerFormset(request.POST)
if form.is_valid():
team= Team()
team.tname= form.cleaned_data['tname']
team.save()
if form.player_instances.cleaned_data is not None:
for item in form.player_instances.cleaned_data:
player = Player()
player.pname= item['pname']
player.hscore= item['hscore']
player.age= item['age']
player.save()
team.player.add(player)
team.save()
else:
form = TeamForm()
return render(request, 'packsapp/employee/new.html', {'form':form})
Forms.py
class PlayerForm(forms.Form):
pname = forms.CharField()
hscore= forms.IntegerField()
age = forms.IntegerField()
PlayerFormset= formset_factory(PlayerForm)
class TeamForm(forms.Form):
tname= forms.CharField()
player= PlayerFormset()

docent display pop up with table id

When I click on my button "Select" it should show me the HTML popup, and for some reason is not happening.
Could it be some id problem or hard code?
The main idea is to click and bring some kind of list reading from a random array list.
Below: my .js with the call back id and display.
Any ideas?
<!-- This hosts all HTML templates that will be used inside the JavaScript code -->
<table class ="cls-{id} active-{active}" style="display: none;" width="100%" id="rowTemplate">
<tr class ="bb cls-{id} active-{active}">
<td class="active-{active}" id="{id}-question" width="70%">{question}</td>
<td class="cls-{id} active-{active}" width="30%">
<button class="buttons" step="0.01" data-clear-btn="false" style="background: #006b54; color:white !important ;" id="{id}-inspectionResult"></button>
</td>
</tr>
</table>
<div id="projectPopUp" class="popup-window" style="display:none">
<div class="popuptitle" id="details-name"></div>
<table width="100%" id="detailsgrid">
<tr>
<td style="text-align:left">Start Time</td>
<td> <select id="details-startTime" data-role="none"></select></td>
</tr>
<tr>
<td style="text-align:left">End Time</td>
<td> <select id="details-endTime" data-role="none"></select></td>
</tr>
</table>
<div>
<button class="smallButton" onClick="closeProjectPopup()">Cancel</button>
<button class="smallButton" onClick="submitProjectPopup()">Submit</button>
</div>
</div>
<table style="display: none;" id="sectionRowTemplate">
<tr width="100%" class="bb cls-{id}-row2 sectionheader">
<td class="cls-{id}" colspan="3">{question}</td>
</tr>
</table>
Javascript code:
var buildQuestionnaire = function(){
parseInitialDataHolder();
for (var i = 0; i < ARRAY_OF_QUESTIONS.length; i++){
var id = i;
var data = {
id: id,
question: ARRAY_OF_QUESTIONS[i].question,
inspectionResult: '',
active: true
};
var initialdata = initialdataholder[id];
if(initialdata) {
data = initialdata;
}
dataholder.push(data);
if (typeof ARRAY_OF_QUESTIONS[i].header == 'undefined') {
$('#questionsTable tbody').append(Utils.processTemplate("#rowTemplate tbody", data));
$("#" + id + "-inspectionResult").text(data.inspectionResult || 'Select');
$("#" + id + "-inspectionResult").click(resultHandler.bind(data));
updateActiveStatus(data);
commentvisibilitymanager(data);
}
else {
$('#questionsTable tbody').append(Utils.processTemplate("#sectionRowTemplate tbody", data));
}
}
}
//to show the popup
$('#projectPopUp').show();
//to close the popup
$('#projectPopUp').hide();
$(document).ready(function() {
buildQuestionnaire();
});

Using v-bind to put data into a tag a in the property href (VUE.JS 2 + Laravel 5.3)

Here is my javascript/vue.js code:
import _ from 'lodash'
export default{
props:['campanha'],
data (){
return{
list:[],
filter: '',
href: '/campanha/9/edit'
}
},
methods:{
url: function (href){
return '/campanha/'+this.href+'/edit'
}
},
mounted: function (){
this.list = JSON.parse(this.campanha)
},
computed: {
filteredCampanhas(){
var self = this
return this.list.filter(function(campanhas) {
return campanhas.nome.indexOf(self.filter) > -1
})
}
}
}
And here it`s my html:
<template>
<div>
<div class="well">
Novo Cadastro <span class="glyphicon glyphicon-plus" aria-hidden="true"/><br></br>
<input type="text" class="form-control" placeholder="Filtrar Campanhas" v-model="filter">
</div>
<div class="table-responsive">
<table class="table table-borderless">
<thead>
<tr>
<th>Id</th>
<th>Nome</th>
<th>Data Início</th>
<th>Data Término</th>
<th>Hora Inícío</th>
<th>Hora Término</th>
</tr>
</thead>
<tbody>
<!--{{ url('/campanha/' . $item->id_campanha . '/edit') }}
href: '/campanha/9/edit'
<td><a v-bind:href="href">{{ c.nome }}</a></td>
!-->
<tr v-for="c in filteredCampanhas">
<td>{{ c.id_campanha }}</td>
<td><a :href="url(c.id_campanha)">{{ c.nome }}</a></td>
<td>{{ c.data_inicio }}</td>
<td>{{ c.data_termino }}</td>
<td>{{ c.hora_inicio }}</td>
<td>{{ c.hora_termino }}</td>
</tr>
</tbody>
</table>
</div>
<div>
</template>
I have tried to put some data into href section of my tag a, to link to another page, but it`s not working.
Try following:
methods:{
url: function (href){
return '/campanha/'+ href+'/edit'
}
},
When you are using this.href it will start to pick href from data of vue instance,

After redirecting to another page how to use controller and scope data of previous page in angularjs

This is for an assignment. Here table contains book details which contains book name, author, price, ISBN and category. When user click on book name it should redirect to order page displaying book name, author and price.
BookPage.html
<script type="text/javascript" src="book.js">
<body ng-app="mymodule" >
<div ng-controller="myController" >
<table border=2>
<thead>
<tr>
<th>ISBN</th>
<th>NAME</th>
<th>AUTHOR</th>
<th>CATEGORY</th>
<th>PRICE</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="book in books">
<td>{{ book.ISBN }}</td>
<td >{{ book.Name }}</td>
<td>{{ book.Author }}</td>
<td>{{ book.Category }}</td>
<td>{{ book.price }}</td>
</tr>
</tbody>
</table>
**books.js**
var myapp = angular.module('mymodule', []);
myapp.controller("myController", function($scope, $http,$window) {
$http.get("https://api.myjson.com/bins/p4ujn").then(function(response) {
$scope.books = response.data;
$scope.getdetail=function(){
$scope.getbookdetail=this.book;
$window.location.href = "orderpage.html";
}
});
});
Page to be redirected when user click on book name.
orderpage.html
<script type="text/javascript" src="book.js"></script>
<body ng-app="mymodule" >
<div ng-controller="myController" >
{{getbookdetail.Name}}<br>
{{getbookdetail.Author}}
{{getbookdetail.price }}<br>
</div>
</body
This is my code. It display nothing, just a blank page.
You can use a Service or factory to share the data across the controllers.
DEMO
var app = angular.module("clientApp", [])
app.controller("TestCtrl",
function($scope,names) {
$scope.names =[];
$scope.save= function(){
names.add($scope.name);
}
$scope.getnames = function(){
$scope.names = names.get();
}
}
);
app.factory('names', function(){
var names = {};
names.list = [];
names.add = function(message){
names.list.push({message});
};
names.get = function(){
return names.list;
};
return names;
});
<!doctype html>
<html >
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="clientApp">
<div ng-controller="TestCtrl">
<input type="text" ng-model="name">
<button ng-click="save()" > save</button>
</div>
<div ng-init="getnames()" ng-controller="TestCtrl">
<div ng-repeat="name in names">
{{name}}
</div>
</div>
</body>
</html>
Apart from service/factory , you can go for other options like localStorage and rootScope, but those are not recommended ways.
You should use factory/Services, localStorage, routeParams or Child Parent controllers

Categories

Resources