Scope model update - javascript

Below demo app is showing three different progressbars.
Now user needs to select which progressbar he/she wants to change value
and then on button click which is provided at same page.
var app = angular.module('myApp',[]);
app.component('listComponent', {
template:'<div ng-repeat="progress in $ctrl.obj.bars track by $index">' +
'<progress value="{{progress}}" max="{{$ctrl.obj.limit}}">{{progress}}</progress><br>'+
'</div>'+
'<br>' +
'<div>' +
'Selected Progressbar : {{$ctrl.selectedProgressbar}}' +
'<span>' +
'<select name="selectedProgressbar" ng-model="$ctrl.selectedProgressbar">' +
'<option ng-repeat="progress in $ctrl.obj.bars track by $index" value="{{$index}}">{{progress}}</option>' +
'</select>' +
'</span>' +
'<span ng-repeat="btn in $ctrl.obj.buttons">' +
'<button class="btn" ng-click="$ctrl.changeProgress(btn, $ctrl.selectedProgressbar)">{{btn}}</button>' +
'</span>' +
'</div>',
controller: function () {
this.obj = {
"buttons": [
10,
38,
-13,
-18
],
"bars": [
62,
45,
62
],
"limit": 230
};
function changeProgressbar(val){
var val = parseInt(val);
var barValue = this.obj.bars[this.selectedProgressbar];
var selectedBar = this.selectedProgressbar;
var bars = this.obj.bars;
// this.obj.bars[0] = parseInt(this.obj.bars[0]) + parseInt(val);
// if we remove comment from above code and comment below one then progresbar value changes at same time
// but with below code its not changing at same time its changing when we click on any button or change progreebar selection
if(val > 0){
var total = parseInt(barValue) + val;
var update = setInterval(function() {
if (parseInt(barValue) > total) {
clearInterval(update);
}
barValue = parseInt(barValue) + 1;
bars[selectedBar] = barValue;
}, 15);
}
}
this.changeProgress = changeProgressbar;
}
});
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="This is just demo application by using Angular 1.6">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Progressbar in Angular 1.6</title>
<style type="text/css" media="screen">
progress:after {
display: block;
content: attr(value);
text-align:center;
}
</style>
</head>
<body ng-app="myApp">
<list-component></list-component>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<script>
</script>
</body>
</html>
jsBin is here,
now after selecting any progressbar then click on any first two buttons then no change is found on progreebar
but as soon as you click again or select some other progressbar then value is changing.

After going through your code, I found some issues there.
You should change the changeProgressbar function and remove the interval function.
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="[add your bin description]">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Progressbar in Angular 1.6</title>
<style type="text/css" media="screen">
progress:after {
display: block;
content: attr(value);
text-align:center;
}
</style>
</head>
<body ng-app="myApp">
<list-component></list-component>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<script>
var app = angular.module('myApp',[]);
app.component('listComponent', {
// isolated scope binding
template:'{{$ctrl.obj.bars}}<div ng-repeat="progress in $ctrl.obj.bars track by $index">' +
'<progress value="{{progress}}" max="{{$ctrl.obj.limit}}">{{progress}}</progress><br>'+
'</div>'+
'<br>' +
'<div>' +
'Selected Progressbar : {{$ctrl.selectedProgressbar}}' +
'<span>' +
'<select name="selectedProgressbar" ng-model="$ctrl.selectedProgressbar">' +
'<option ng-repeat="progress in $ctrl.obj.bars track by $index" value="{{$index}}">{{progress}}</option>' +
'</select>' +
'</span>' +
'<span ng-repeat="btn in $ctrl.obj.buttons">' +
'<button class="btn" ng-click="$ctrl.changeProgress(btn, $ctrl.selectedProgressbar)">{{btn}}</button>' +
'</span>' +
'</div>',
controller: function () {
this.obj = {
"buttons": [
10,
38,
-13,
-18
],
"bars": [
62,
45,
62
],
"limit": 230
};
function changeProgressbar(val){
var val = parseInt(val);
var barValue = this.obj.bars[this.selectedProgressbar];
var selectedBar = this.selectedProgressbar;
var bars = this.obj.bars;
// this.obj.bars[0] = parseInt(this.obj.bars[0]) + parseInt(val);
// if we remove comment from above code and comment below one then progresbar value changes at same time
// but with below code its not changing at same time its changing when we click on any button or change progreebar selection
if(val > 0){
var total = parseInt(barValue) + val;
if (parseInt(barValue) > total) {
clearInterval(update);
}
else
{
barValue = total;
bars[selectedBar] = barValue;
}
}
}
this.changeProgress = changeProgressbar;
}
});
</script>
</body>
</html>
PLEASE RUN THE ABOVE SNIPPET
Here is a working DEMO

