Error when calling jQuery html method - javascript

I am making my first foray into javascript + jQuery, designing a simple page but encountering errors, I'm sure it's something silly but I've been over the code several times and can't spot it.
The error I receive is below:
The entire code is below (I've changed the dynamic '#' + elementname + 'perc' to a string and I get the same error), can anyone offer any insight?
<DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<!--<script src="js/dealercalc.js"></script>-->
<script type="text/javascript">
$(document).ready(function(){
$(".val-adjust").click(function(){
var name = $(this).attr('name');
var bit = $(this).attr('value');
setvalue(name,bit);
//discountbits['basic'] = false;
//$("#basedisper").text(discountlist['basic']);
});
$("#basdisyes").click(function(){
discountbits['basic'] = true;
//$("#test1").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val(gettotal());
});
}
);
function getpercbypurc(value){
return 0;
};
function setvalue(elementname,yesno){
discountbits[elementname] = yesno;
if (yesno) {
$("#basicperc").hmtl(discountlist[elementname] + "%");
} else {
$('#' + elementname + 'perc').hmtl("0%");
}
};
function gettotal() {
var total = 0;
for (var i=0; i<keys.length; i++){
if (discountbits[keys[i]] = true) {
total += discountlist[keys[i]];
}
}
return total;
};
function displaytotal(){
$('#totalper').html(gettotal());
};
var keys = ['basic', 'marketing'];
var discountlist = {
basic:20,
marketing:2
};
var discountbits = {
basic:true,
marketing:false
};
</script>
</head>
<body>
Base Discount<br>
<button class="val-adjust" name="basic" value="false">No</button>
<button class="val-adjust" name="basic" value="true">Yes</button>
<span id="basicperc">0</span>
<br>
<br>
Marketing Plan<br>
<button class="val-adjust" name="marketing" value="false">No</button>
<button class="val-adjust" name="marketing" value="true">Yes</button>
<span id="marketingperc">0</span>
<br>
<br>
Total<br>
<span id="totalper">0</span>
</body>
</html>

You have wrong spelling for html, hmlt should be html
Change
$("#basicperc").hmtl(discountlist[elementname] + "%");
To
$("#basicperc").html(discountlist[elementname] + "%");

you have a typo
$("#basicperc").hmtl(discountlist[elementname] + "%");
//-----^^^^---here
should be
$("#basicperc").html(discountlist[elementname] + "%");

you've made a typo, it's html not hmtl :)

Very obvious typo. It's html, not hmtl !

Related

How to return contents of php using javascript $.get

