JQuery add Checkbox not working - javascript

I am currently experimenting with the google chart api and jquery. I don't have any problems with the google chart api so far, however i have not been able to get jquery working. What I want to do is I want to loop over my json objects I got and add Checkboxes depending on what I get out of the json.
<html>
<head>
<title>Test</title>
<!-- Load jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<!-- Load Google JSAPI -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
addSensorCheckboxes();
function drawChart() {
var jsonData = $.ajax({
dataType: "json",
url: "getValues.php",
data: window.location.href.slice(window.location.href.indexOf('?') + 1),
async: false
}).responseText;
var obj = jQuery.parseJSON(jsonData);
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: ''
};
var chart = new google.visualization.LineChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
function addSensorCheckboxes() {
var jsonData = $.ajax({
dataType: "json",
url: "getSensors.php",
async: false
}).responseText;
var obj = jQuery.parseJSON(jsonData);
for (i in obj)
{
var checkbox = '<input type="checkbox" name="sensors[]" value="'+obj[i][0]+'" />'+obj[i][1];
//alert(checkbox);
$("#test").append(checkbox);
}
}
</script>
</head>
<body>
<form id="theForm" name="theForm" action="index.php" method="get">
<span id="test"></span>
<input id="submit" type="submit" value="Submit" /><br>
</form>
<div id="chart_div" style="width: 100%; height: 100%;">
</div>
</body>
</html>
Any specific mistake I made?
Thanks in advance,
Best regards
Germinator

Try
var checkbox = $('<input type="checkbox" name="sensors[]"
value="'+obj[i][0]+'" />'+obj[i][1]);

A lot of possibilities. Make sure addSensorCheckboxes() is being called and that obj is populated. console.log() is the easiest way to figure out where the application is failing.
Fix your for-in loop as well....for (var i in obj) otherwise 'i' would be global.
Make sure var checkbox is a DOM element, HTML string, or jQuery object (as per the jquery documentation)

Related

How to call one javascript variable to another javascript file

I have an HTMLForm which on click forward me to new HTML page i have Two JS files for each HTML
What i am doing and trying to achieve is :-
On 1st HTML when i click search button i am storing the values of input field and select field in different variables
What I am trying to achieve is when on search new page loaded I want to use that new variable into my new JavaScript
I have Two HTML files also
here is the code of my file1.html
<form id="formId" action="file2.html">
<div class="container">
<h4>Date:</h4>
<input type="text" id="startdate" name="fromdate" width="276"
placeholder="dd/mm/yyyy" required />
<h4>Outlets:</h4>
<select name="outlet" id="myselect">
<option>ALL</option>
</select>
<div>
<br>
<button id="btn-search" class="btn btn-default" type="submit">
<i class="fa fa-search"></i> Search
</button>
</div>
</div>
</form>
<script type="text/javascript" src="JS/JavaScript1.js"></script>
In This HTML i have a form having one date field and one select field
On clicking submit Button I am Storing the values of date and Outlet into a variable in my JavaScript file which is JavaScript1
**Here is my JavaScript1 file **
$(document).ready(function() {
$("#btn-search").click(function(){
var currentlyClickedOutletform = $("#myselect").find(":selected")[0].textContent;
var currentlyClickedStartdateform= $("#startdate").val();
$.ajax({
url : "LinkReportMain",
method : "POST",
data : {
Outletlink : currentlyClickedOutletform,
Fromdatelink : currentlyClickedStartdateform,
},
});
});
});
var currentlyClickedOutletform and var currentlyClickedStartdateform are the two values i want to use in my new JavaScript file which is JavaScript2
my file2.html is
in this file i am just populating an HTML table so i only have an div tag inside
<div id="tbl"></div>
<script type="text/javascript" src="JS/JavaScript1.js"></script>
<script type="text/javascript" src="JS/JavaScript2.js"></script>
And finally my JavaScript2 is
in this file I want to use the values of first Javascript file
$(document).ready(function() {
alert(currentlyClickedOutletform)
$('.loader').show();
$('.overlay').show();
$.ajax({
url: "LinkReportMain",
method: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
fromdate: $("#startdate").val(),
todate: $("#enddate").val(),
outlet: $("#all").val()
},
success: function(data) {
let formatedData = formatData(data);
renderTable(formatedData);
$('.loader').hide();
$('.overlay').hide();
}
});
});
NOTE to see the code of JavaScript2 file please see the snippet its not working but my code was not getting formatted so I have put that into snippet
So what I am trying to achieve is to use the Variable of JavaScript1 into JavaScript2
i am doing it right but its not working any one out here who can guide em please, it would be very helpfull
Without localStorage
First set type="button" of you search button or prevent form submit by e.preventDefault(); on click event.
$("#btn-search").click(function(){
e.preventDefault();
// your other code
//code to redirect to another html page
var queryString = "?para1=" + currentlyClickedOutletform + "&para2=" + currentlyClickedStartdateform;
window.location.href = "page2.html" + queryString;
})
for other page script:
var queryString = decodeURIComponent(window.location.search);
queryString = queryString.substring(1);
var oldParam = queryString.split("&");
var param1 = oldParam[0];
var param2 = oldParam[1];
Now you can use param1 and param2.
**localStorage ** :
in first page store object :
localStorage.setItem("outletFrom",currentlyClickedOutletform);
localStorage.setItem("startDate",currentlyClickedStartdateform);
in seond page get data:
var currentlyClickedOutletform = localStorage.getItem("outletFrom");
var currentlyClickedStartdateform= localStorage.getItem("startDate");