Related

How can I stop my timer function if the quiz ends before time is up? Javascript

I have everything working as it should, except for me trying a million different things and not being able to get the timer function to stop counting down if the quiz ends before the 60 seconds is up.
//total score var that is defined in local storage and question number var that will be incremented later on
var totalScore = 0,
questionNumber = 0,
i = 0;
// questions object
allQuestions = [{
question: "What do you call a variable with multiple boolean values?",
choices: ["variable", "object", "array", "let"],
correctAnswer: "array"
},
{
question: "A useful tool for debugging during development is_______.",
choices: ["wrench", "Chrome dev tools", "Visual Studio Code", "keyboard"],
correctAnswer: "Chrome dev tools"
},
{
question: "Where will you find most of the answers to the questions you will have in your coding career?",
choices: ["Teachers", "Coworkers", "User manual", "The Internet"],
correctAnswer: "The Internet"
},
{
question: "What should you do when using git before you push a project to the repository?",
choices: ["pull", "bop it", "save it", "close it"],
correctAnswer: "pull"
}
];
var counterValue = 60;
var mainContent = $('#mainContent');
//logic if correct answer is chosen
function correctGuess() {
totalScore ++;
questionNumber ++;
var updatePage = question(questionNumber);
localStorage.setItem("scoreCount", totalScore);
$('#mainContent').html(updatePage);
if(questionNumber < 4){
var updatePage = question(questionNumber);
$('#mainContent').html(updatePage);
}
};
//logic if incorrect answer is chosen
function incorrectGuess() {
counterValue -= 5;
totalScore = 0;
questionNumber ++;
var updatePage = question(questionNumber);
$('#mainContent').html(updatePage);
};
//starting screen
function welcome() {
mainContent.html('<h2>Welcome to the Code Quiz!</h2>' + '<br />' +
'<h5>If you think you have what it takes, go ahead and click the start button to see how you do!</h5>'
+ '<button type="button" class="btn btn-primary" id="startQuizBtn">Start Quiz!</button>');
document.getElementById("startQuizBtn").addEventListener("click", function() {question(i)});
//timer function
document.getElementById("startQuizBtn").addEventListener("click", function() {timer()})
};
function timer() {
var timer = setInterval(function(){
counterValue -= 1;
$("#timer-value").html(counterValue)
if (counterValue <= 0) {
clearInterval(timer)
displayScore()
}
},1000)
}
//loads start page to begin with
window.onload = function () {
this.welcome();
};
//logic to run through questions object
function question(i) {
if (i < 4) {
mainContent.html('<div id="questionDiv">' +
'<h2>Question ' + (i + 1) + '<h2>' +
'<h3>' + allQuestions[i].question + '</h3>' +
'<input type="radio" class="radiobtn" name="questionChoices" value="' + allQuestions[i].choices[0] + '" checked="yes">' + allQuestions[i].choices[0] + '</input>' + '<br />' +
'<input type="radio" class="radiobtn" name="questionChoices" value="' + allQuestions[i].choices[1] + '">' + allQuestions[i].choices[1] + '</input>' + '<br />' +
'<input type="radio" class="radiobtn" name="questionChoices" value="' + allQuestions[i].choices[2] + '">' + allQuestions[i].choices[2] + '</input>' + '<br />' +
'<input type="radio" class="radiobtn" name="questionChoices" value="' + allQuestions[i].choices[3] + '">' + allQuestions[i].choices[3] + '</input>' + '<br />' +
'<button type="button" class="btn btn-primary" id="submitButton">Submit</button>' + '</div>' );
} else {
chooseNextScreen();
};
//submit button at the bottom of the questions
$('#submitButton').on('click', function() {
if($('input:radio[name=questionChoices]:checked').val() === allQuestions[i].correctAnswer && i < 4) {
correctGuess();
} else {
incorrectGuess();
}
});
};
//logic to decide what screen to append next
function chooseNextScreen(){
if (questionNumber < 4) {
question();
} else {
displayScore();
}
};
// end screen of quiz
function displayScore() {
//Text, form and button on end page
$('#mainContent').html('<h2>Well Done!</h2>' + '<h4> You scored ' + totalScore + '!</h4>' + '<h4>Please enter your name for the end screen</h4>' +
'<hr />' + '<form>' + '<input class="form-control" id="initialsBox" type="text" placeholder="Your Name">' + '<button type="button" class="btn btn-primary" id="hiScoreSubmitBtn">Submit</button>' + '</form>');
// Submit button on end screen of quiz
$('#hiScoreSubmitBtn').on('click', function(event) {
localStorage.setItem(initialsBox[0].value, totalScore);
mainContent.html('<h1>' + initialsBox[0].value + ' scored a ' + totalScore + '!' + '</h1>');
});
var initialsBox = $("#initialsBox");
};
//calls function for quiz to run
question(questionNumber);
Here's the HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Code Quiz</title>
<link rel="stylesheet" type="text/css" href="assets/style.css" />
</head>
<body>
<!--Top row heading of title and time left-->
<div class="row">
<div class="col">
<h1 id="code-quiz">Code Quiz!</h1>
</div>
<div class="col">
<h3 id="timer">Time Left: <span id="timer-value"></span></h3>
</div>
</div>
<!--Main Content-->
<div class="container">
<div id="headingLine" class="row main-heading">
<div class="classname" id="id"></div>
</div>
<div class="row">
<div class="col" id="mainContent">
</div>
</div>
</div>
<!--Script Tags-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="assets/script.js"></script>
</body>
</html>
I cant help but feel like the answer is right in front of me, but I've been staring at it for hours at this point.
document.getElementById("startQuizBtn").addEventListener("click", ()=>{
var counterVal = 5;
timer=setInterval(function() {
counterVal=counterVal-1;
console.log(counterVal)
if(counterVal==0){
clearInterval(timer)
}
},1000)
})