I have a PHP script hosted in the root of a working LAMP server which provides me with the output of a MySQL query. The typical output of values.php:
2017-01-12 22:02:17/12/2017-01-12 22:03:18/12/2017-01-12
22:04:18/12/2017-01-12 22:05:18/12/2017-01-12 22:06:18/12/2017-01-12
22:07:19/12/2017-01-12 22:08:19/12/2017-01-12 22:09:19/12/2017-01-12
22:10:20/12/2017-01-12 22:11:20/12/2017-01-12 22:12:20/12/2017-01-12
22:13:21/12/2017-01-12 22:14:21/12/2017-01-12 22:15:21/12/2017-01-12
22:16:21/12/2017-01-12 22:17:22/12/2017-01-12 22:18:22/11/2017-01-12
22:19:22/11/2017-01-12 22:20:23/12/2017-01-12 22:21:23/11/2017-01-12
22:22:23/11/2017-01-12 22:23:24/11/2017-01-12 22:24:24/11/2017-01-12
22:25:24/11/2017-01-12 22:26:25/11/2017-01-12 22:27:25/11/2017-01-12
22:28:25/11
I am trying to use $.get to break it up and list it on a page. My code is as follows but it won't work:
<!DOCTYPE html>
<html>
<body>
<script>
function() {
var switch1 = true;
$.get('values.php', function(data) {
data = data.split('/');
for (var i in data)
{
if (switch1 == true)
{
document.write(data[i] + " Temp: ");
switch1 = false;
}
else
{
document.writeln(data[i]);
switch1 = true;
}
}
});
};
</script>
</body>
</html>
Any ideas where I am going wrong?
I should have added the code <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jque‌​ry.min.js"></script> in the html. Final code is as follows and works fine:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<script>
var switch1 = true;
$.get('values.php', function(data) {
data = data.split('/');
for (var i in data)
{
if (switch1 == true)
{
document.write(data[i] + " Temp: ");
switch1 = false;
}
else
{
document.write(data[i] + "<br>");
switch1 = true;
}
}
});
</script>
</body>
</html>
Thanks to all.
I don't know what your PHP script actually returns but if I store manually to data it seems to work the way you expected. Can you explain what exactly does not work?
I would shorten code bit though:
var switch1 = true;
var data = "2017-01-12 22:02:17/12/2017-01-12 22:03:18/12/2017-01-12 22:04:18/12/2017-01-12 22:05:18/12/2017-01-12 22:06:18/12/2017-01-12 22:07:19/12/2017-01-12 22:08:19/12/2017-01-12 22:09:19/12/2017-01-12 22:10:20/12/2017-01-12 22:11:20/12/2017-01-12 22:12:20/12/2017-01-12 22:13:21/12/2017-01-12 22:14:21/12/2017-01-12 22:15:21/12/2017-01-12 22:16:21/12/2017-01-12 22:17:22/12/2017-01-12 22:18:22/11/2017-01-12 22:19:22/11/2017-01-12 22:20:23/12/2017-01-12 22:21:23/11/2017-01-12 22:22:23/11/2017-01-12 22:23:24/11/2017-01-12 22:24:24/11/2017-01-12 22:25:24/11/2017-01-12 22:26:25/11/2017-01-12 22:27:25/11/2017-01-12 22:28:25/11"
data = data.split('/').map(function(i){
document.write(i + (switch1 ? " Temp: " : ""));
switch1 = !switch1;
});
Give this a try, should do what you are looking for...
var content = "2017-01-12 22:02:17/12/2017-01-12 22:03:18/12/2017-01-12 22:04:18/12/2017-01-12 22:05:18/12/2017-01-12 22:06:18/12/2017-01-12 22:07:19/12/2017-01-12 22:08:19/12/2017-01-12 22:09:19/12/2017-01-12 22:10:20/12/2017-01-12 22:11:20/12/2017-01-12 22:12:20/12/2017-01-12 22:13:21/12/2017-01-12 22:14:21/12/2017-01-12 22:15:21/12/2017-01-12 22:16:21/12/2017-01-12 22:17:22/12/2017-01-12 22:18:22/11/2017-01-12 22:19:22/11/2017-01-12 22:20:23/12/2017-01-12 22:21:23/11/2017-01-12 22:22:23/11/2017-01-12 22:23:24/11/2017-01-12 22:24:24/11/2017-01-12 22:25:24/11/2017-01-12 22:26:25/11/2017-01-12 22:27:25/11/2017-01-12 22:28:25/11";
var regexp = /(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})\/(\d{2})/g;
var matches;
while ( matches = regexp.exec( content ) ) {
document.write( matches[1] + " Temp: " + matches[2] + "<br/>");
}
Hope this helps!

How can I run a function when a radio is selected and I click a button?