openweathermap weather data by zip code not working?

i need to make it so that when a zip code is typed into the box and the submit button is clicked, the name of the city shows up under it. when i click the button after putting a zip code the city name doesn't show up. it says the error is that wallOfText is not a function but i'm not sure how to fix it. any help would be appreciated!! here's the code:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
Enter your zip code:<br><input type="text" id="zipBox" name="zipCode"><br><br>
<button onclick="weatherFunction()">Submit</button>
<p id="result"></p>
<script>
function weatherFunction() {
var zip = document.getElementById("zipBox").value;
jQuery(document).ready(function ($) {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?zip=" +zip+ ",us&appid=b3456f9acbfa64fc4495e6696ecdc9a5",
dataType: "jsonp",
success: function (wallOfText) {
city = wallOfText("name");
if (zip != null) {
document.getElementById("result").innerHTML = wallOfText;
}
}
});
});
}
</script>
</body>
</html>
The issue you have is that you're attempting to call wallOfText like it's a function, when in fact it's the object which has been deserialised from the response of the AJAX call. As such, you need to access the object's name property to set the city variable, then use that to set the text() of the #result element.
Note that the document.ready handler within the function is redundant, and you should be doing the zip value validation before you make the request. I also updated the logic to use jQuery to bind the event handler on the button instead of the outdated onclick attribute. Try this:
jQuery(function() {
$('#send').click(function() {
var zip = $("#zipBox").val();
if (zip !== '') {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?zip=" + zip + ",us&appid=b3456f9acbfa64fc4495e6696ecdc9a5",
dataType: "jsonp",
success: function(wallOfText) {
var city = wallOfText.name;
$("#result").text(city);
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Enter your zip code:<br>
<input type="text" id="zipBox" name="zipCode" value="90210" /><br /><br />
<button type="button" id="send">Submit</button>
<p id="result"></p>

Draw bar graph using javascript

I am trying to draw a bar graph using the values returned from server using jQuery. I use the following code,
I try to draw graph using the values in the variable data_list, the issue is the graph draws first with empty values the I got values from server.
I am a newbie to Javascript and jQuery. Thanks in advance.
<html>
<head>
<title>the title</title>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#datepicker1" ).datepicker();
$( "#datepicker2" ).datepicker();
});
</script>
<script type="text/javascript" language="javascript">
var data_list
$(document).ready(function() {
$.get('/api/', function(data) {
data_list = data;
alert(data_list); // alert work second
});
});
alert('test') // first this alert work
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(data_list);
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<form>
<p>Date1: <input type="text" id="datepicker1"></p>
<p>Date2: <input type="text" id="datepicker2"></p>
</form>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
There are two parts in yout JS code. The first is loading the chart data from your API with an AJAX request. The second starts the chart library and attach the data in this line:
var data = google.visualization.arrayToDataTable(data_list);
The problem is the ajax request is asynchronous and the data is not loaded yet when you attach that data. The data_list var will be avaliable when the AJAX request finishes and not when the page is loaded. In other words, you must separated the initialization of the chart and the data attach to it, or simply: init the graph, load the data and set it to the chart when the AJAX request is done. A simple example with your code (not tested) could be:
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
$(document).ready(function() {
$.get('/api/', function(data) {
data_list = data;
var data = google.visualization.arrayToDataTable(data_list);
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
});
}
Remember this code is not tested, it ilustrates the idea of the correct initialization:
- Load Google Chart Library
- Load the data
- When the data is loaded, init the concrete chart
The asynchronous load adds some complexity to the code, but are the base of programming in JavaScript with AJAX and DOM events. Another option, more readable and simple, is to use jquery deferred objects and promises. More on deferred and promises:
- http://api.jquery.com/category/deferred-object/
- http://www.html5rocks.com/en/tutorials/es6/promises/?redirect_from_locale=es

jQuery AJAX POST; Not posting

I'm fairly certain the issue I'm having is related to the jQuery's $.ajax({...}); function . When printing the array in PHP i get Notice: Undefined index.
I'd sincerely appreciate it if i could get some advice here.
<script>
$(document).ready(function(){
$("#submit").click(function() {
var platform_var = $('input[name="platform"]').val();
var bandwidth_var = $("#bandwidth-widget").val();
alert(bandwidth_var); // Returns the array as an alert.
$.ajax({
url: "index.php",
type: "POST",
data: {
platform_var: platform_var,
bandwidth_var: bandwidth_var
}
});
});
});
</script>
<?php
print_r($_POST['platform_var']);
?>
Demo (w/o PHP)
You need to assign the values to the variables on document load.
$(document).ready(function() {
platform_var = $('input[name="platform"]').val();
bandwidth_var = $("#bandwidth-widget").val();
});
EDIT: if the values are not instanciated on document load, you need to assign them when they actually have the correct value, just before you do the Ajax request.
$(document).on('submit', '#compare', function(e) {
var platform_var = $('input[name="platform"]').val();
var bandwidth_var = $("#bandwidth-widget").val();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: {
platform: platform_var,
bandwidth: bandwidth_var
}
});
});
Currently, you are assigning them before the values actually exists.
Hope this helps.
Your have two problems in your code:
The selector is wrong - you're searching for an input with the name attribute which equals to platform and in the html you have an array input with the name platform[]. Therefore it will not find any matching inputs, which is why the var platform_var is undefined or null.
To fetch the checked checkboxes, you need to add :checked to the selector, otherwise jQuery will return all of the checkboxes regardless of their checkbox status.
To fix this, simply change
var platform_var = $('input[name="platform"]').val();
to
var platform_var = $('input[name="platform[]"]:checked').map(function(){return $(this).val();}).get();
Also, have in mind that in your php script, the $_POST['platform'] variable will be an array.
I would advice you to have a look at the jQuery API documentation to further understand how the selectors work.
Here is the edited fiddle.
Edit:
I've code I've added below confirms that the code in the fiddle is working fine. Apparently you are having trouble with your own php code rather than your JavaScript.
I believe you should sit down and check your code.
<?php
// Save everything here in a file called "test.php"
if (isset($_POST) && !empty($_POST)){
print_r($_POST);
exit();
}
?>
<html>
<head>
<title>Testing page</title>
<link rel="stylesheet" type="text/css" href="http://www.hostingarchive.com/wp-content/themes/My-theme/assets/styles/jquery.selectBox.css"/>
<link rel="stylesheet" type="text/css" href="http://www.hostingarchive.com/wp-content/themes/My-theme/assets/styles/jquery.nouislider.min.css"/>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://www.hostingarchive.com/wp-content/themes/My-theme/assets/scripts/jquery.selectBox.js"></script>
<script type="text/javascript" src="http://www.hostingarchive.com/wp-content/themes/My-theme/assets/scripts/jquery.nouislider.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.cmp-select').selectBox();
$("#price-widget").noUiSlider({
range: [5, 150], start: [5, 75], step: [5], connect: true, direction: 'ltr', serialization: {
mark: '.', resolution: 1, to: [
[$("#low-price"), 'html'],
[$('#high-price'), 'html']
]
}
});
$("#bandwidth-widget").noUiSlider({
range: [0, 2000], start: [10, 1000], step: [10], connect: true, direction: 'ltr', serialization: {
mark: '.', resolution: 1, to: [
[$("#low-bandwidth"), 'html'],
[$('#high-bandwidth'), 'html']
]
}
});
$("#submit").click(function () {
var platform_var = $('input[name="platform[]"]:checked').map(function () {
return $(this).val();
}).get();
var bandwidth_var = $("#bandwidth-widget").val();
alert(bandwidth_var);
console.log(platform_var);
console.log(bandwidth_var);
$.ajax({
url : "test.php",
type: "POST",
data: {
platform_var : platform_var,
bandwidth_var: bandwidth_var
}
});
});
});
</script>
</head>
<body>
<div id="compare">
<h3>Platform</h3>
<input name="platform[]" type="checkbox" value="shared" checked="checked">Shared</input>
<input name="platform[]" type="checkbox" value="dedicated">Dedicated</input>
<input name="platform[]" type="checkbox" value="cdn">CDN</input>
<input name="platform[]" type="checkbox" value="vps">VPS</input>
<input name="platform[]" type="checkbox" value="vds">VDS</input>
<h3>Bandwidth</h3>
<div id="bandwidth-slide">
<p class="inline-block"><span id="low-bandwidth"></span><span><small>GB</small></span></p>
<div class="inline-block" id="bandwidth-widget"></div>
<p class="inline-block"><span id="high-bandwidth"></span><span><small>GB</small></span></p>
</div>
<h3>Price</h3>
<div id="pricing-slide" class="clearfix">
<p class="inline-block">$<span id="low-price"></span></p>
<div class="inline-block" id="price-widget"></div>
<p class="inline-block">$<span id="high-price"></span><span>/mo</span></p>
</div>
<input type="submit" id="submit" value="enter">
</div>
</body>
</html>

How do you use $('document').ready(function()) in jQuery?

I have a piece of code that is working fine in IE, but it doesn’t run in Firefox. I think the problem is that I have not been able to implement $('document').ready(function). The structure of my json is like [{"options":"smart_exp"},{"options":"user_intf"},{"options":"blahblah"}].
I will be very thankful if someone can see my code & help me in correctly implementing it. Here is my code:
<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2
/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$.getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
$.each(jsonData, function (i, j) {
document.form1.fruits.options[i] = new Option(j.options);
});});
});
</script></head>
<body><form name="form1">
My favourite fruit is :
<select name="fruits" id="fruits" /></form></body>
</html>
Short version (suggested by meeger): don't use single quotes around document.
document is a variable that comes with JavaScript (at least in the browser context). Instead, try the following for the relevant line.
$(document).ready(function() {
You'll also want to take the onLoad attribute off of the body tag, else it will run twice.
Just run $(document).ready(function() {doStuff}). This will automatically run when the document is ready.
It's best practice, at least in my opinion, that you don't put any events in the html itself. This way you separate the structure of an html document from it's behavior. Instead attach events in the $(document).ready function.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("http://localhost/conn_mysql.php", function (jsonData) {
var selectElem = $('#fruits');
for(var i = 0; i < jsonData.length; i++) {
selectElem.append($('<option>').html(jsonData[i].options));
}
});
});
</script>
</head>
<body>
<form name="form1">
My favourite fruit is :
<select name="fruits" id="fruits" />
</form>
</body>
</html>
EDIT:
I tested with the following and mocked the json object since I can't make that call myself.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var jsonData = JSON.parse('[{"options":"smart_exp"},{"options":"user_intf"},{"options":"blahblah"}]');
var selectElem = $('#fruits');
for(var i = 0; i < jsonData.length; i++) {
selectElem.append($('<option>').html(jsonData[i].options));
}
});
</script>
</head>
<body>
<form name="form1">
My favourite fruit is :
<select name="fruits" id="fruits" />
</form>
</body>
</html>
Here it is in all its glory. The shorthand, awesome version:
UPDATED
<script type="text/javascript" language="javascript">
$(function() {
$.getJSON("http://localhost/conn_mysql.php", function (jsonData) {
var cacheFruits = $('#fruits'),
cacheOption = $(document.createElement('option'));
$.each(jsonData, function (i, j) {
cacheFruits.append(
cacheOption.clone().attr('value', j.options).html(j.options)
);
});
});
});
</script>
Of course, I don't know what your JSON structure is, so you may need to play around with the append section of the code.
There should be no reason why the above would not work.
You do not need quotes around document. Once the page has completely loaded, it will start executing whatever you have defined in ready()
$(document).ready(function() {
$(this).getJSON("http://localhost/conn_mysql.php", function (jsonData) {
$(this).each(jsonData, function (i, j) {
document.form1.fruits.options[i] = new Option(j.options);
});
});
});
Try this, your json data should be in this format:
[{'text':'sometext','value':'somevalue'},{'text':'sometext','value':'somevalue'}];
$(document).ready(function() {
$(this).getJSON("http://localhost/conn_mysql.php", function (jsonData) {
var options = [];
$.each(jsonData, function (i, j) {
options.push('<option value="' + j.value + '">' + j.text + '</option>');
});
$('#fruits').html( options.join(''));
});
});
Please note that there may be an encoding/escaping issues here.
Make sure that you escape the text properly from the server side.
htmlentities, htmlspecialchars can help you with that.
This should work in most browsers

Categories