Changing Date should change data

Hello what I am not understanding why when the user inputs the date it it doesn't update the URL. I am taking the NASA API for the APOD and trying to make it interactive, the issue here is that when I manually change the URL the api data loads that data, but I lost on why my user input data is not working for it.
// Go to https://api.nasa.gov/index.html#apply-for-an-api-key to get an API Key
var apodContain = document.getElementById('apod');
var API_KEY = 'XEXvzGBBdF14FSu6UZyzoPYqazSsUkSwAsI8730G';
var datePick = document.getElementById('date');
datePick.max = todaysDate();
datePick.value = todaysDate();
var date = datePick.value;
var url = 'https://api.nasa.gov/planetary/apod?api_key=' + API_KEY + '&date=' + date;
function makeApiRequest(url) {
var myRequest = new XMLHttpRequest();
myRequest.onreadystatechange = function () {
if (myRequest.readyState === XMLHttpRequest.DONE) {
if (myRequest.status === 200) {
var responseText = myRequest.responseText;
myRequest.onload = function () {
var responseJson = JSON.parse(responseText);
console.log(responseJson);
renderHTML(responseJson);
}
} else {
var errorMessage = document.getElementById('error');
errorMessage.innerHTML = "This date this not work";
}
}
}
// intializes AJAX
myRequest.open('GET', url, true);
myRequest.send();
};
makeApiRequest(url);
datePick.addEventListener('change', function(e){
date = datePick.value;
url = 'https://api.nasa.gov/planetary/apod?api_key=' + API_KEY + '&date=' + date;
})
function todaysDate() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
return year + '-' + month + '-' + day;
datePicker.setAttribute("max", datePicker.value);
}
function renderHTML(data) {
var htmlString = "";
htmlString = "<img src = " + data.url + "></img>" + "<h1>" + data.title + "</h1>" + "<p>" + data.explanation + "</p>";
apodContain.insertAdjacentHTML('beforeend', htmlString);
}
h1{
text-align: center;
font: bold;
}
h5 {
text-align: center;
font: bold;
}
img {
display: block;
margin-left: auto;
margin-right: auto;
width: 500px;
height: 500px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>INFO 343 APOD</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous" type="text/css" />
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>INFO 343 APOD</h1>
<div id="apod"></div>
<h5>Choose your date: <input id="date" type="date"></input></h5>
<div id="error"></div>
<script src="js/app.js" type="text/javascript"></script>
</body>
</html>
.
You forgot to add
datePick.addEventListener('change', function(e){
date = datePick.value;
url = 'https://api.nasa.gov/planetary/apod?api_key=' + API_KEY + '&date=' + date;
makeApiRequest(url); // <- this
})

How to add select filtering for column values in javascript DataTables

I'm using javascript DataTables to display a csv file on a webpage. Below is my
javascript file:
var CsvToHtmlTable = CsvToHtmlTable || {};
CsvToHtmlTable = {
init: function (options) {
options = options || {};
var csv_path = options.csv_path || "";
var el = options.element || "table-container";
var allow_download = options.allow_download || false;
var csv_options = options.csv_options || {};
var datatables_options = options.datatables_options || {};
var custom_formatting = options.custom_formatting || [];
$("#" + el).html("<table class='table table-striped table-condensed' id='" + el + "-table'></table>");
$.when($.get(csv_path)).then(
function(data){
var csv_data = $.csv.toArrays(data, csv_options);
var table_head = "<thead><tr>";
for (head_id = 0; head_id < csv_data[0].length; head_id++) {
table_head += "<th>" + csv_data[0][head_id] + "</th>";
}
table_head += "</tr></thead>";
$('#' + el + '-table').append(table_head);
$('#' + el + '-table').append("<tbody></tbody>");
for (row_id = 1; row_id < csv_data.length; row_id++) {
var row_html = "<tr>";
var color = "red";
//takes in an array of column index and function pairs
if (custom_formatting != []) {
$.each(custom_formatting, function(i, v){
var col_idx = v[0]
var func = v[1];
csv_data[row_id][col_idx]= func(csv_data[row_id][col_idx]);
})
}
for (col_id = 0; col_id < csv_data[row_id].length; col_id++) {
if (col_id === 2) {
row_html += "<td>" + parseFloat(csv_data[row_id][col_id]) + "</td>";
}
else {
row_html += "<td>" + csv_data[row_id][col_id] + "</td>";
}
if (parseFloat(csv_data[row_id][2]) <= 1 && parseFloat(csv_data[row_id][2]) > 0.7) {
color = "red";
}
else if (parseFloat(csv_data[row_id][2]) <= 0.7 && parseFloat(csv_data[row_id][2]) >= 0.5) {
color = "orange";
}
else {
color = "yellow";
}
}
row_html += "</tr>";
$('#' + el + '-table tbody').append(row_html).css("background-color", color));
}
$('#' + el + '-table').DataTable(datatables_options);
if (allow_download)
$("#" + el).append("<p><a class='btn btn-info' href='" + csv_path + "'><i class='glyphicon glyphicon-download'></i> Download as CSV</a></p>");
});
}
}
And below is my index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>CSV to HTML Table</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/dataTables.bootstrap.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script type="text/javascript" src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script type="text/javascript" src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container-fluid">
<h2>CSV to HTML Table</h2>
<div id='table-container'></div>
</div><!-- /.container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/jquery.csv.min.js"></script>
<script type="text/javascript" src="js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="js/dataTables.bootstrap.js"></script>
<script type="text/javascript" src="js/csv_to_html_table.js"></script>
<script type="text/javascript">
function format_link(link){
if (link)
return "<a href='" + link + "' target='_blank'>" + link + "</a>";
else
return "";
}
CsvToHtmlTable.init({
csv_path: 'data/fatty_acid_profiles.csv',
element: 'table-container',
allow_download: true,
csv_options: {separator: ','},
datatables_options: {"paging": false},
custom_formatting: [[4, format_link]]
});
</script>
</body>
</html>
My webpage currently looks like this:
I want to know is it possible in DataTables that for 2nd & 3rd columns, I get a Filter along with the column name so that we can select for which specific values we want to view data for, something like what we have in Excel (using Sort & Filter)?? Please help!!
Yes, it is possible with a customized solution.
You need to read all columns and add distinct members to dropdowns like this.
$(document).ready(function() {
$('#example').DataTable( {
initComplete: function () {
this.api().columns().every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.header()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
});
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
});
});
}
});
});
By using column().search() functionality, you will have a column based filter with dropdowns. You can move dropdowns from header to footer by changing .appendTo($(column.header()).empty()) to .appendTo($(column.footer()).empty()).
Examples:
jsFiddle (header dropdowns)
jsFiddle (footer dropdowns)