I've created this simple code that I'll use to store in the user's browser, so, I'd like to know how can I run a function when there's a selected radio and when I click the delete button, using JS or JQuery. Any help is appreciated.
Thanks in advance.
check it on liveweave
P.S.: Your browser should have WebStorage support
var taskCounter = 1 + Number(localStorage.getItem("count"));
var name = "de"+ taskCounter;
for(var i=1;i<taskCounter;i++){
var temp = "de" + i;
document.writeln("<br/>"+'<input type="radio" name="rad" value="'+localStorage.getItem(temp)+'" /> <label>'+localStorage.getItem(temp)+'</lable>');
}
function saveItUp(){
var desc = $('#descrip').val();
alert(desc);
// Store
localStorage.setItem(name, desc);
localStorage.setItem("count", taskCounter);
// Retrieve
console.log(localStorage.getItem(name));
console.log(localStorage.getItem("count"));
}
//This is where I'm trying to do that, I know selected doesn't exist, but I put it just for a better comprehension
function deleteItUp(){
$('input:radio').selected(function(){
if (this.checked) {
alert(this.value);
}
});
}
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="main">
<label>Task</label> <textarea id="descrip"></textarea>
<button onclick="saveItUp();" id="save">Save it</button>
<button onclick="deleteItUp();" id="delete">Delete</button>
</div>
</body>
</html>
I have edited your snippet. Use $('input[type="radio"]').prop('checked') to see whether the radio button is checked. You will need to modify the selector to get the appropriate radio button if there are multiple on the page.
var taskCounter = 1 + Number(localStorage.getItem("count"));
var name = "de" + taskCounter;
for (var i = 1; i < taskCounter; i++) {
var temp = "de" + i;
document.writeln("<br/>" + '<input type="radio" name="rad" value="' + localStorage.getItem(temp) + '" /> <label>' + localStorage.getItem(temp) + '</lable>');
}
function saveItUp() {
var desc = $('#descrip').val();
alert(desc);
// Store
localStorage.setItem(name, desc);
localStorage.setItem("count", taskCounter);
// Retrieve
console.log(localStorage.getItem(name));
console.log(localStorage.getItem("count"));
}
//This is where I'm trying to do that, I know selected doesn't exist, but I put it just for a better comprehension
function deleteItUp() {
if ($('input[type="radio"]').prop('checked')) {
alert('Deleting!');
} else {
alert('Delete radio not checked!');
}
}
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="main">
<label>Task</label>
<textarea id="descrip"></textarea>
<button onclick="saveItUp();" id="save">Save it</button>
<button onclick="deleteItUp();" id="delete">Delete</button>
<input type="radio">Check to delete
</div>
</body>
</html>
I've been trying other ways to achieve it, and I found a nice way that gave me the expected result, thank all of you who tried to help me.
var taskCounter = 1 + Number(localStorage.getItem("count"));
var name = "de" + taskCounter;
for (var i = 1; i < taskCounter; i++) {
var temp = "de" + i;
document.writeln("<br/>" + '<input type="radio" name="rad" value="' + temp + '" /> <label>' + 'Code: ' + temp + ' | Value: ' + localStorage.getItem(temp) + '</lable>');
}
function saveItUp() {
var desc = $('#descrip').val();
alert(desc);
// Store
localStorage.setItem(name, desc);
localStorage.setItem("count", taskCounter);
// Retrieve
console.log(localStorage.getItem(name));
console.log(localStorage.getItem("count"));
}
var selectedRadioId = 0;
$('input:radio').change(function() {
if (this.checked) {
selectedRadioId = this.value;
}
});
function deleteItUp() {
if (selectedRadioId !== 0) {
alert('Deleting!');
} else {
alert("Radio hasn't been checked!");
}
}
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="main">
<label>Task</label>
<textarea id="descrip"></textarea>
<button onclick="saveItUp();" id="save">Save it</button>
<button onclick="deleteItUp();" id="delete">Delete</button>
</div>
</body>
</html>
You are talking about firing an event when a radio button is checked and then calling a callback function: https://api.jquery.com/checked-selector/

Why do I lose formatting after running javascript?

This is probably a silly question but why do I lose all the formatting when the function test() starts? What should I change in my code? I would really appreciate your help!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style type="text/css">
body {
background: #E6E6FA;
font-family: book antiqua;
}
h1, h2 {
color: grey;
}
</style>
</head>
<h3>Title</h3>
<body bgcolor="#E6E6FA">
<input type="text" id="userInput"></input>
<button onclick="test()">Submit</button>
<p id="Demo"></p>
<p id="Beg"></p>
<p id="Fin"></p>
<script>
function test()
{
var nam= document.getElementById("userInput").value;
var l = nam.length;
var pocz = nam.slice(0,1);
var kon = nam.slice(-1);
document.getElementById("Demo").innerHTML = document.write("Your secret code: " + l + pocz + kon);
var one = nam.slice(-1)
if (one == "a") {
document.write(nam.slice(0,-1) + "bbb");
} else {
document.write(nam + "ccc");
}
}
</script>
</body>
</html>
If document.write is called after the DOM loaded, it replaces the document. Also you are using document.write incorrectly, it doesn't return anything. Just omit it and it will work fine.
document.getElementById("Demo").innerHTML = "Your secret code: " + l + pocz + kon;
For the other uses, do the same thing and assign the value to an element via innerHTML.
Please read the documentation before you use an unfamiliar function.
Never use document.write. Ever. Just don't use it. It is completely antiquated.
Felix Kling's answer will work for the first part, since you are assigning html to an element directly. but the later calls are adding more content to the document, not replacing content, so you must append new content to the document, or make another placeholder (like demo). here is how to do it with appending new content:
function test()
{
var nam= document.getElementById("userInput").value;
var l = nam.length;
var pocz = nam.slice(0,1);
var kon = nam.slice(-1);
document.getElementById("Demo").innerHTML = "Your secret code: " + l + pocz + kon;
var one = nam.slice(-1);
if (document.getElementsByClassName("spantext").length===0)
{
var text=document.createElement("span");
text.setAttribute("class","spantext");
document.getElementsByTagName("body")[0].appendChild(text);
}
else {
var text=document.getElementsByClassName("spantext")[0];
}
if (one == "a") {
text.innerHTML=nam.slice(0,-1) + "bbb";
} else {
text.innerHTML=nam + "ccc";
}
}
fiddle

