I'm creating a website that grabs weather information based on the location entered by the user. At the moment there are some features on the page with no functionality, it is still a work in progress. I apologies for the sloppy code.
I have 9 checkboxes at the top of my form that have the info that should be displayed and I'm not sure of the best method to edit the output accordingly.
In my JS file there is a block that grabs all of the relevant weather data and assigns it to variables. These variables are then used to generate a <p> element containing all of this info. How can I edit it to only display the variables that are selected via checkboxes?
$(document).ready(function() {
var inputType = 1;
$("#Radio1").click(function() {
$("#lbl1").text("City Name:");
$("#lbl2").text("Country Code:");
$("#Firstbox").removeAttr("min max step");
$("#Secondbox").removeAttr("min max step");
document.getElementById('Firstbox').value = '';
document.getElementById('Secondbox').value = '';
$("#Firstbox").attr({
"type": "text",
"pattern": "[a-zA-Z]{2,}",
"placeholder": "Regina"
});
$("#Secondbox").attr({
"type": "text",
"pattern": "[a-zA-Z]{2}",
"placeholder": "ca"
});
inputType = 1;
});
$("#Radio2").click(function() {
$("#lbl1").text("Postal Code:");
$("#lbl2").text("Country Code:");
$("#Firstbox").removeAttr("min max step");
$("#Secondbox").removeAttr("min max step");
document.getElementById('Firstbox').value = '';
document.getElementById('Secondbox').value = '';
$("#Firstbox").attr({
"type": "text",
"pattern": "[A-Z][0-9][A-Z]",
"placeholder": "S4X"
});
$("#Secondbox").attr({
"type": "text",
"pattern": "[a-zA-Z]{2}",
"placeholder": "ca"
});
inputType = 2;
});
$("#Radio3").click(function() {
$("#lbl1").text("Latitude:");
$("#lbl2").text("Longitude:");
$("#Firstbox").removeAttr("pattern");
$("#Secondbox").removeAttr("pattern");
document.getElementById('Firstbox').value = '';
document.getElementById('Secondbox').value = '';
$("#Firstbox").attr({
"type": "number",
"min": "-90",
"max": "90",
"step": "any",
"placeholder": "50.4"
});
$("#Secondbox").attr({
"type": "number",
"min": "-180",
"max": "180",
"step": "any",
"placeholder": "-105.5"
});
inputType = 3;
});
$("#SearchButton").click(function() {
if (checkValidity()) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var SearchResponse = this.responseText;
var obj = JSON.parse(SearchResponse);
var city_name = obj["name"];
var country_name = obj["sys"]["country"];
var longitude = obj["coord"]["lon"];
var latitude = obj["coord"]["lat"];
var weather_description = obj["weather"][0]["description"];
var temp = obj["main"]["temp"] - 273.15;
var pressure = obj["main"]["pressure"];
var humidity = obj["main"]["humidity"];
var wind_speed = obj["wind"]["speed"];
var wind_direction = obj["wind"]["deg"];
var sunrise = new Date(obj["sys"]["sunrise"] * 1000);
var sunset = new Date(obj["sys"]["sunset"] * 1000);
var SearchResultsHTML = "City: " + city_name + "<br />" +
"Country: " + country_name + "<br />" +
"Longitude: " + longitude + "<br />" +
"Latitude: " + latitude + "<br />" +
"Weather: " + weather_description + "<br />" +
"Temperature: " + temp + "<br />" +
"Pressure: " + pressure + "<br />" +
"Humidity: " + humidity + "<br />" +
"Wind Speed: " + wind_speed + "<br />" +
"Wind Direction: " + wind_direction + "<br />" +
"Sunrise: " + sunrise.toLocaleTimeString() + "<br />" +
"Sunset: " + sunset.toLocaleTimeString() + "<br />";
$("#SearchResults").html(SearchResultsHTML);
}
}
var Firstbox = $("#Firstbox").val();
var Secondbox = $("#Secondbox").val();
var apiKey = "52453f34dee0d65b1a41a02656142c6b";
if (inputType == 1) {
var SearchString = "https://api.openweathermap.org/data/2.5/weather" +
"?q=" + Firstbox + "," + Secondbox +
"&APPID=" + apiKey;
} else if (inputType == 2) {
var SearchString = "http://api.openweathermap.org/data/2.5/weather" +
"?zip=" + Firstbox + "," + Secondbox +
"&APPID=" + apiKey;
} else if (inputType == 3) {
var SearchString = "http://api.openweathermap.org/data/2.5/weather" +
"?lat=" + Firstbox + "&lon=" + Secondbox +
"&APPID=" + apiKey;
}
xhttp.open("GET", SearchString, true);
xhttp.send();
}
});
function displayError() {
var first = document.getElementById('Firstbox');
var second = document.getElementById('Secondbox');
if (first.validity.valid) {
if (inputType == 1 || inputType == 2) {
alert("Country code must be 2 characters in length.");
} else {
alert("Longitude must be between -180 and 180");
}
} else {
if (inputType == 1) {
alert("City name must be longer than 1 character.");
} else if (inputType == 2) {
alert("Postal code must be 3 characters in length, following the format 'S4X'");
} else {
alert("Latitude must be between -90 and 90");
}
}
}
function checkValidity() {
var first = document.getElementById('Firstbox');
var second = document.getElementById('Secondbox');
if (first.validity.valid && second.validity.valid) {
return true;
} else {
displayError();
return false;
}
}
function checksSelected() {
}
});
.validated:valid {
background-color: #BDF0A8;
}
.validated:invalid {
background-color: #FAC3C9;
}
.row {
margin-bottom: 10px;
}
.ticksel {
border: solid black 1px;
}
tr,
td {
border: solid black 1px;
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
<title>Final Project</title>
<link rel="stylesheet" type="text/css" href="weather.css">
<form id="searchForm" method="POST" action="URL">
<div class="row col-md-12">
<h2>OpenWeatherMap Weather Search</h2>
</div>
<div class="row">
<div class="col-md-6">
<h4>Search by:</h4>
<input id="Radio1" name="searchBy" type="radio" checked /> City Name<br/>
<input id="Radio2" name="searchBy" type="radio"> Postal Code<br/>
<input id="Radio3" name="searchBy" type="radio" /> Latitude / Longitude<br/>
</div>
<div class="col-md-6">
<h4>Show in search results:</h4>
<div class="row">
<div class="col ticksel"><input type="checkbox" checked id="" value=""> Longitude</div>
<div class="col ticksel"><input type="checkbox" checked id="" value=""> Latitude</div>
<div class="col ticksel"><input type="checkbox" checked id="" value=""> Temperature</div>
</div>
<div class="row">
<div class="col ticksel"><input type="checkbox" checked id="" value=""> Pressure</div>
<div class="col ticksel"><input type="checkbox" checked id="" value=""> Humidity</div>
<div class="col ticksel"><input type="checkbox" checked id="" value=""> Wind Speed</div>
</div>
<div class="row">
<div class="col ticksel"><input type="checkbox" checked id="" value=""> Wind Direction</div>
<div class="col ticksel"><input type="checkbox" checked id="" value=""> Sunrise</div>
<div class="col ticksel"><input type="checkbox" checked id="" value=""> Sunset</div>
</div>
</div>
</div>
<div class="row col-md-12">
<label id="lbl1">City Name:</label><input id="Firstbox" class="validated" type="text" required pattern=".{2,}" placeholder="Regina" />
<label id="lbl2">Country Code:</label><input id="Secondbox" class="validated" type="text" required pattern="[a-zA-Z]{2}" placeholder="ca" />
<input id="SearchButton" type="button" value="Search" />
</div>
</form>
<div class="row col-md-12">
<h4>Current Weather</h4>
</div>
<div class="row col-md-12">
<p id="SearchResults"></p>
</div>
<div class="row col-md-12">
<table width="100%">
<thead>
<tr>
<th>City</th>
<th>Country</th>
<th>Longitude</th>
<th>Latitude</th>
<th>Weather</th>
<th>Temperature</th>
<th>Pressure</th>
<th>Humidity</th>
<th>Wind Speed</th>
<th>Wind Direction</th>
<th>Sunrise</th>
<th>Sunst</th>
<th><a class="deleteAll" href="#">Clear Log</a></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
Here is a version that will take the checked boxes and show their corresponding values
I changed your xmlhttp to getJSON
You can do
let SearchResultsHTML = []
SearchResultsHTML.push("City: " + city_name);
SearchResultsHTML.push("Country: " + country_name);
SearchResultsHTML.push("Weather: " + weather_description);
if ($("#long").is(":checked")) SearchResultsHTML.push("Longitude: " + longitude);
if ($("#lat").is(":checked")) SearchResultsHTML.push("Latitude: " + latitude);
if ($("#temp").is(":checked")) SearchResultsHTML.push("Temperature: " + temp);
if ($("#pres").is(":checked")) SearchResultsHTML.push("Pressure: " + pressure);
if ($("#hum").is(":checked")) SearchResultsHTML.push("Humidity: " + humidity);
if ($("#ws").is(":checked")) SearchResultsHTML.push("Wind Speed: " + wind_speed);
if ($("#wd").is(":checked")) SearchResultsHTML.push("Wind Direction: " + wind_direction);
if ($("#sunup").is(":checked")) SearchResultsHTML.push("Sunrise: " + sunrise.toLocaleTimeString());
if ($("#sundown").is(":checked")) SearchResultsHTML.push("Sunset: " + sunset.toLocaleTimeString());
$("#SearchResults").html(SearchResultsHTML.join("<br/>"));
or more elegantly add a span and toggle this at show time or even after
let SearchResultsHTML = []
SearchResultsHTML.push("City: " + city_name);
SearchResultsHTML.push("Country: " + country_name);
SearchResultsHTML.push("Weather: " + weather_description);
SearchResultsHTML.push("<span id='longSpan'>Longitude: " + longitude + "</span>");
SearchResultsHTML.push("<span id='latSpan'>Latitude: " + latitude + "</span>");
SearchResultsHTML.push("<span id='tempSpan'>Temperature: " + temp + "</span>");
SearchResultsHTML.push("<span id='pressSpan'>Pressure: " + pressure + "</span>");
SearchResultsHTML.push("<span id='humSpan'>Humidity: " + humidity + "</span>");
SearchResultsHTML.push("<span id='wsSpan'>Wind Speed: " + wind_speed + "</span>");
SearchResultsHTML.push("<span id='wdSpan'>Wind Direction: " + wind_direction + "</span>");
SearchResultsHTML.push("<span id='sunupSpan'>Sunrise: " + sunrise.toLocaleTimeString + "</span>");
SearchResultsHTML.push("<span id='sundownSpan'>Sunset: " + sunset.toLocaleTimeString() + "</span>");
$("#SearchResults").html(SearchResultsHTML.join("<br/>"));
showSpans();
})
}
using
$(".ticksel").on("change", showSpans);
function showSpans() {
$(".ticksel input").each(function() {
const id = this.id;
const checked = this.checked;
if (id) {
const $span = $("#" + id + "span");
if ($span) $span.toggle(checked);
}
})
}
$(document).ready(function() {
var inputType = 1;
$("#Radio1").click(function() {
$("#lbl1").text("City Name:");
$("#lbl2").text("Country Code:");
$("#Firstbox").removeAttr("min max step");
$("#Secondbox").removeAttr("min max step");
document.getElementById('Firstbox').value = '';
document.getElementById('Secondbox').value = '';
$("#Firstbox").attr({
"type": "text",
"pattern": "[a-zA-Z]{2,}",
"placeholder": "Regina"
});
$("#Secondbox").attr({
"type": "text",
"pattern": "[a-zA-Z]{2}",
"placeholder": "ca"
});
inputType = 1;
});
$("#Radio2").click(function() {
$("#lbl1").text("Postal Code:");
$("#lbl2").text("Country Code:");
$("#Firstbox").removeAttr("min max step");
$("#Secondbox").removeAttr("min max step");
document.getElementById('Firstbox').value = '';
document.getElementById('Secondbox').value = '';
$("#Firstbox").attr({
"type": "text",
"pattern": "[A-Z][0-9][A-Z]",
"placeholder": "S4X"
});
$("#Secondbox").attr({
"type": "text",
"pattern": "[a-zA-Z]{2}",
"placeholder": "ca"
});
inputType = 2;
});
$("#Radio3").click(function() {
$("#lbl1").text("Latitude:");
$("#lbl2").text("Longitude:");
$("#Firstbox").removeAttr("pattern");
$("#Secondbox").removeAttr("pattern");
document.getElementById('Firstbox').value = '';
document.getElementById('Secondbox').value = '';
$("#Firstbox").attr({
"type": "number",
"min": "-90",
"max": "90",
"step": "any",
"placeholder": "50.4"
});
$("#Secondbox").attr({
"type": "number",
"min": "-180",
"max": "180",
"step": "any",
"placeholder": "-105.5"
});
inputType = 3;
});
$("#SearchButton").click(function() {
if (checkValidity()) {
var Firstbox = $("#Firstbox").val();
var Secondbox = $("#Secondbox").val();
var apiKey = "52453f34dee0d65b1a41a02656142c6b";
if (inputType == 1) {
var SearchString = "https://api.openweathermap.org/data/2.5/weather" +
"?q=" + Firstbox + "," + Secondbox +
"&APPID=" + apiKey;
} else if (inputType == 2) {
var SearchString = "http://api.openweathermap.org/data/2.5/weather" +
"?zip=" + Firstbox + "," + Secondbox +
"&APPID=" + apiKey;
} else if (inputType == 3) {
var SearchString = "http://api.openweathermap.org/data/2.5/weather" +
"?lat=" + Firstbox + "&lon=" + Secondbox +
"&APPID=" + apiKey;
}
$.getJSON(SearchString, function(obj) {
var city_name = obj["name"];
var country_name = obj["sys"]["country"];
var longitude = obj["coord"]["lon"];
var latitude = obj["coord"]["lat"];
var weather_description = obj["weather"][0]["description"];
var temp = obj["main"]["temp"] - 273.15;
var pressure = obj["main"]["pressure"];
var humidity = obj["main"]["humidity"];
var wind_speed = obj["wind"]["speed"];
var wind_direction = obj["wind"]["deg"];
var sunrise = new Date(obj["sys"]["sunrise"] * 1000);
var sunset = new Date(obj["sys"]["sunset"] * 1000);
let SearchResultsHTML = []
SearchResultsHTML.push("City: " + city_name);
SearchResultsHTML.push("Country: " + country_name);
SearchResultsHTML.push("Weather: " + weather_description);
SearchResultsHTML.push("<span id='longSpan'>Longitude: " + longitude + "</span>");
SearchResultsHTML.push("<span id='latSpan'>Latitude: " + latitude + "</span>");
SearchResultsHTML.push("<span id='tempSpan'>Temperature: " + temp + "</span>");
SearchResultsHTML.push("<span id='pressSpan'>Pressure: " + pressure + "</span>");
SearchResultsHTML.push("<span id='humSpan'>Humidity: " + humidity + "</span>");
SearchResultsHTML.push("<span id='wsSpan'>Wind Speed: " + wind_speed + "</span>");
SearchResultsHTML.push("<span id='wdSpan'>Wind Direction: " + wind_direction + "</span>");
SearchResultsHTML.push("<span id='sunupSpan'>Sunrise: " + sunrise.toLocaleTimeString + "</span>");
SearchResultsHTML.push("<span id='sundownSpan'>Sunset: " + sunset.toLocaleTimeString() + "</span>");
$("#SearchResults").html(SearchResultsHTML.join("<br/>"));
showSpans();
})
}
});
$(".ticksel").on("change", showSpans);
function showSpans() {
$(".ticksel input").each(function() {
const id = this.id;
const checked = this.checked;
if (id) {
const $span = $("#" + id + "span");
if ($span) $span.toggle(checked);
}
})
}
function displayError() {
var first = document.getElementById('Firstbox');
var second = document.getElementById('Secondbox');
if (first.validity.valid) {
if (inputType == 1 || inputType == 2) {
alert("Country code must be 2 characters in length.");
} else {
alert("Longitude must be between -180 and 180");
}
} else {
if (inputType == 1) {
alert("City name must be longer than 1 character.");
} else if (inputType == 2) {
alert("Postal code must be 3 characters in length, following the format 'S4X'");
} else {
alert("Latitude must be between -90 and 90");
}
}
}
function checkValidity() {
var first = document.getElementById('Firstbox');
var second = document.getElementById('Secondbox');
if (first.validity.valid && second.validity.valid) {
return true;
} else {
displayError();
return false;
}
}
function checksSelected() {
}
});
.validated:valid {
background-color: #BDF0A8;
}
.validated:invalid {
background-color: #FAC3C9;
}
.row {
margin-bottom: 10px;
}
.ticksel {
border: solid black 1px;
}
tr,
td {
border: solid black 1px;
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
<title>Final Project</title>
<link rel="stylesheet" type="text/css" href="weather.css">
<form id="searchForm" method="POST" action="URL">
<div class="row col-md-12">
<h2>OpenWeatherMap Weather Search</h2>
</div>
<div class="row">
<div class="col-md-6">
<h4>Search by:</h4>
<input id="Radio1" name="searchBy" type="radio" checked /> City Name<br/>
<input id="Radio2" name="searchBy" type="radio"> Postal Code<br/>
<input id="Radio3" name="searchBy" type="radio" /> Latitude / Longitude<br/>
</div>
<div class="col-md-6">
<h4>Show in search results:</h4>
<div class="row">
<div class="col ticksel"><input type="checkbox" checked id="long" value="yes"> Longitude</div>
<div class="col ticksel"><input type="checkbox" checked id="lat" value=""> Latitude</div>
<div class="col ticksel"><input type="checkbox" checked id="temp" value=""> Temperature</div>
</div>
<div class="row">
<div class="col ticksel"><input type="checkbox" checked id="press" value=""> Pressure</div>
<div class="col ticksel"><input type="checkbox" checked id="hum" value=""> Humidity</div>
<div class="col ticksel"><input type="checkbox" checked id="ws" value=""> Wind Speed</div>
</div>
<div class="row">
<div class="col ticksel"><input type="checkbox" checked id="wd" value=""> Wind Direction</div>
<div class="col ticksel"><input type="checkbox" checked id="sunup" value=""> Sunrise</div>
<div class="col ticksel"><input type="checkbox" checked id="sundown" value=""> Sunset</div>
</div>
</div>
</div>
<div class="row col-md-12">
<label id="lbl1">City Name:</label><input id="Firstbox" class="validated" type="text" required pattern=".{2,}" placeholder="Regina" />
<label id="lbl2">Country Code:</label><input id="Secondbox" class="validated" type="text" required pattern="[a-zA-Z]{2}" placeholder="ca" />
<input id="SearchButton" type="button" value="Search" />
</div>
</form>
<div class="row col-md-12">
<h4>Current Weather</h4>
</div>
<div class="row col-md-12">
<p id="SearchResults"></p>
</div>
<div class="row col-md-12">
<table width="100%">
<thead>
<tr>
<th>City</th>
<th>Country</th>
<th>Longitude</th>
<th>Latitude</th>
<th>Weather</th>
<th>Temperature</th>
<th>Pressure</th>
<th>Humidity</th>
<th>Wind Speed</th>
<th>Wind Direction</th>
<th>Sunrise</th>
<th>Sunst</th>
<th><a class="deleteAll" href="#">Clear Log</a></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
Related
var checkSum = 0;
var jsonData = {};
var pushData;
var trData = [];
var sumData = [];
var chkArray = [];
countTab2 = 1;
$(".add-customs").click(function() {
customsTable();
});
function customsTable() {
var markup = "<div class='col-md-1'>Custom</div>" +
"<div class='col-md-4'><input id='customReason" +
countTab2 +
"' type='text' value='' class='txt form-control'" +
"name='customReason' path='customReason' /></div>" +
"<div class='col-md-2'><input value='0' type='text' class='txt form-control'" +
"name='customAmount' id='customAmount" +
countTab2 +
"'></div>" +
"<div class='col-md-2'><input value='0' onchange='getCustomTotal();' type='text' class='txt form-control'" +
"name='customPenalty' id='customPenalty" +
countTab2 +
"'></div>" +
"<div class='col-md-1'><span id='customSum" +
countTab2 +
"'>0</span></div>" +
"<div class='col-md-2'></div>";
countTab2++;
$(".custom-table").append(markup);
}
//adding row for VAT
countTab3 = 1;
$(".add-vat").click(function() {
vatTable();
});
function vatTable() {
var markup = "<div class='col-md-1'>VAT</div>" +
"<div class='col-md-4'><input id='vatReason" +
countTab3 +
"' type='text' value='' class='txt1 form-control'" +
"name='vatReason' /></div>" +
"<div class='col-md-2'><input type='text' class='txt1 form-control'" +
"name='vatAmount' value='0' id='vatAmount" +
countTab3 +
"'></div>" +
"<div class='col-md-2'><input type='text' value='0' onchange='getVatTotal();' class='txt1 form-control'" +
"name='vatPenalty' id='vatPenalty" +
countTab3 +
"'></div>" +
"<div class='col-md-1'><span id='vatTotal" +
countTab3 +
"'></span></div>" +
"<div class='col-md-2'></div>";
countTab3++;
$(".vat-table").append(markup);
}
//adding row for Excise
countTab4 = 1;
$(".add-excise").click(function() {
exciseTable();
});
function exciseTable() {
var markup = "<div class='col-md-1'>Excise</div>" +
"<div class='col-md-4'><input id='exciseReason" +
countTab4 +
"' type='text' value='' class='txt2 form-control'" +
"name='exciseReason' /></div>" +
"<div class='col-md-2'><input type='text' class='txt2 form-control'" +
"name='exciseAmount' value='0' id='exciseAmount" +
countTab4 +
"'></div>" +
"<div class='col-md-2'><input type='text' onchange='getExciseTotal();' class='txt2 form-control'" +
"name='excisePenalty' value='0' id='excisePenalty" +
countTab4 +
"'></div>" +
"<div class='col-md-1'><span id='exciseTotal" +
countTab4 +
"'></span></div>" +
"<div class='col-md-2'></div>";
countTab4++;
$(".excise-table").append(markup);
}
customs = [];
function getListCustoms() {
for (i = 0; i < countTab2; i++) {
if ($("#customPenalty" + i).length) {
customs.push({
assessReason: $("#customReason" + i).val(),
assessAmount: $("#customAmount" + i).val(),
assessPenalty: $("#customPenalty" + i).val()
});
}
}
}
function getCustomTotal() {
var customTotal = 0;
getListCustoms();
customs.unshift({
assessReason: $("#customReason").val(),
assessAmount: $("#customAmount").val(),
assessPenalty: $("#customPenalty").val()
});
customTotal = customTotal + parseInt(customs[0].assessAmount) +
parseInt(customs[0].assessPenalty);
for (i = 1; i < customs.length; i++) {
customTotal = customTotal + parseInt(customs[i].assessAmount) +
parseInt(customs[i].assessPenalty);
customRowTotal = 0;
customRowTotal = parseInt($("#customAmount" + i).val()) +
parseInt($("#customPenalty" + i).val());
$("#customSum" + i).html(customRowTotal);
}
getTotalSum();
$('#tot').html(wholeTotal);
}
$("#customPenalty").change(
function() {
totalCustom = 0;
totalCustom = parseInt($("#customAmount").val()) +
parseInt($("#customPenalty").val());
$("#customSum").html(totalCustom);
});
function getVatTotal() {
var vatTotal = 0;
getVatList();
vats.unshift({
assessReason: $("#vatReason").val(),
assessAmount: $("#vatAmount").val(),
assessPenalty: $("#vatPenalty").val()
});
vatTotal = vatTotal + parseInt(vats[0].assessAmount) +
parseInt(vats[0].assessPenalty);
for (i = 1; i < vats.length; i++) {
vatTotal = vatTotal + parseInt(vats[i].assessAmount) +
parseInt(vats[i].assessPenalty);
vatRowTotal = 0;
vatRowTotal = parseInt($("#vatAmount" + i).val()) +
parseInt($("#vatPenalty" + i).val());
$("#vatTotal" + i).html(vatRowTotal);
}
getTotalSum();
$('#tot').html(wholeTotal);
}
$("#vatPenalty").change(
function() {
totalVat = 0;
totalVat = parseInt($("#vatAmount").val()) +
parseInt($("#vatPenalty").val());
$("#vatTotal").html(totalVat);
});
vats = [];
function getVatList() {
for (i = 0; i < countTab3; i++) {
if ($("#vatPenalty" + i).length) {
vats.push({
assessReason: $("#vatReason" + i).val(),
assessAmount: $("#vatAmount" + i).val(),
assessPenalty: $("#vatPenalty" + i).val()
});
}
}
}
excises = [];
function getExciseList() {
for (i = 0; i < countTab4; i++) {
if ($("#excisePenalty" + i).length) {
excises.push({
assessReason: $("#exciseReason" + i).val(),
assessAmount: $("#exciseAmount" + i).val(),
assessPenalty: $("#excisePenalty" + i).val()
});
}
}
}
$("#excisePenalty").change(
function() {
totalExcise = 0;
totalExcise = parseInt($("#exciseAmount").val()) +
parseInt($("#excisePenalty").val());
/* $("#tot").html(totalVat+totalCustom); */
$("#exciseTotal").html(totalExcise);
});
function getExciseTotal() {
var exciseTotal = 0;
getExciseList();
excises.unshift({
assessReason: $("#exciseReason").val(),
assessAmount: $("#exciseAmount").val(),
assessPenalty: $("#excisePenalty").val()
});
exciseTotal = exciseTotal + parseInt(excises[0].assessAmount) +
parseInt(excises[0].assessPenalty);
for (i = 1; i < excises.length; i++) {
exciseTotal = exciseTotal + parseInt(excises[i].assessAmount) +
parseInt(excises[i].assessPenalty);
exciseRowTotal = 0;
exciseRowTotal = parseInt($("#exciseAmount" + i).val()) +
parseInt($("#excisePenalty" + i).val());
$("#exciseTotal" + i).html(exciseRowTotal);
}
getTotalSum();
$('#tot').html(wholeTotal);
}
function getTotalSum() {
wholeTotal = 0;
var allList = customs.concat(vats, excises);
for (i = 0; i < allList.length; i++) {
wholeTotal += parseInt(allList[i].assessAmount) + parseInt(allList[i].assessPenalty);
}
console.log(wholeTotal);
}
//submit method now
$("form").submit(function() {
event.preventDefault();
getTotalSum();
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<form>
<div class="col-md-12" style="float: none;">
<!-- <button onclick="myFunction()" class="pull-right">+</button> -->
<div style="margin-bottom: 30px;">
<div class="form-group row">
<div class="col-md-1"></div>
<div class="col-md-4">
<label>Reason</label>
</div>
<div class="col-md-2">
<label>Amount</label>
</div>
<div class="col-md-2">
<label>Penalty</label>
</div>
<div class="col-md-1">Total</div>
<div class="col-md-2">Action</div>
</div>
<div class="custom-table row">
<div class="col-md-1">
<label>Customs</label>
</div>
<div class="col-md-4">
<input type="text" class="form-control" id="customReason" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt" id="customAmount" value="0" name="abc" min="0" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt" id="customPenalty" onchange="getCustomTotal();" value="0" name="abc" min="0" />
</div>
<div class="col-md-1">
<span id="customSum">0</span>
</div>
<div class="col-md-2">
<button class="add-customs">+</button>
</div>
</div>
<div class="vat-table row">
<div class="col-md-1">
<label>VAT</label>
</div>
<div class="col-md-4">
<input type="text" class="form-control" id="vatReason" name="vatReason" />
</div>
<div class="col-md-2">
<input type="text" class="form-control txt1" id="vatAmount" value="0" name="vatAmount" min="0" />
</div>
<div class="col-md-2">
<input type="text" class="form-control txt1" id="vatPenalty" value="0" name="vatPenalty" onchange="getVatTotal();" min="0" />
</div>
<div class="col-md-1">
<span id="vatTotal">0</span>
</div>
<div class="col-md-2">
<button class="add-vat">+</button>
</div>
</div>
<div class="excise-table row">
<div class="col-md-1">
<label>Excise</label>
</div>
<div class="col-md-4">
<input type="text" class="form-control" id="exciseReason" name="exciseReason" />
</div>
<div class="col-md-2">
<input type="text" class="form-control txt2" id="exciseAmount" value="0" name="exciseAmount" min="0" />
</div>
<div class="col-md-2">
<input type="text" class="form-control txt2" id="excisePenalty" value="0" name="excisePenalty" onchange="getExciseTotal();" min="0" />
</div>
<div class="col-md-1">
<span id="exciseTotal">0</span>
</div>
<div class="col-md-2">
<button class="add-excise">+</button>
</div>
<div class="col-md-1 pull-right">
<label>Total:</label> <b> <span id="tot">0</span></b>
</div>
</div>
</div>
<button type="submit" class="btn btn-success pull-right">Submit</button>
</div>
</form>
I have the form looking like this:
The total of the respective row is shown successfully but the total of all the input field is not showing as expected. And when I clear one input field then its data is not subtracted from the total. I am not able to get the correct sum of all the input fields which are dynamic. How can I make the changes here?
UPDATE:
when I am typing some data in "amount" and "penalty" then the total is also coming just after Penalty "column".
Can I pass those individual Total to the array like
{
assessmentType: "PRE",
assessCatID: 1,
assessReason: "11",
assessAmount: "22",
assessPenalty: "33"
}
I need a new field customOneRowTotal:22+33 and need to be inserted in array
Updated code(December 9,2018):
I have a AJAX calling a API and it has successfully arrived in my console:
var table = $('#nepal')
.DataTable(
{
"processing" : true,
"ajax" : {
"url" : A_PAGE_CONTEXT_PATH
+ "/form/api/getSelectionByAssessmentOrNonAssessment",
dataSrc : ''
},
"columns" : [ {
"data" : "selectionId"
}, {
"data" : "selectionDate"
}, {
"data" : "selectedBy"
}, {
"data" : "eximPanNo"
}, {
"data" : "eximPanName"
}, {
"data" : "eximPanAddr"
}, {
"data" : "eximPanPhone"
}, {
"data" : "selectionType"
}, {
"data" : "auditorGroupName"
} ]
});
Data is shown recently on Datatable and when I click on the single row then it is selected and populated as:
The JSON Data coming through this Ajax Call is:(We need assessCatAmount data recently now from this whole JSON data)
{
"selectionId":1,
"selectionDate":"2075-08-15",
"selectedBy":"Department",
"eximPanNo":1234,
"eximPanName":"PCS",
"eximPanNameEng":"PCS",
"eximPanAddr":"KAPAN",
"eximPanAddrEng":"PCS",
"eximPanPhone":9843709166,
"selectionType":"consignment\r\n",
"consignmentNo":122,
"consignmentDate":"2018-2-6",
"productName":null,
"selectionFromDate":"2018-11-30",
"selectionToDate":"2018-11-28",
"agentNo":3,
"selectionStatus":"1",
"entryBy":"1",
"entryDate":"2018-11-25 11:25:11",
"rStatus":"1",
"custOfficeId":1,
"selectionAudit":null,
"letter":null,
"auditorGroupName":null,
"document":null,
"assessment":{
"assessmentNo":1,
"assessmentType":"PRE",
"offCode":null,
"assessmentDate":"2071",
"assessmentBy":null,
"totalAssessment":null,
"selectionId":1,
"assSec":null,
"assRule":null,
"parentAssessmentId":null,
"appealId":445,
"demandNo":null,
"eximCd":null,
"consignmentNo":null,
"assessFrom":null,
"assessTo":null,
"assessReason":null,
"reasonDesc":null,
"intCalUpto":"2070",
"assessBasis":null,
"entryBy":"PCS",
"rStatus":"1"
},
"assessCatAmount":[
{
"assessmentNo":1,
"assessmentType":"PRE",
"assessCatId":1,
"assessReason":"A",
"assessAmount":1,
"assessPenalty":2,
"entryBy":"PCS",
"rStatus":"1"
},
{
"assessmentNo":1,
"assessmentType":"PRE",
"assessCatId":1,
"assessReason":"D",
"assessAmount":3,
"assessPenalty":4,
"entryBy":"PCS",
"rStatus":"1"
},
{
"assessmentNo":1,
"assessmentType":"PRE",
"assessCatId":2,
"assessReason":"B",
"assessAmount":5,
"assessPenalty":6,
"entryBy":"PCS",
"rStatus":"1"
},
{
"assessmentNo":1,
"assessmentType":"PRE",
"assessCatId":2,
"assessReason":"E",
"assessAmount":7,
"assessPenalty":8,
"entryBy":"PCS",
"rStatus":"1"
},
{
"assessmentNo":1,
"assessmentType":"PRE",
"assessCatId":3,
"assessReason":"C",
"assessAmount":9,
"assessPenalty":10,
"entryBy":"PCS",
"rStatus":"1"
},
{
"assessmentNo":1,
"assessmentType":"PRE",
"assessCatId":3,
"assessReason":"F",
"assessAmount":10,
"assessPenalty":10,
"entryBy":"PCS",
"rStatus":"1"
}
]
}
Now we have this form as:
Now i need to populate those six assessCatAmount data into this table. how can i get this?
When i click on Datatable the action of clicking is happening by:
.selected {
background-color: #a7d8d3;
}
$('#nepal tbody').on('click', 'tr', function() {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
} else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
trDataSecondTable = table.row(this).data();
console.log(trDataSecondTable);
});
everything is stored in trDataSecondTable on click of row of the datatable.
$('#chooseButton')
.on(
'click',
function() {
$('.hidden')
.css('display', 'block');
$("#panEximName")
.html(
trDataSecondTable.eximPanNameEng);
$("#panEximPhone")
.html(
trDataSecondTable.eximPanPhone);
for (var i = 0; i < trDataSecondTable.document.length; i++) {
if ($("#invoice").val() == trDataSecondTable.document[i].docNameEng) {
$("#invoice").prop(
'checked', true);
} else if ($("#packingList")
.val() == trDataSecondTable.document[i].docNameEng) {
$("#packingList").prop(
'checked', true);
} else {
$("#invoice").prop(
'checked', false);
$("#packingList").prop(
'checked', false);
}
}
$("#inoutDate")
.val(
trDataSecondTable.letter[0].inoutDate);
});
You need to delegate and not use inline event handling
Delegate and clone - I changed the div class to match customs instead of custom
Sum on every change
Change all buttons to type="button" to not submit on [+]
I moved the grand total out of the excise row
function sumIt() {
$("#formContainer [type=number]").each(function() {
var $row = $(this).closest(".row");
var $fields = $row.find("[type=number]");
var val1 = $fields.eq(0).val();
var val2 = $fields.eq(1).val();
var tot = (isNaN(val1) ? 0 : +val1) + (isNaN(val2) ? 0 : +val2)
$row.find(".sum").text(tot);
});
var total = 0;
$(".sum").each(function() {
total += isNaN($(this).text()) ? 0 : +$(this).text()
});
$("#tot").text(total);
return total;
}
$(".customs-table .remove:lt(1)").hide();
$(".vat-table .remove:lt(1)").hide();
$(".excise-table .remove:lt(1)").hide();
$("#formContainer").on("click", "button", function() {
var selector = "div.row";
var $div = $(this).closest(selector);
if ($(this).is(".add")) {
var $newDiv = $div.clone();
$newDiv.find(":input").val(""); // clear all
$newDiv.find("[type=number]").val(0); // clear numbers
$newDiv.find(".sum").text(0); // clear total
$newDiv.insertAfter($div)
}
else {
$div.remove();
sumIt();
}
$(".customs-table .remove:gt(0)").show();
$(".vat-table .remove:gt(0)").show();
$(".excise-table .remove:gt(0)").show();
});
$("#formContainer").on("input", "[type=number]", sumIt);
$("form").submit(function() {
event.preventDefault();
var user_profile = [];
$(".row").each(function() {
var $fields = $(this).find(":input");
if ($fields.length > 0) {
var cat = $(this).find("div>label").eq(0).text(); // use the label of the row
var catId = ["","Customs","VAT","Excise"].indexOf(cat)
user_profile.push({
assessmentType: "PRE",
assessCatID : catId,
assessReason: $fields.eq(0).val(),
assessAmount: $fields.eq(1).val(),
assessPenalty: $fields.eq(2).val(),
assessTotal: +$fields.eq(1).val() + +$fields.eq(2).val() // the leading + makes it a number
});
}
});
console.log(user_profile);
/*
$.ajax({
url: "someserverfunction",
data: JSON.encode(user_profile),
success : function(data) { }
error: function() { }
});
*/
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<form id="myForm">
<div id="formContainer" class="col-md-12" style="float: none;">
<!-- <button onclick="myFunction()" class="pull-right">+</button> -->
<div style="margin-bottom: 30px;">
<div class="form-group row">
<div class="col-md-1"></div>
<div class="col-md-4">
<label>Reason</label>
</div>
<div class="col-md-2">
<label>Amount</label>
</div>
<div class="col-md-2">
<label>Penalty</label>
</div>
<div class="col-md-1">Total</div>
<div class="col-md-2">Action</div>
</div>
<div class="customs-table row">
<div class="col-md-1">
<label>Customs</label>
</div>
<div class="col-md-4">
<input type="text" class="form-control customReason" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt customAmount" value="0" name="abc" min="0" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt customPenalty" value="0" name="abc" min="0" />
</div>
<div class="col-md-1">
<span class="sum">0</span>
</div>
<div class="col-md-2">
<button type="button" class="add">+</button>
<button type="button" class="remove">-</button>
</div>
</div>
<div class="vat-table row">
<div class="col-md-1">
<label>VAT</label>
</div>
<div class="col-md-4">
<input type="text" class="form-control vatReason" name="vatReason" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt1 vatAmount" value="0" name="vatAmount" min="0" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt1 vatPenalty" value="0" name="vatPenalty" min="0" />
</div>
<div class="col-md-1">
<span class="sum">0</span>
</div>
<div class="col-md-2">
<button type="button" class="add">+</button>
<button type="button" class="remove">-</button>
</div>
</div>
<div class="excise-table row">
<div class="col-md-1">
<label>Excise</label>
</div>
<div class="col-md-4">
<input type="text" class="form-control exciseReason" name="exciseReason" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt2 exciseAmount" value="0" name="exciseAmount" min="0" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt2 excisePenalty" value="0" name="excisePenalty" min="0" />
</div>
<div class="col-md-1">
<span class="sum">0</span>
</div>
<div class="col-md-2">
<button type="button" class="add">+</button>
<button type="button" class="remove">-</button>
</div>
</div>
<div class="col-md-12 pull-right">
<label>Total:</label> <b><span id="tot">0</span></b>
</div>
</div>
<button type="submit" class="btn btn-success pull-right">Submit</button>
</div>
</form>
I have created a eBay Item search form. I want to make form.html to form.php but when I change it to .php the form doesn't work and display blank page. you can see form.html here:
<script>
function showDetail(name){
$("."+name).collapse('toggle');
}
function getPage(num){
var data = {
"action": "test",
"pageNumber": num
};
data = $('form').serialize() + "&" + $.param(data);
// jQuery AJAX call to PHP Script with JSON Return
$.ajax({
type: "GET",
dataType: "json",
url: "advancedItemSearchTest.php", //Relative or absolute path to response.php file
data: data,
success: function(new_data) {
$( ".container" ).hide();
$( ".the-return" ).html( "" );// clear all the contents first
if(new_data['ack'] != 'Success' || new_data['resultCount'] <= 0){
$( ".the-return" ).html( "<h2>No Results were found</h2>" );
}
else{
for ( var i = 0; i < new_data.itemCount; i++ ) {
var $media = $( '<div class = "media"></div>');
var $media_body = $( '<div class = "media-body"></div>');
var $a_class = $('<a class= "pull-left"></a>');
var $name = 'name' + i;
//<img class = "media-object" src = alt = "Item Image" />
//<?php echo $item->title ?>
var $item = new_data['item'][i];
var $imageURL = $item['basicInfo']['galleryURL'];
var $price = $item['basicInfo']['convertedCurrentPrice']
var $title = '<a href = '+ $item['basicInfo']['viewItemURL']+ '>' + $item['basicInfo']['title'] + '</a>';
var $image = '<img class = "media-object" src =' + $imageURL +'alt = "Item Image" style="width:96px;height:96px" data-toggle="modal" data-target="#myModal'+ $name +'"/>';// concatenating string must use+ for variable!!
var $modal = $('<div class="modal fade" id="myModal'+ $name +'" role="dialog"></div>');
var $modalDialog = $('<div class="modal-dialog"></div>');
var $modalContent = $('<div class="modal-content"></div>');
$modalContent.append($('<div class="modal-header"></div>').append('<h4 class="modal-title">'+$item['basicInfo']['title']+'</h4>'));
$modalContent.append($('<div class="modal-body"></div>').append('<img src='+$item['basicInfo']['pictureURLSuperSize']+' alt="Item image" style="width:512px;height:512px" align="middle">'));
$modalContent.append($('<div class="modal-footer"></div>').append('<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'));
$modalDialog.append($modalContent);
$modal.append($modalDialog);
var $shippingCost = "(Free Shipping)";
if($item['basicInfo']['shippingServiceCost'] > 0){
$shippingCost = "(+$" + $item['basicInfo']['shippingServiceCost'] + ")";
}
$price = "<b>" + "Price:$" + $price + "</b>";
var $location = "<i>" + "Location:"+ $item['basicInfo']['location'] + "</i>";
var $topRated = "";
if($item['basicInfo']['topRatedListing']){
$topRated = '<img src =' + 'http://cs-server.usc.edu:45678/hw/hw8/itemTopRated.jpg' +' alt = "Top Rated" style="width:32px;height:24px" />';
}
var $collapse = $('<div class="collapse '+ $name +'"></div>');//
var $ul = $('<ul class="nav nav-tabs"></ul>');
$ul.append($('<li class="active"><a data-toggle="tab" href="#basic'+ $name +'">Basic Info</a></li>'));
$ul.append($('<li><a data-toggle="tab" href="#seller'+ $name +'">Seller Info</a></li>'));
$ul.append($('<li><a data-toggle="tab" href="#shipping'+ $name +'">Shipping Info</a></li>'));
$collapse.append($ul);
var $tabContend = $('<div class="tab-content"></div>');
var $basic = $('<div id="basic'+ $name +'" class="tab-pane fade in active"></div>');
var $table = $('<tbody></tbody>');//$('<table class = "table table-striped" ></table>');
var $tr = $('<tr></tr>');
$tr.append('<td><b>Condition</b></td>' + '<td>'+$item['basicInfo']['conditionDisplayName']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
$tr.append('<td><b>Category Name</b></td>' + '<td>'+$item['basicInfo']['categoryName']+'</td>');
$table.append($tr);
$tabContend.append($basic.append($('<table class = "table table-striped" ></table>').append($table)));
var $seller = $('<div id="seller'+ $name +'" class="tab-pane fade"></div>');
$table = $('<tbody></tbody>');//$('<table class = "table table-striped""></table>');
$tr = $('<tr></tr>');
$tr.append('<td><b>User name</b></td>' + '<td>'+$item['sellerInfo']['sellerUserName']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
$tr.append('<td><b>Feedback score</b></td>' + '<td>'+$item['sellerInfo']['feedbackScore']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
$tr.append('<td><b>Positive feedback</b></td>' + '<td>'+$item['sellerInfo']['positiveFeedbackPercent']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
var $storeName = 'N/A';
if($item['sellerInfo']['sellerStoreName']!=''){
$storeName = $item['sellerInfo']['sellerStoreName'];
}
$tr.append('<td><b>Store name</b></td>' + '<td>'+$storeName+'</td>');
$table.append($tr);
$tabContend.append($seller.append($('<table class = "table table-striped" ></table>').append($table)));
var $shipping = $('<div id="shipping'+ $name +'" class="tab-pane fade"></div>');
$table = $('<tbody></tbody>');//$('<table class = "table table-striped""></table>');
$tr = $('<tr></tr>');
$tr.append('<td><b>Shipping type</b></td>' + '<td>'+$item['shippingInfo']['shippingType']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
$tr.append('<td><b>Handling time</b></td>' + '<td>'+$item['shippingInfo']['handlingTime']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
$tr.append('<td><b>Shipping locations</b></td>' + '<td>'+$item['shippingInfo']['shipToLocations']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
//✔(correct) ✘(wrong)
var $mark = "✘";
if($item['shippingInfo']['expeditedShipping']){
$mark = "✔";
}
$tr.append('<td><b>Expedited shipping</b></td>' + '<td>'+ $mark +'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
//✔(correct) ✘(wrong)
var $mark = "✘";
if($item['shippingInfo']['returnsAccepted']){
$mark = "✔";
}
$tr.append('<td><b>Return accepted</b></td>' + '<td>'+ $mark +'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
//✔(correct) ✘(wrong)
var $mark = "✘";
if($item['shippingInfo']['oneDayShippingAvailable']){
$mark = "✔";
}
$tr.append('<td><b>One day shipping</b></td>' + '<td>'+ $mark +'</td>');
$table.append($tr);
$tabContend.append($shipping.append($('<table class = "table table-striped" ></table>').append($table)));
$collapse.append($tabContend);
var $viewDetail= '<a onclick="showDetail(\'' + $name +'\')">View Detail</a>';//'+$name+'
$media.append($a_class.html( $image));
$media_body.append($collapse);
$media_body.prepend( '<font size="4">' + $title + '</font>' + '<br/>' + $price + $shippingCost + ' ' + $location + ' ' + $topRated + ' ' + $viewDetail );
$media.append($media_body);
$media.appendTo( $( ".the-return" ) );
$modal.appendTo( $( ".the-return" ) );
}
var $pagination = $('<div class = "pagination"></div>');
var $ul = $('<ul class="pagination"></ul>');
var $prev = num - 1;
if( num == 1){
$pagination.append($ul.append('<li class="disabled">' + '<<' + '</li>'));
}
else{
$pagination.append($ul.append('<li>' + '<<' + '</li>'));
}
for( var i = num; i < num+5; i++ ){
$pagination.append($ul.append('<li>' + i + '</li>'));
}
var $next = num + 1;
if( num == new_data['totalPages']){
$pagination.append($ul.append('<li class="disabled">' + '>>' + '</li>'));
}
else{
$pagination.append($ul.append('<li>' + '>>' + '</li>'));
}
var $itemFrom = (num-1) * Number(new_data.itemCount) + 1;
var $itemTo = $itemFrom + Number(new_data.itemCount) - 1;
var $resultNum = $( '<div class = "resultNum" ></div>').append( '<b><font size="5">'+$itemFrom +'-'+ $itemTo + ' items out of ' + new_data['resultCount'] +'</font></b>');
$resultNum.prependTo($( ".the-return" ));
$pagination.appendTo( $( ".the-return" ) );
}
},
error: function(jqXHR, textStatus, errorThrown){
//alert('error: ' + textStatus + ': ' + errorThrown);
}
});
}
$(document).ready(function(){
$('form').validate({
rules: {
keyword: { // should be name, not id!
required: true
},
priceLow: {
number: true,
digits: true
},
priceHigh: {
number: true,
digits: true
},
shippingTime:{
number: true,
digits: true
}
},
messages:{
keyword: { // should be name, not id!
required: "Please enter a keyword"
},
priceLow: {
number: "Price should be a valid number",
digits: "Price should be a valid number",
min : "Minimum price cannot be below 0"
},
priceHigh: {
number: "Price should be a valid number",
digits: "Price should be a valid number",
min : "Maximum price cannot be less than minimum price or below 0"
},
shippingTime:{
number: "Max handling time should be a valid digit",
digits: "Max handling time should be a valid digit",
min: "Max handling time should be greater than or equal to 1"
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
$('form').submit(function(){
//var num = 1;
getPage(1);
return false;
});
}); // end document.ready
</script>
</head>
<body>
<style>
.center_div{
margin: 0 auto;
width:80%;
}
</style>
<div class = "container center_div" >
<img src = " http://cs-server.usc.edu:45678/hw/hw8/ebay.jpg" class="img-responsive"><br>
<form class = "form-horizontal" action = "advancedItemSearchTest.php" method="GET" role = "form" id = "myForm" accept-charset="utf-8">
<div class = "form-group">
<label class="control-label col-sm-2" for="keyword">Key words:*</label>
<div class="col-sm-8">
<input type = "text" class="form-control" id = "keyword" name = "keyword" placeholder="Enter keyword">
</div>
<label class="control-label col-sm-2" for="keyword">APP ID</label>
<div class="col-sm-8">
<input type = "text" class="form-control" id = "appid" name = "appid" placeholder="Enter appID">
</div>
</div>
<div class = "form-group row">
<label class="control-label col-sm-2" for="priceLow">Price range: </label>
<div class="col-sm-4">
<input type = "number" class="form-control" name = "priceLow" id = "priceLow" min="0" placeholder="from($)">
</div>
<label class="control-label " for="priceHigh"> </label>
<div class="col-sm-4">
<input type = "number" class="form-control" name = "priceHigh" id = "priceHigh" min="0" placeholder="to($)">
</div>
</div>
<div class = "form-group">
<label class="control-label col-sm-2" for="conditionNew">Condition: </label>
<div class="col-sm-8">
<label class="checkbox-inline"><input type="checkbox" id = "conditionNew" name = "condition[]" value=1000>New</label>
<label class="checkbox-inline"><input type="checkbox" name = "condition[]" value=3000>Used</label>
<label class="checkbox-inline"><input type="checkbox" name = "condition[]" value=4000>Very Good</label>
<label class="checkbox-inline"><input type="checkbox" name = "condition[]" value=3000>Good</label>
<label class="checkbox-inline"><input type="checkbox" name = "condition[]" value=4000>Acceptable</label>
</div>
</div>
<div class = "form-group">
<label class="control-label col-sm-2" for="formats">Buying formats: </label>
<div class="col-sm-8">
<label class="checkbox-inline"><input type="checkbox" id = "formats" name = "BuyFormat[]" value="FixedPrice">Buy It Now</label>
<label class="checkbox-inline"><input type="checkbox" name = "BuyFormat[]" value="Auction">Auction</label>
<label class="checkbox-inline"><input type="checkbox" name = "BuyFormat[]" value="Classified">Classified Ad</label>
</div>
</div>
<div class = "form-group">
<label class="control-label col-sm-2" for="shipping">Shipping: </label>
<div class="col-sm-8">
<label class="checkbox-inline"><input type="checkbox" id = "shipping" name = "FreeShippingOnly" value="true">Free Shipping</label>
<label class="checkbox-inline"><input type="checkbox" name = "ExpeditedShippingType" value="Expedited">Expedited shipping</label>
</div>
</div>
<div class = "form-group">
<label class="control-label col-sm-2" for="shippingTime"> </label>
<div class="col-sm-8">
<input type = "number" class="form-control" name = "shippingTime" id = "shippingTime" min="1" placeholder="Max handling time(days)">
</div>
</div>
</div>
</div>
<div class="form-group col-sm-10" align="right">
<input type="reset" class="btn btn-default" value="Clear" >
<input type="submit" class="btn btn-primary" value="Search">
</div>
</form>
when form is in .html extension it works fine but when I change it to .php it display blank page.
Change the last button type from submit to button.
In submit It will redirect on new page.
I am working on a WCF service application that required to get the Barcode reader characters and show data of it on UI for user. My problem is that when I write data on textbox with keyboard is OK but when read from barcode reader overwrite it and show 3 times data in UI.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>سرویس و بارکد خوان</title>
<script src="Scripts/jquery-1.11.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
function setFocusToTextBox() {
$(document).ready(function () {
document.getElementById('txtFirst').focus();
});
}
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#txtFirst").keydown(function (e) {
if (e.which == 17 || e.which == 74) {
e.preventDefault();
} else {
console.log(e.which);
}
})
});
</script>
<script type="text/javascript" language="javascript">
function JqueryAjaxCall(val) {
$("#contentHolder").empty();
$(".form-errors").empty();
if (val != null && val.length === 20) {
document.getElementById("txtFirst").select();
var pageUrl = '<%= ResolveUrl("~/Default.aspx/jqueryAjaxCall") %>';
var parameter = { "myVal": val}
$.ajax({
type: 'POST',
url: pageUrl,
data: JSON.stringify(parameter),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
dateFormat: 'dd/mm/yy',
success: function (data) {
onSuccess(data);
},
error: function (data, success, error) {
var myitems = jQuery.parseJSON(data.responseText);
$(".form-errors").text(myitems.Message).show();
}
});
return false;
}
function onSuccess(data) {
var items = data.d;
var fragment = "<ul>"
var BLNumber = items.BLNumber;
var ContainerNumber = items.ContainerNumber;
var Destination = items.Destination;
var SerialNumberVerification = items.SerialNumberVerification;
var TempPermission = items.TempPermission;
var VehicleNumber = items.VehicleNumber;
var VehicleType = items.VehicleType;
var VoyageID = items.VoyageID;
var value = new Date(parseInt(items.ExitDate.substr(6)));
var ExitDate = value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear();
var ExitPermissionNumber = items.ExitPermissionNumber;
var myvalue = new Date(parseInt(items.SpecialZoneOrCustomPermissionDate.substr(6)));
var SpecialZoneOrCustomPermissionDate = myvalue.getMonth() + 1 + "/" + myvalue.getDate() + "/" + myvalue.getFullYear();
var SpecialZoneOrCustomPermissionNumber = items.SpecialZoneOrCustomPermissionNumber;
fragment += "<li> " + " شماره بارنامه : " + BLNumber + " <br> "
+ " شماره کانتینر : " + ContainerNumber + " <br> "
+ " مسافت : " + Destination + " <br/> "
+ " شماره تائیدیه : " + SerialNumberVerification + " <br/> "
+ " شماره مجوز موقت : " + TempPermission + " <br/> "
+ " شماره وسیله نقلیه : " + VehicleNumber + " <br/> "
+ " نوع وسیله نقلیه : " + VehicleType + " <br/> "
+ " VoyageID : " + VoyageID + " <br/> "
+ " تاریخ خروج : " + ExitDate + " <br/> "
+ " شماره خروج : " + ExitPermissionNumber + " <br/> "
+ " تاریخ مجوز : " + SpecialZoneOrCustomPermissionDate + " <br/> "
+ " شماره مجوز : " + SpecialZoneOrCustomPermissionNumber + " <br/> "
+ "</li>";
$("#contentHolder").append(fragment);
}
}
</script>
</head>
<body onload="setFocusToTextBox();" bgcolor="#E6E6FA">
<form id="myForm" runat="server" dir="rtl" >
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<hr />
<div>
<table cellpadding="1" cellspacing="0" style="width: 80%;">
<tr>
<td>
</td>
<td>
<asp:Label ID="lblFirst" runat="server" Text="لطفا شماره سند را وارد نمائید : " Font-Bold="True"></asp:Label>
<input type="text" id="txtFirst" onfocus="setFocusToTextBox" onkeyup="return JqueryAjaxCall(this.value);" class="col-xs-4" style="background-color:#ede0dd"/>
</td>
</tr>
<tr>
<td>
</td>
<td>
<div id="contentHolder" >
<asp:Label ID="lblError" runat="server" Text=""></asp:Label>
</div>
</td>
<td>
<div class="form-errors" style="margin-right:-175%;font-style:oblique" dir="rtl" align="right"></div>
</td>
</tr>
</table>
</div>
</form>
<br />
<br />
<br />
<br />
<br />
<hr />
</body>
</html>
on this line code you call your ajax on every key click
onkeyup="return JqueryAjaxCall(this.value);"
and so on each click you have data output, 3 times and maybe more, on each key press. Redesign your code so only when you are finish typing you make the render.
I Understand it just now. problem was for this line of code
$("#contentHolder").append(fragment);
I add .empty() to that.
$("#contentHolder").empty().append(fragment);
I find it from this link
https://www.joezimjs.com/javascript/jquery-html-youre-doing-it-wrong/
i am trying to get an image from a given url. but i am unsure where i am going wrong in my coding. The url link is displayed but not the image of the url
for example, i would like to paste this url link
https://www.petfinder.com/wp-content/uploads/2012/11/dog-how-to-select-your-new-best-friend-thinkstock99062463.jpg
for my coding to display the image and not the link
Any help would be much appreciated
$(function() {
var dialog, form,
// From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29
emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
url = $("#url"),
// url = $('#elementId').attr('src');
name = $("#name"),
email = $("#email"),
company = $("#company"),
password = $("#password"),
allFields = $([]).add(url).add(name).add(email).add(company).add(password),
tips = $(".validateTips");
function updateTips(t) {
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function() {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function checkLength(o, n, min, max) {
if (o.val().length > max || o.val().length < min) {
o.addClass("ui-state-error");
updateTips("Length of " + n + " must be between " +
min + " and " + max + ".");
return false;
} else {
return true;
}
}
function checkRegexp(o, regexp, n) {
if (!(regexp.test(o.val()))) {
o.addClass("ui-state-error");
updateTips(n);
return false;
} else {
return true;
}
}
function addUser() {
var valid = true;
allFields.removeClass("ui-state-error");
valid = valid && checkLength(name, "username", 3, 16);
valid = valid && checkLength(email, "email", 6, 80);
valid = valid && checkLength(name, "company", 3, 16);
valid = valid && checkLength(password, "password", 5, 16);
valid = valid && checkRegexp(name, /^[a-z]([0-9a-z_\s])+$/i, "Username may consist of a-z, 0-9, underscores, spaces and must begin with a letter.");
valid = valid && checkRegexp(email, emailRegex, "eg. ui#jquery.com");
valid = valid && checkRegexp(password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9");
if (valid) {
$("#users tbody").append("<tr>" +
"<td>" + url.val() + "</td>" +
"<td>" + name.val() + "</td>" +
"<td>" + email.val() + "</td>" +
"<td>" + company.val() + "</td>" +
"<td>" + password.val() + "</td>" +
"</tr>");
dialog.dialog("close");
}
return valid;
}
dialog = $("#dialog-form").dialog({
autoOpen: false,
height: 510,
width: 400,
modal: true,
buttons: {
// addClass: "account-btn",
"GET STARTED": addUser,
// Cancel: function() {
// dialog.dialog( "close" );
// }
},
close: function() {
form[0].reset();
allFields.removeClass("ui-state-error");
}
});
form = dialog.find("form").on("submit", function(event) {
event.preventDefault();
addUser();
});
$("#create-user").button().on("click", function() {
dialog.dialog("open");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- modal/dialog form -->
<div id="dialog-form" title="">
<form>
<fieldset>
<label for="name">Your Name:</label>
<input type="text" name="name" id="name" value="username" class="text ui-widget-content ui-corner-all">
<label for="email">Your Email:</label>
<input type="text" name="email" id="email" value="username#example.com" class="text ui-widget-content ui-corner-all">
<label for="company">Your Company Name:</label>
<input type="text" name="company" id="company" value="example ltd" class="text ui-widget-content ui-corner-all">
<label for="password">Your Password:</label>
<input type="password" name="password" id="password" value="xxxxxxx" class="text ui-widget-content ui-corner-all">
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
<label for="url">Image Url</label>
<input type="text" name="url" id="url" value="http://example.com/picture.jpg" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form>
</div>
<!-- table -->
<div class="L-1-1" id="users-contain" class="ui-widget">
<h1 class="table_title">Existing Users</h1>
<table id="users" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header ">
<th class="first">Image</th>
<th>Name</th>
<th>Email</th>
<th>Company Name</th>
<th class="last">Password</th>
</tr>
</thead>
<tbody>
<tr>
<td>image</td>
<td>Richill Tamakloe</td>
<td>richill.tamakloe#example.com</td>
<td>Example Ltd</td>
<td>coder1</td>
</tr>
</tbody>
</table>
</div>
<button id="create-user">CREATE NEW USER</button>
You should replace this line:
"<td>" + url.val() + "</td>" +
with something like this:
"<td><img src='" + url.val() + "' /></td>" +
so that the actual image is shown in the table cell.
The aim of the code is to use checkboxes for filtering. In the JSFiddle example you can see that there are 5 filter groups with checkboxes.
The goal is: when somebody ticks multiple checkboxes, it should narrow the results list down, no matter if the checked checkboxes are in one filter group or in different groups. For example if you check two boxes in the Filter 1 group (e.g. Check1 and Check2) it should only display those results which are in Check1 AND Check2, which in this case is Result1 only. (Currently the code expands the results and if you check these 2 checkboxes it shows Result1, Result2, Result3 and Result9.)
(The narrowing works if you check checkboxes in different Filter groups and it should remain this way.)
Another goal is that, there are 5 Filter groups, but only the first 3 groups are coded in yet. How can I include the Filter 4 and Filter 5 groups in the code?
Thank you for your help.
The code:
<style media="screen" type="text/css">
body { font-family:'Arial'; color:#646464; }
.filtering-wrap { float:left; width:20%; margin:0 5% 0 0; padding:0; position:relative;}
</style>
<script type="text/javascript" src="/javascript/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function() {
var byFilter1 = [], byFilter2 = [], byFilter3 = [], byFilter4 = [], byFilter5 = [];
$("input[name=fl-1]").on( "change", function() {
if (this.checked) byFilter1.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byFilter1, "[data-category~='" + $(this).attr("value") + "']");
});
$("input[name=fl-2]").on( "change", function() {
if (this.checked) byFilter2.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byFilter2, "[data-category~='" + $(this).attr("value") + "']");
});
$("input[name=fl-3]").on( "change", function() {
if (this.checked) byFilter3.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byFilter3, "[data-category~='" + $(this).attr("value") + "']");
});
$("input[name=fl-4]").on( "change", function() {
if (this.checked) byFilter4.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byFilter4, "[data-category~='" + $(this).attr("value") + "']");
});
$("input[name=fl-5]").on( "change", function() {
if (this.checked) byFilter5.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byFilter5, "[data-category~='" + $(this).attr("value") + "']");
});
$("input").on( "change", function() {
var str = "Include items \n";
var selector = '', cselector = '', nselector = '';
var $lis = $('.results > div'),
$checked = $('input:checked');
if ($checked.length) {
if (byFilter1.length) {
if (str == "Include items \n") {
str += " " + "with (" + byFilter1.join(',') + ")\n";
$($('input[name=fl-1]:checked')).each(function(index, byFilter1){
if(selector === '') {
selector += "[data-category~='" + byFilter1.id + "']";
} else {
selector += ",[data-category~='" + byFilter1.id + "']";
}
});
} else {
str += " AND " + "with (" + byFilter1.join(' OR ') + ")\n";
$($('input[name=fl-2]:checked')).each(function(index, byFilter1){
selector += "[data-category~='" + byFilter1.id + "']";
});
}
}
if (byFilter2.length) {
if (str == "Include items \n") {
str += " " + "with (" + byFilter2.join(' OR ') + ")\n";
$($('input[name=fl-2]:checked')).each(function(index, byFilter2){
if(selector === '') {
selector += "[data-category~='" + byFilter2.id + "']";
} else {
selector += ",[data-category~='" + byFilter2.id + "']";
}
});
} else {
str += " AND " + "with (" + byFilter2.join(' OR ') + ")\n";
$($('input[name=fl-2]:checked')).each(function(index, byFilter2){
if(cselector === '') {
cselector += "[data-category~='" + byFilter2.id + "']";
} else {
cselector += ",[data-category~='" + byFilter2.id + "']";
}
});
}
}
if (byFilter3.length) {
if (str == "Include items \n") {
str += " " + "with (" + byFilter3.join(' OR ') + ")\n";
$($('input[name=fl-3]:checked')).each(function(index, byFilter3){
if(selector === '') {
selector += "[data-category~='" + byFilter3.id + "']";
} else {
selector += ",[data-category~='" + byFilter3.id + "']";
}
});
} else {
str += " AND " + "with (" + byFilter3.join(' OR ') + ")\n";
$($('input[name=fl-3]:checked')).each(function(index, byFilter3){
if(nselector === '') {
nselector += "[data-category~='" + byFilter3.id + "']";
} else {
nselector += ",[data-category~='" + byFilter3.id + "']";
}
});
}
}
$lis.hide();
console.log(selector);
console.log(cselector);
console.log(nselector);
if (cselector === '' && nselector === '') {
$('.results > div').filter(selector).show();
} else if (cselector === '') {
$('.results > div').filter(selector).filter(nselector).show();
} else if (nselector === '') {
$('.results > div').filter(selector).filter(cselector).show();
} else {
$('.results > div').filter(selector).filter(cselector).filter(nselector).show();
}
} else {
$lis.show();
}
$("#result").html(str);
});
function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
});
</script>
<div class="filtering-wrap">
<p style="font-size:12px;"><strong>Filter 1</strong></p>
<form>
<label style="font-size:12px;"><input type="checkbox" name="fl-1" value="check1" id="check1" /> Check1</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-1" value="check2" id="check2" /> Check2</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-1" value="check3" id="check3" /> Check3</label><br>
</form>
<p style="font-size:12px;"><strong>Filter 2</strong></p>
<form>
<label style="font-size:12px;"><input type="checkbox" name="fl-2" value="check4" id="check4" /> Check4</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-2" value="check5" id="check5" /> Check5</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-2" value="check6" id="check6" /> Check6</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-2" value="check7" id="check7" /> Check7</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-2" value="check8" id="check8" /> Check8</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-2" value="check9" id="check9" /> Check9</label>
</form>
<p style="font-size:12px;"><strong>Filter 3</strong></p>
<form>
<label style="font-size:12px;"><input type="checkbox" name="fl-3" value="check10" id="check10" /> Check10</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-3" value="check11" id="check11" /> Check11</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-3" value="check12" id="check12" /> Check12</label>
</form>
<p style="font-size:12px;"><strong>Filter 4</strong></p>
<form>
<label style="font-size:12px;"><input type="checkbox" name="fl-4" value="check13" id="check13" /> Check13</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-4" value="check14" id="check14" /> Check14</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-4" value="check15" id="check15" /> Check15</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-4" value="check16" id="check16" /> Check16</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-4" value="check17" id="check17" /> Check17</label>
</form>
<p style="font-size:12px;"><strong>Filter 5</strong></p>
<form>
<label style="font-size:12px;"><input type="checkbox" name="fl-5" value="check18" id="check18" /> Check18</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-5" value="check19" id="check19" /> Check19</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-5" value="check20" id="check20" /> Check20</label>
</div>
<div class="results">
<div class="result" data-id="result1" data-category="check1 check2 check3 check4 check5 check6 check7 check8 check9 check10">Result1</div>
<div class="result" data-id="result2" data-category="check1 check3 check5 check7 check9 check11 check13 check15 check17 check19">Result2</div>
<div class="result" data-id="result3" data-category="check2 check4 check6 check8 check10 check12 check14 check16 check18 check20">Result3</div>
<div class="result" data-id="result4" data-category="check5 check6 check7 check8 check9 check10">Result4</div>
<div class="result" data-id="result5" data-category="check15">Result5</div>
<div class="result" data-id="result6" data-category="check3 check13 check20">Result6</div>
<div class="result" data-id="result7" data-category="check11 check12 check13 check14 check15 check16">Result7</div>
<div class="result" data-id="result8" data-category="check4 check8 check12 check16 check20">Result8</div>
<div class="result" data-id="result9" data-category="check2 check3 check5 check7 check11 check13 check17 check19">Result9</div>
<div class="result" data-id="result10" data-category="check3 check6 check9 check12 check15 check18">Result10</div>
<div class="result" data-id="result11" data-category="check5 check10 check15 check20">Result11</div>
<div class="result" data-id="result12" data-category="check6 check12 check18">Result12</div>
<div class="result" data-id="result13" data-category="check7 check14">Result13</div>
<div class="result" data-id="result14" data-category="check8 check16">Result14</div>
You can do all groups and use a simpler process to do it by using filter() and creating a simpler set of data arrays for comparisons.
var $results=$('.result'),
$checks=$(':checkbox[name^=fl]');
$checks.change(function(){
var $checked=$checks.filter(':checked');
/* show all when nothing checked*/
if(!$checked.length){
$results.show();
return; /* quit here if nothing checked */
}
/* create array of checked values */
var checkedVals= $.map($checked, function(el){
return el.value
});
/* hide all results, then filter for matches */
$results.hide().filter(function(){
/* split categories for this result into an array*/
var cats=$(this).data('category').split(' ');
/* filter the checkedVals array to only values that match */
var checkMatches=$.grep(checkedVals, function(val){
return $.inArray(val, cats) >-1;
});
/* only return elements with matched array and original array being same length */
return checkMatches.length === checkedVals.length;
/* show results that match all the checked checkboxes */
}).show();
/* do something when there aren't any matches */
if(!$results.length){
alert('Ooops...no matches');
}
});
DEMO