Button being triggered twice and element not being rendered anymore

I have this weather page that every time I click the button it changes from Celcius to Fahrenheit or vice-versa.
What is happening is that once I click the first time, it works fine, but then if I click it again or more times, my console log shows that it executes it twice and does not render the element anymore (#link).
$("#data").on('click', '#link', function () {
var html2 = "";
html2 += '<button class="temp" id="link">'
if (flag == 0){
console.log("c to f");
html2 += "<h1>" + celciusToFahrenheit(Math.round(json.main.temp)) + " °F</h1>";
flag = 1;
} else if (flag == 1){
console.log("f to c");
html2 += "<h1>" + Math.round(json.main.temp) + " °C</h1>";
flag = 0;
}
html2 += "</button>"
$("#link").html(html2);
});
I am including the entire file bellow:
$(document).ready(function() {
function getCurrentLocation(callback) {
if (!navigator.geolocation) return;
navigator.geolocation.getCurrentPosition(function(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
url = ('http://api.openweathermap.org/data/2.5/weather?lat=' + latitude + '&lon=' + longitude + '&units=metric&appid=b464bb8dd84e7e7d36103593a472ae9a');
callback(url);
});
}
function celciusToFahrenheit(celcius) {
var fahrenheit = celcius * (9 / 5) + 32;
return fahrenheit;
}
getCurrentLocation(function(currLocMap) {
$.getJSON(url, function(json) {
var html = "";
var flag = 0;
html += '<button class="temp" id="link">'
html += "<h1>" + Math.round(json.main.temp) + " °C </h1>";
html += "</button>"
html += "<h1>" + json.name + "</h1>";
html += "<h3>" + json.weather[0].main + "</h3>";
html += "<h3>" + json.weather[0].description + "</h3>";
$("#data").on('click', '#link', function () {
var html2 = "";
html2 += '<button class="temp" id="link">'
if (flag == 0){
console.log("c to f");
html2 += "<h1>" + celciusToFahrenheit(Math.round(json.main.temp)) + " °F</h1>";
flag = 1;
console.log(flag);
} else if (flag == 1){
console.log("f to c");
html2 += "<h1>" + Math.round(json.main.temp) + " °C</h1>";
flag = 0;
console.log(flag);
}
html2 += "</button>"
$("#link").html(html2);
});
console.log(json);
console.log(json.name);
console.log(json.main.temp);
console.log(json.weather[0].main);
console.log(json.weather[0].description);
console.log(json.weather[0].icon);
$("#data").html(html);
});
});
});
button#link { background:none;border:none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Weather</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<!-- <script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script> -->
</head>
<body>
<div id="data">
<h4>You are here:</h4>
</div>
</body>
</html>
That's because you're recreating the button inside the click event handler. You should change the content of the h1 tag in your handler instead of recreating the entire button, something like so:
$("h1",$(this)).html("new content");

how to edit the text of row in jQuery +JQM [duplicate]

This question already has an answer here:
Binding the click event of a row with jQuery
(1 answer)
Closed 8 years ago.
I am creating a demo in which I make row in button click .I want to edit it's text when I click generated row "it generate another row inside container".can we give a option to change the text of row while clicking the edit button .It some thing open pop up when your press done it save the text on same id ?
http://jsfiddle.net/k7zJ4/2/
function createTestCase(testCaseName,iscreatedFromScript,jsonObject) {
var id;
if (typeof ($("#testCaseContainer li:last").attr('id')) == 'undefined') {
id = "tc_1";
} else {
id = $("#testCaseContainer li:last").attr('id');
var index = id.indexOf("_");
var count = id.substring(index + 1, id.length);
count = parseInt(count);
id = id.substring(0, index) + "_" + parseInt(count + 1);
}
var html = '<div class="testcaselist_row">' + '<ul>' + '<li id="' + id + '" class="clickTestCaseRow">' + testCaseName + '<a class="delete deleteTestCase_h"></a><button class="editclass" style="width:200px !important">edit</button ></li>' + '</ul>' + '</div>';
$('#testCaseContainer').append(html);
var elem = document.getElementById('testCaseContainer'); // just to scroll down the line
elem.scrollTop = elem.scrollHeight;
}
Please find the below sample code that will replicate the scenario you want to achieve in your code using jqm.Save the below code as html and click on add text case and click on change text button
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0-beta.1/jquery.mobile-1.3.0-beta.1.min.css" />
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.0-beta.1/jquery.mobile-1.3.0-beta.1.min.js"></script>
</head>
<body>
<div data-role="page">
<div data-role=" content ">
<div class="contentsubbox" id="testCaseContainer">
<div class="testcaselist_row"><ul id="testCaseLists" data-role="listview" data-theme="a"></ul></div>
</div>
</div>
<footer id="firstPageFooter">
<button class="addtestbtn" id="addTestCase" data-theme="a" style="color: #ffffff!important;">Add Test Case</button>
</footer>
</div>
<script>
$( document ).ready(function() {
console.log( "ready!" );
});
$('#addTestCase').click(function () {
createTestCase("trdt",false,null);
});
$('#testCaseLists').delegate('li', 'tap', function () {
console.log('put your text changing logic here');
$(this).find('a:first').text('text u want to change');//text function shud contain the text
});
function createTestCase(testCaseName,iscreatedFromScript,jsonObject) {
console.log("create test case");
var id;
if ($("div.contentsubbox").find("ul li").length == 0){
id = "tc_1";
} else {
id = $("#testCaseContainer").find("ul li:last").attr('id');
var index = id.indexOf("_");
var count = id.substring(index + 1, id.length);
count = parseInt(count);
id = id.substring(0, index) + "_" + parseInt(count + 1);
}
var html = "<li id="+ id +" class='clickTestCaseRow'><a href='#' style='color: #ffffff!important;'>" + testCaseName + "</a><a class='delete deleteTestCase_h'></a><button class='editclass' style='width:200px !important'>Change text</button ></li>";
$('#testCaseLists').append(html);
$('#testCaseLists').listview('refresh');
var elem = document.getElementById('testCaseContainer'); // just to scroll down the line
elem.scrollTop = elem.scrollHeight;
}
</script>
</body>
</html>
Add comments if you need further help.

Categories

Resources