Is there a way that you can print this code instead of having an onclick?

I am making a puzzle website where you select a puzzle, I was wondering if there was a way of, instead of it being in pop up boxes it would be printed to the website. I don't mind what code we are using as I am fluent in most,
This is the code I have so far:
<body>
<script type="text/javascript">
function myFunction()
{
function ask() {
var a = (Math.round(Math.random()*1000000))
alert (a)
return prompt("What was the number?") == eval( a );
}
var questions = [ask(), ask(), ask(), ask(), ask()],
total = questions.length,
correct = questions.filter(Boolean).length;
alert( "You got "+correct+"/"+total+" correct");
}
</script>
<button onClick="myFunction()">Remember the number</button>
</body>
<body>
<script type="text/javascript">
function myFunction2(){
function ask() {
var a = Math.floor(Math.random() * 10) + 1;
var b = Math.floor(Math.random() * 10) + 1;
var op = ["*", "+", "/", "-"][Math.floor(Math.random()*4)];
return prompt("How much is " + a + " " + op + " " + b + "?") == eval( a + op + b);
}
var questions = [ask(), ask(), ask(), ask(), ask()],
total = questions.length,
correct = questions.filter(Boolean).length;
alert( "You got "+correct+"/"+total+" correct");
}
</script>
<button onClick="myFunction2()">Quick math</button>
</body>
</html>
</html>
So I was wondering if there was a way to make it show up as text and have a text box on the page to type into that would still work. And the design is able to be changed, so I can make a larger text box, or a larger font so it's not just an un-editable onclick.
All help greatly appreciated.
Thanks.
I did what I thought that you wanted to the "Remember the number" button click.
Sorry, had no time to do the other one.
HTML:
<body>
<button id="rmbrBtn">Remember the number</button>
</body>
<body>
<button id="quivkBtn">Quick math</button>
<div id="question_area">
</div>
</body>
</html>
</html>
JS & jQuery code:
$("#rmbrBtn").click(function()
{
// Answers collection
var questions = [];
// Check the correctness of the answer
function checkAnswer (){
total = questions.length,
correct = questions.filter(Boolean).length;
if(total < 5)
{
ask();
}else{
var answer = '<div>You got '+correct+'/'+total+' correct <input type="button" value="Ok" id="ansOk"/></div>';
$("#question_area").append(answer);
$("#ansOk").click(function(){
$(this).parent().empty();
$(this).parent().remove();
});
}
}
// Get the question
function ask() {
var a = (Math.round(Math.random()*1000000));
// View the generated number
var viewNumber = '<div>'+a+'<input type="button" id="ok" value="OK"/>'+'</div>';
// Prompt user with a text box
var promptVal = '<div>Enter your value: <input type="text" id="ans" /> <input type="button" id="prmtOk" value="Ok"/></div>';
// Append
$("#question_area").append(viewNumber);
$("#ok").click(function(){
$(this).parent().empty();
$(this).parent().remove();
$("#question_area").append(promptVal);
$("#prmtOk").click(function(){
var prmt = $("#ans").val();
var addVal = prmt == a;
questions.push(addVal);
checkAnswer();
$(this).parent().empty();
$(this).parent().remove();
});
});
}
// Run the function.
checkAnswer();
});
Online solution:
JSFiddle
Try to do the other one same as this.
Sorry had no time to comment also.
I think you can figure this out.
Just add a div at the top of your page and use jqueries .html() and you will be done
like
$('.header').html('You are correct.');
here is a fiddle http://jsfiddle.net/AMISingh/8nWKD/3/
This can also be done without JQuery and just JavaScript.
http://jsfiddle.net/8nWKD/4/
<div id="header" class="header">This is the header</div>
<div class="button" onClick="test_click()"> Click me!</div>
and the JavaScript
function test_click()
{
document.getElementById("header").innerHTML = "CORRECT!";
}

How do I control the font weight of any text within a paragraph (<p> tag) within braces or curly brackets { } using JavaScript

I would like to be able to control the font-weight of text if bracketed inside a p tag using JavaScript.
For instance:
The cow jumped over the {moon}. font-weight within {} would be increased.
This so the end user can type this into a text area and on submit the would print to page altering the font-weight within the braces or curly brackets.
Any help on this would be great.
Here is how you can do this:
var ps = document.getElementsByTagName('p');
foreach = Array.prototype.forEach;
foreach.call(ps, function (p) {
var content = p.innerHTML;
p.innerHTML = content.replace(/\{(.*?)\}|\((.*?)\)/g, function (m) {
return '<span style="font-weight: bold;">' + m + '</span>';
});
});
​
And of course a fiddle.
For the example you need just pure JavaScript, no additional libraries.
Edit:
If you don't want to see the brackets in the result you can use:
var ps = document.getElementsByTagName('p');
foreach = Array.prototype.forEach;
foreach.call(ps, function (p) {
var content = p.innerHTML;
p.innerHTML = content.replace(/\((.*?)\)|\{(.*?)\}/g, function (m) {
return '<span style="font-weight: bold;">' + m.replace(/[\(\)\{\}]/g, '') + '</span>';
});
});
Fiddle: http://jsfiddle.net/ma47D/4/
​
Best regards!
You can do it with mootools like this:
window.addEvent('domready', function()
{
$$('P').each(function(p)
{
p.set('html', p.get('text').replace(/{([^\}]*)*}/g,"<b>$1</b>"));
});
});​
domready is important because it must be done after page is completely loaded. converting to jquery would not be so hard.
http://jsfiddle.net/Smw7Q/1/
Locally you can handle it like this:
<!DOCTYPE html>
<html>
<head>
<script>
function transfer(){
document.getElementById("result").innerHTML=document.getElementById("demo").value.replace(/{/g,'<strong>').replace(/}/g,'</strong>');
}
</script>
</head>
<body>
Input: <input type="text" name="input" id="demo"><br>
<input type="button" value="Submit" onclick="transfer();">
<p id="result"></p>
</body>
</html>
If you submit the text to server, the magic can be done similarly at server side.
My suggestion
<!DOCTYPE html>
<html>
<head>
<style>
p span {
font-size:1.5em;
}
</style>
<script>
function regex(){
document.getElementById("output").innerHTML=
document.getElementById("input").value.replace(/{(.*?)}/g, "<span>$1</span>");
};
</script>
</head>
<body>
<p id="output"></p>
<textarea id="input" rows="30" cols="80"></textarea>
<input type="button" value="Input" onclick="regex();"/>
</body>
<html>
Of course, prior to submitting, you need to sanitize your data.
If tried something, but I'm sure there are more elegant solutions.
http://jsfiddle.net/xT7Fg/
$(document).ready(function(){
$(tb).blur(function(){
var str = '';
var nextFont = 0;
$.each($(tb).val(),function(i,char){
if(nextFont == 0){
if(char == '{'){
if($(tb).val().indexOf(i,'}')){
str += '<font size="15">';
nextFont = $(tb).val().indexOf('}', i);
} else {
str += char;
}
} else {
str += char;
}
} else if (nextFont === i) {
str += '</font>';
nextFont = 0;
} else {
str += char;
}
});
$("#txt").html(str);
});
});

Categories

Resources