Layout Issue when content changes on page - javascript

I'm stuck on a problem here that I've been trying to d/dx. I have a layout for an inventory page, and the css is set up to properly to make it display correctly. Let me start off with the html/php code:
<div class='container-fluid second-row'>
<div class='row' id='truckviewer-content'>
</div>
<div id="display">
<div class='row content' id='content'>
<div class='col-md-2 col-md-offset-2 page-title hidden-sm hidden-xs'>
<h1 class='page-title-top'>Inventory</h1>
</div>
<div class='col-md-6'>
<h3 class='page-sub-title'>Pick Your Rig</h3>
<p>
Not only does Lone Mountain Truck Leasing provide a great selection of reliable semi trucks for sale, usually 3-5 years old, we also ensure your satisfaction because we encourage you to drive the truck off the lot for diagnostic evaluations and required inspections.
</p>
<p>
Our inventory includes fleets of semi trucks for sale, so take a look at just a few samples of our current inventory, and if you find something you like, give us a call toll-free at 866.512.5685, or contact us with the form below.
</p>
</div>
</div>
<div class='row'>
<div class='col-md-10 col-md-offset-1'>
<form class='form-inline center' role='form'>
<h3 class='inventory-sub-title'>Filters</h3>
<div class='form-group'>
<select id='yearFilter' class='filter form-control'>
<option value="allY" selected>-- year --</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="2010">2010</option>
<option value="2009">2009</option>
<option value="2008">2008</option>
<option value="2007">2007</option>
</select>
</div>
<div class='form-group'>
<select id='makeFilter' class='filter form-control'>
<option value="allM" selected>-- Make --</option>
<option value="freightM">Freightliner</option>
<option value="intM">International</option>
<option value="kenM">Kenworth</option>
<option value="mackM">Mack</option>
<option value="peteM">Peterbilt</option>
<option value="volvoM">Volvo</option>
</select>
</div>
<div class='form-group'>
<select id='engineFilter' class='filter form-control'>
<option value="allE" selected>-- Engine --</option>
<option value="catE">Caterpillar</option>
<option value="cumE">Cummins</option>
<option value="detE">Detroit</option>
<option value="mackE">Mack</option>
<option value="volE">Volvo</option>
</select>
</div>
<div class='form-group'>
<select id='transFilter' class='filter form-control'>
<option value="allT" selected>-- Transmission --</option>
<option value="10T">10 Speed</option>
<option value="13T">13 Speed</option>
<option value="18T">18 Speed</option>
<option value="autoT">Auto</option>
</select>
</div>
<div class='form-group'>
<select id='apuFilter' class='filter form-control'>
<option value="allA" selected>-- APU --</option>
<option value="apuYes">Yes</option>
<option value="apuNo">No</option>
</select>
</div>
Show All
</form>
</div>
</div>
<?
$truckorder = file_get_contents("truckorder.tpl");
$truckorder = preg_replace('/\s+/', ' ', trim($truckorder));
$tagname = "truckorder";
$trucks = parseContent($truckorder, $tagname);
$trucks = explode("|", $trucks);
foreach($trucks as $truck){
$truck = preg_replace('/\s+/', ' ', trim($truck));
$quickview = file_get_contents("groups/group_$truck/content/quickview.tpl");
$quickview = preg_replace('/\s+/', ' ', trim($quickview));
$tagname = "quickfilter";
$filter = parseContent($quickview, $tagname);
$tagname = "quicktitle";
$title = parseContent($quickview, $tagname);
$tagname = "quickprice";
$price = parseContent($quickview, $tagname);
$tagname = "quicklook";
$specs = parseContent($quickview, $tagname);
$detailview = file_get_contents("groups/group_$truck/content/detailview.tpl");
$detailview = preg_replace('/\s+/', ' ', trim($detailview));
$tagname = "trucks";
$params = parseContent($detailview, $tagname);
$param = explode("|", $params);
$param1 = $param[0];
$param2 = $param[1];
$param3 = $param[2];
$param4 = $param[3];
$instock = getTruckTotals($param2,$param3,$param4);
?>
<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12 truck<?=$filter?>">
<div class="item ">
<p class='truck-img-align'>
<img class="truckTip" src="groups/group_<?=$truck?>/photos/quicktruck.png" border="no-border" />
</p>
<a class='ajax ajax-main' data-price="<?=$price?>" data-title="<?=$title?>" data-stock="<?=$instock?>" data-truck="<?=$truck?>" href="detail/?id=<?=$truck?>"><div class="caption"><h4>Quick Look</h4><?=$specs?></div></a>
</div>
<h3 class='truck-title'><?=$title?></h3>
<h3 class='truck-price'><?=$price?></h3>
<p class='in-stock'><?=$instock?></p>
<a class='ajax bottom-link' data-price="<?=$price?>" data-title="<?=$title?>" data-stock="<?=$instock?>" data-truck="<?=$truck?>" href="detail/?id=<?=$truck?>">Click or hover for more details</a>
</div>
<?
}
?>
</div>
</div>
EDIT: I have changed the javascript up. I have added a new sorting algorithm that is beginning to solve the problems that I am facing, but the error is now different.
$(function(){
sortDisplay();
});
// Image Overlay
$('.item').hover(function() {
$(this).find('div.caption').stop(false,true).fadeIn(200);
},
function(){
$(this).find('div.caption').stop(false,true).fadeOut(200);
});
// Filtering
$("#showAll").click(function(){
sortDisplay();
$(".truck").addClass("allY allM allE allT allA");
$("#yearFilter").val("allY");
$("#makeFilter").val("allM");
$('#engineFliter').val("allE");
$('#transFliter').val("allT");
$('#apuFliter').val("allA");
$(".truck").show();
// Update Filters
$("#yearFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+':visible').size() < 1 && $(this).val() !=='allY'){
$(this).attr('disabled','disabled');
}
else{
$(this).removeAttr('disabled');
}
});
$("#makeFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+':visible').size() < 1 && $(this).val() !=='allM'){
$(this).attr('disabled','disabled');
}
else{
$(this).removeAttr('disabled');
}
});
$("#engineFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+':visible').size() < 1 && $(this).val() !=='allE'){
$(this).attr('disabled','disabled');
}
else{
$(this).removeAttr('disabled');
}
});
$("#transFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+':visible').size() < 1 && $(this).val() !=='allT'){
$(this).attr('disabled','disabled');
}
else{
$(this).removeAttr('disabled');
}
});
$("#apuFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+':visible').size() < 1 && $(this).val() !=='allA'){
$(this).attr('disabled','disabled');
}
else{
$(this).removeAttr('disabled');
}
});
});
$('.filter').change(function(){
sortDisplay();
$(".truck").each(function(){
$(this).removeClass("truck-reset");
});
$(".truck").addClass("allY allM allE allT allA");
var year = $("#yearFilter").val();
if(year !=='allY'){
$(".truck").removeClass("allY");
}
var make = $("#makeFilter").val();
if(make !=='allM'){
$(".truck").removeClass("allM");
}
var eng = $("#engineFilter").val();
if(eng !=='allE'){
$(".truck").removeClass("allE");
}
var trans = $("#transFilter").val();
if(trans !=='allT'){
$(".truck").removeClass("allT");
}
var apu = $("#apuFilter").val();
if(apu !=='allA'){
$(".truck").removeClass("allA");
}
$(".truck").hide();
$(".truck").each(function(){
if($(this).hasClass(year)&&$(this).hasClass(make)&&$(this).hasClass(eng)&&$(this).hasClass(trans)&&$(this).hasClass(apu)){
$(this).fadeIn();
}
});
//$("#anchor").slideto();
// Update Filters
$("#yearFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+':visible').size() < 1 && $(this).val() !=='allY'){
$(this).attr('disabled','disabled');
}
else{
$(this).removeAttr('disabled');
}
});
$("#makeFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+':visible').size() < 1 && $(this).val() !=='allM'){
$(this).attr('disabled','disabled');
}
else{
$(this).removeAttr('disabled');
}
});
$("#engineFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+':visible').size() < 1 && $(this).val() !=='allE'){
$(this).attr('disabled','disabled');
}
else{
$(this).removeAttr('disabled');
}
});
$("#transFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+':visible').size() < 1 && $(this).val() !=='allT'){
$(this).attr('disabled','disabled');
}
else{
$(this).removeAttr('disabled');
}
});
$("#apuFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+':visible').size() < 1 && $(this).val() !=='allA'){
$(this).attr('disabled','disabled');
}
else{
$(this).removeAttr('disabled');
}
});
});
// Check If Filter Exists Else Disable Select Option
$("#yearFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+'').size() < 1 && $(this).val() !=='allY'){
$(this).attr('disabled','disabled');
}
});
$("#makeFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+'').size() < 1 && $(this).val() !=='allM'){
$(this).attr('disabled','disabled');
}
});
$("#engineFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+'').size() < 1 && $(this).val() !=='allE'){
$(this).attr('disabled','disabled');
}
});
$("#transFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+'').size() < 1 && $(this).val() !=='allT'){
$(this).attr('disabled','disabled');
}
});
$("#apuFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+'').size() < 1 && $(this).val() !=='allA'){
$(this).attr('disabled','disabled');
}
});
$('.ajax').click(function(e){
e.preventDefault();
var truckWindowId = $(this).data('truck');
var truckWindowTitle = $(this).data('title');
var truckWindowStock = $(this).data('stock');
var truckWindowPrice = $(this).data('price');
var content = {
id : truckWindowId,
title : truckWindowTitle,
stock : truckWindowStock,
price : truckWindowPrice
};
$.ajax({
url: "../assets/server/inventory/getTruckDetails.php",
type: "POST",
data: content,
dataType: "JSON",
cache: false,
success: function(data){
var images = data.images;
$('#display').fadeOut(function(){
$('#content').fadeOut();
$('#truckviewer-content').html(data.message).fadeIn();
//shut off the carousel autoscroll feature
$('.carousel').carousel({
interval: false
});
//allow for outside the box to be clickable and closer the div on click
$(document).mouseup(function(e){
var container = $(".truckview");
if(!container.is(e.target) && container.has(e.target).length === 0){
$('.closer').trigger("click");
}
});
});
}
});
});
$(function(){
$("#truckviewer-content").on('click', '.closer', function(e){
e.preventDefault();
var viewer = $('#close-button').data('toggle');
$(viewer).fadeOut(function(){
$('#content').fadeIn();
$('#display').fadeIn();
});
});
});
function sortDisplay(){
var count = 0;
var vizCount = 0;
if($(window).width() > 1200){
$(".truck").each(function(){
$(this).removeClass('view-sort-left');
$(this).removeClass('view-sort-right');
if(count <= 3){
if(count == 0 && $(this).is(':visible')){
vizCount++;
$(this).addClass('view-sort-left');
}else if(count == 3 && $(this).is(':visible')){
vizCount++;
$(this).addClass('view-sort-right');
}else if($(this).is(":visible")){
vizCount++;
}
}else if(count > 3){
if($(this).is(':visible')){
if(vizCount%4 === 0){
$(this).addClass('view-sort-left');
vizCount++;
}else if(vizCount%4 === 3){
$(this).addClass('view-sort-right');
vizCount++;
}else{
vizCount++;
}
}
}
count++;
});
}
}
EDIT: What's happening now is that when the second row of items gets checked the objects won't have the sorting classes of .sort-view-left or .sort-view-right appended to them, but they do in the first row. If you need further explanation please comment, and I'll answer.
This is all working properly but I'm sure I'm going to need to tweek it with what I am trying to figure out what to do.
When the items change display based on the filter that you pick, the css layout doesn't correct itself, that is because of the nth-child selectors used to pick them.
.truck{
width: 16%;
margin-left: 1%;
margin-right: 1%;
min-height: 350px;
margin-top: 25px;
}
.view-sort-left{
margin-left: 14% !important;
}
.view-sort-right{
margin-right: 14% !important;
}
.truck-reset:nth-child(4n-1){
margin-left: 14%;
}
With all that information above given, it is time to get to the point. What I'm trying to figure out is how do I change it up so that system is smart enough to decide how many objects are being shown on the inventory page, and then calculate a nice css table based on that. I'm almost considering just doing that from the get go. And then also calculate it based on page width as well. This might be too big of a problem to post on here. I'm not sure, i'm still kind of a noob at posts on here. if someone has an idea though let me know. If you think I should consolidate and shrink this problem down let me know that as well, and I can fix problems that way. I would like to put my brain together with someone on here though so that I can get to the bottom of this problem. Hope to hear from some people soon!

Figured it out, I needed to consolidate the two loops into just one and use options within the if statement to determine where my classes should go.
function sortDisplay(){
var count = 0;
var vizCount = 0;
if($(window).width() > 1200){
$(".truck").each(function(){
$(this).removeClass('view-sort-left');
$(this).removeClass('view-sort-right');
if((count == 0 || vizCount%4 == 0) && $(this).is(':visible')){
$(this).addClass('view-sort-left');
vizCount++;
}else if((count == 3 || vizCount%4 == 3)&& $(this).is(':visible')){
$(this).addClass('view-sort-right');
vizCount++;
}else if($(this).is(":visible")){
vizCount++;
}
count++;
});
}else if($(window).width() <= 1200 && $(window).width() > 992){
$(".truck").each(function(){
$(this).removeClass('view-sort-left');
$(this).removeClass('view-sort-right');
if((count == 0 || vizCount%3 == 0) && $(this).is(':visible')){
$(this).addClass('view-sort-left');
vizCount++;
}else if((count == 2 || vizCount%3 == 2)&& $(this).is(':visible')){
$(this).addClass('view-sort-right');
vizCount++;
}else if($(this).is(":visible")){
vizCount++;
}
count++;
});
}else{
$(".truck").each(function(){
$(this).removeClass('view-sort-left');
$(this).removeClass('view-sort-right');
});
}
}
$(window).resize(function(){
sortDisplay();
})

Related

Default value not working in select tag if the user doesn't select any options?

Hello,
I'm trying to make a default value of language selection to be English whose value is 1. So if the user doesn't select language option, it should still be 1 so that I can run my algorithm. But when I test it that doesn't select any value, it doesn't make it default value.
And I decided to check the datatype of language option, it's a string type, but even if I make if(isNaN(languageOption)){ languageOption = "1";}, it's still not working. Can anyone tell me why?
Thank you for your help
<body>
<div>
<img src="image/MindScribe-cursive.png" id="cursive">
</div>
<div id="container">
<img src="image/MindScribe-zebra.png" id="ImageEnterVariables" alt="Hello, I'm Stripes">
<img src="image/MindScribe-zebra2.png" id="onlyShowZebraImage" alt="Hello, I'm Stripes" style=display:none>
<select id="languageSelection" style=display:none>
<option value="">Choose a language</option>
<option value="1">English (American)</option>
<option value="2">Chinese (Mandarin)</option>
<option value="3">Japanese</option>
</select>
<script>
var languageOption = parseInt($("#languageSelection").val() );
$("#languageSelection").on("change", function(){
if(isNaN(languageOption)){ languageOption = "1";}
languageOption = $(this).val();
console.log("langugeOption is " + languageOption);
console.log("Language changed to: "+ $(this).find("option").eq( $(this)[0].selectedIndex ).text() + " (Index: "+languageOption+")" );
console.log(typeof(languageOption)); // Outputs string
endingArr = [];
runThroughArr = [];
randomArr = [];
if(languageOption === "1"){
console.log("English");
for(i = 0; i < intro_playList.length; i++){
if(intro_playList[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList[i].runThrough){ runThroughArr.push(i); }
if(intro_playList[i].random){ randomArr.push(i); }
}
}
else if (languageOption === "2"){
console.log("Chinese");
for(i = 0; i < intro_playList_chi.length; i++){
if(intro_playList_chi[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList_chi[i].runThrough){ runThroughArr.push(i); }
if(intro_playList_chi[i].random){ randomArr.push(i); }
}
}
});
</script>
</body>
Why you are doing these much stuff for making English default value? You can just add selected attribute to that option which you want to make default.
<select id="languageSelection" style=display:none>
<option value="">Choose a language</option>
<option value="1" selected>English (American)</option>
<option value="2">Chinese (Mandarin)</option>
<option value="3">Japanese</option>
</select>
And in your script, you can apply below logic to set default option to 1 :
languageOption = $(this).val();
if(languageOption==""){
languageOption="1";
}
$("#languageSelection").on("change", function(){
var languageOption = $(this).val();
if(languageOption.length==0){
languageOption=1;
}
console.log("langugeOption is " + languageOption);
console.log("Language changed to: "+ $(this).find("option").eq( $(this)[0].selectedIndex ).text() + " (Index: "+languageOption+")" );
console.log(typeof(languageOption)); // Outputs string
endingArr = [];
runThroughArr = [];
randomArr = [];
if(languageOption === "1"){
console.log("English");
for(i = 0; i < intro_playList.length; i++){
if(intro_playList[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList[i].runThrough){ runThroughArr.push(i); }
if(intro_playList[i].random){ randomArr.push(i); }
}
}
else if (languageOption === "2"){
console.log("Chinese");
for(i = 0; i < intro_playList_chi.length; i++){
if(intro_playList_chi[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList_chi[i].runThrough){ runThroughArr.push(i); }
if(intro_playList_chi[i].random){ randomArr.push(i); }
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="languageSelection" >
<option value="">Choose a language</option>
<option value="1">English (American)</option>
<option value="2">Chinese (Mandarin)</option>
<option value="3">Japanese</option>
</select>
Above code works for me, it gives me 1 if Choose a language is selected.
If you need the "Choose a language" to be displayed, set its value to 1 (the same as English):
<option value="1">Choose a language</option>

Bind another dropdowns as per previous values

I have total 4 dropdowns list... all dropdown contain numbers.
The maximum number of the last three dropdowns together is always equal to the amount that’s selected in the 1st dropdown.
If user selected 4 from 1st dropdown.
In this case all remaining dropdowns contain the values 0, 1, 2 ,3 and 4.
If customer selects 2 from 2nd dropdown then other two dropdowns will only show the values 0,1 and 2.
If customer selects 1 from 3rd dropdown then last should only show the values 0 and 1.
can anyone help me to sort-out this. Thanks in advance
I have tried so far
var tripChildSelect = $('#trip-child-count-range_0');
var childRangeLength = "<?php echo $this->getChildRangeLength()?>";
var j;
for(j=1; j <= childRangeLength; j++ )
{
var childRange = $('#trip-child-count-range_' + j);
}
tripChildSelect.change(function() {
tripChildSelect = $(this);
availableChildren = tripChildSelect.data('max-count') - tripChildSelect.val();
console.log(tripChildSelect.data('max-count') - tripChildSelect.val());
if(tripChildSelect.data('max-count') - tripChildSelect.val() === 0) {
for(j=1; j <= childRangeLength; j++ )
{
var childRange = $('#trip-child-count-range_' + j);
childRange.prop('disabled', true);
}
} else {
for(j=1; j <= childRangeLength; j++ )
{
var childRange = $('#trip-child-count-range_' + j);
childRange.find('option').each(function (index, element) {
selectOption = $(element);
if(selectOption.val() <= availableChildren) {
selectOption.show();
} else {
selectOption.hide();
}
});
childRange.prop('disabled', false);
}
}
});
//disable if sum equals
$('.trip-child-count-range').change(function() {
// body...
var sum = 0;
$('.trip-child-count-range :selected').each(function() {
sum += Number($(this).val());
});
// console.log('sum- '+sum);
if(sum == $('#trip-child-count').val())
{
$('.trip-child-count-range').each(function() {
if($(this).val() == 0)
$(this).attr('disabled', true);
});
}
else
{
$('.trip-child-count-range').each(function() {
if($(this).val() == 0)
$(this).attr('disabled', false);
});
}
})
$('#trip-child-count').change(function() {
// body...
var i;
for (i = 1; i <= $(this).val(); i++)
{
if ( $(".trip-child-count-range option[value='"+i+"']").length == 0 )
$('.trip-child-count-range').append( '<option value="'+i+'">'+''+i+'</option>' );
}
//set adta-max-xount
$('#trip-child-count-range_0').data( "max-count", $(this).val());
// console.log('hello' + $('#trip-child-count-range_0').data( "max-count"));
//remove greater options
$(".trip-child-count-range option").each(function() {
if($(this).val() > $('#trip-child-count').val())
{
$(".trip-child-count-range option[value="+this.value+"]").remove();
}
});
//added finalllu
$('.trip-child-count-range').attr('disabled', false);
$('.trip-child-count-range option[value=0]').attr('selected','selected');
availableChildren = $('#trip-child-count').val();
});
first dropdown id : #trip-child-count
common class for remaining 3 dropdowns: trip-child-count-range
Here I put your basic need. First create first drop down with 0-4 options and make other three drop down as empty. Then append options to other drop down based on the current drop down value
<!DOCTYPE html>
<html>
<body>
<div>
<select id="dropdown1">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="dropdown2">
</select>
<select id="dropdown3">
</select>
<select id="dropdown4">
</select>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#dropdown1").on("change",function(){
var dd1 = parseInt($(this).val());
$("#dropdown2, #dropdown3, #dropdown4").empty();
for(var i=0;i<=dd1;i++){
$("#dropdown2, #dropdown3, #dropdown4").append('<option val='+i+'>'+i+'</option>');
}
});
$("#dropdown2").on("change",function(){
var dd1 = parseInt($("#dropdown1").val());
var dd2 = parseInt($(this).val());
$("#dropdown3, #dropdown4").empty();
for(var i=0;i<=dd1-dd2;i++){
$("#dropdown3, #dropdown4").append('<option val='+i+'>'+i+'</option>');
}
});
$("#dropdown3").on("change",function(){
var dd2 = parseInt($("#dropdown2").val());
var dd3 = parseInt($(this).val());
$("#dropdown4").empty();
for(var i=0;i<=dd2-dd3;i++){
$("#dropdown4").append('<option val='+i+'>'+i+'</option>');
}
});
});
</script>
</body>
</html>

Count Unique Selection from Multiple Dropdown

I'm new to jquery, I'm working on a survey form and I have multiple dropdown menus for different questions but they all have the same dropdown value. Supposed I have:
<select name="Forms[AgentIsPitch]" id="Forms_AgentIsPitch">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<select name="Forms[MandatoryOptIsStated]" id="Forms_MandatoryOptIsStated">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
And other different dropdowns with different id's. What is the best way to count how many has selected Yes, No and N/A/ ? Thanks
you can do it simple this way
$('select').change(function() {
// get all selects
var allSelects = $('select');
// set values count by type
var yes = 0;
var no = 0;
// for each select increase count
$.each(allSelects, function(i, s) {
// increase count
if($(s).val() == 'Yes') { yes++; }
if($(s).val() == 'No') { no++; }
});
// update count values summary
$('.cnt-yes').text(yes);
$('.cnt-no').text(no);
});
DEMO
Try this — https://jsfiddle.net/sergdenisov/h8sLxw6y/2/:
var count = {};
count.empty = $('select option:selected[value=""]').length;
count.yes = $('select option:selected[value="Yes"]').length;
count.no = $('select option:selected[value="No"]').length;
count.nA = $('select option:selected[value="N/A"]').length;
console.log(count);
My way to do it would be :
var optionsYes = $("option[value$='Yes']:selected");
var optionsNo = $("option[value$='No']:selected");
var optionsNA = $("option[value$='N/A']:selected");
console.log('number of yes selected = ' + optionsYes .length);
console.log('number of no selected = ' + optionsNo .length);
console.log('number of N/A selected = ' + optionsNA .length);
Check the console (or replace with alert).
With your code, it would be something like that (assuming you want to check on a button click event) :
<select name="Forms[AgentIsPitch]" id="Forms_AgentIsPitch">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<select name="Forms[MandatoryOptIsStated]" id="Forms_MandatoryOptIsStated">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<button class="btn btn-primary" id="countYes"></button>
<script type="text/javascript">
$('#countYes').on('click', function(){
var optionsYes = $("option[value$='Yes']:selected");
var optionsNo = $("option[value$='No']:selected");
var optionsNA = $("option[value$='N/A']:selected");
console.log('number of yes selected = ' + optionsYes .length);
console.log('number of no selected = ' + optionsNo .length);
console.log('number of N/A selected = ' + optionsNA .length);
});
</script>
You can check at another event, I choosed a button click just for example.
There is likely a cleaner way to do this, but this will get the job done (assuming there is a button click to trigger things):
$("#theButton").on('click', function() {
var totalSelect = 0;
var totalYes = 0;
var totalNo = 0;
var totalNA = 0;
$("select").each(function(){
totalSelect++;
if ($(this).val() == "Yes") { totalYes++; }
if ($(this).val() == "No") { totalNo++; }
if ($(this).val() == "N/A") { totalNA++; }
});
});
Hope this helps the cause.
In common you can use change event:
var results = {};
$('select').on('change', function() {
var val = $(this).val();
results[val] = (results[val] || 0) + 1;
});
DEMO
If you want count for each type of select:
$('select').on('change', function() {
var val = $(this).val();
var name = $(this).attr('name');
if (!results[name]) {
results[name] = {};
}
results[name][val] = (results[name][val] || 0) + 1;
});
DEMO
In the results will be something like this:
{
"Forms[AgentIsPitch]": {
"Yes": 1,
"No": 2,
"N/A": 3
},
"Forms[MandatoryOptIsStated]": {
"No": 5,
"N/A": 13
},
}
UPD: for counting current choice:
$('select').on('change', function() {
var results = {};
$('select').each(function() {
var val = $(this).val();
if (val) {
results[val] = (results[val] || 0) + 1;
}
})
console.log(results);
});
DEMO

change value upon select

what i'm aiming is to show the other div when it selects one of the two options
Full time and Part Time
and if possible compute a different value for each
When the user selects Part time
the value of PrcA will change to PrcB
this is the code i used
<!====================================================================================>
<script language="javascript">
<!--//
function dm(amount)
{
string = "" + amount;
dec = string.length - string.indexOf('.');
if (string.indexOf('.') == -1)
return string + '.00';
if (dec == 1)
return string + '00';
if (dec == 2)
return string + '0';
if (dec > 3)
return string.substring(0,string.length-dec+3);
return string;
}
function calculate()
{
QtyA = 0;
TotA = 0;
PrcA = 1280;
PrcB = 640;
if (document.form1.qtyA.value > "")
{ QtyA = document.form1.qtyA.value };
document.form1.qtyA.value = eval(QtyA);
TotA = QtyA * PrcA;
document.form1.totalA.value = dm(eval(TotA));
Totamt =
eval(TotA) ;
document.form1.GrandTotal.value = dm(eval(Totamt));
}
//-->
</script>
<!====================================================================================>
<p>
<label for="acct" style="margin-right:90px;"><strong>Account Type<strong><font color=red size=3> * </font></strong></label>
<select name="acct" style="background-color:white;" class="validate[custom[serv]] select-input" id="acct" value="">
<option value="Full Time">Full-Time</option>
<option value="Part Time">Part-Time</option>
<option selected="selected" value=""></option>
</select></p>
<!====================================================================================>
<script>
$(document).ready(function() {
$("input[name$='acct']").select(function() {
var test = $(this).val();
$("div.desc").hide();
$("#acct" + test).show();
});
});
</script>
<!====================================================================================>
<p>
<table><tr><td>
<lable style="margin-right:91px;"># of Agent(s)<font color=red size=3> * </font></lable>
</td><td>
<input style="width:25px; margin-left:5px;" type="text" class="validate[custom[agnt]] text-input" name="qtyA" id="qtyA" onchange="calculate()" />
</td><td>
<div id="acctFull Time" class="desc">
x 1280 =
</div>
<div id="acctPart Time" class="desc" style="display:none">
x 640 =
</div>
</td><td>
$<input style="width:80px; margin-left:5px;" type="text" readonly="readonly" name="totalA" id="totalA" onchange="calculate()" />
</p>
</td></tr></table>
is there any way for me to achieve this?
Check this [FIDDLE] ..
Added two classes to the div's which show the amount.. This should make like easier to access them..
$(document).ready(function() {
$("#acct").on('change', function() {
var selVal = $(this).val();
if (selVal == '1') { // Full Time
$('.parttime').hide();
$('.fulltime').show();
$('.agent').show();
$('.error').hide();
}
else if (selVal == '2') { // Part Time
$('.parttime').show();
$('.fulltime').hide();
$('.agent').show();
$('.error').hide();
}
else {
$('.parttime').hide();
$('.fulltime').hide();
$('.agent').hide();
$('.error').show();
}
});
$('#qtyA').on('change', function() {
var selVal = $("#acct").val();
if (!isNaN($(this).val())) {
var total = 0;
if (selVal == '1') {
total = parseInt($(this).val()) * 1280;
}
else if (selVal == '2') {
total = parseInt($(this).val()) * 640;
}
$('#totalA').val(total.toFixed(2));
}
else {
$(this).val('0');
$('#totalA').val('0.00');
}
});
});​
Also you can completely eliminate the vanilla javascript and go with jQuery that should be lot easier..
got the answer this is what i used
<script type="text/javascript">
$(document).ready(function(){
$('#acct').change(function() {
$('.box').hide();
$('#acct' + $(this).val()).show();
});
});
</script>
A jsfiddle would help tremendously here. However, it sounds like you're trying to:
Show/hide content containers based on a pulldown selection, and
Process a field value based on the pulldown selection.
These two problems could generally be addressed like so (assuming jQuery, per your snippit):
<select id="time-select">
<option value="full">Full-Time</option>
<option value="part">Part-Time</option>
</select>
<div id="full-detail" class="detail">
Full-time info.
</div>
<div id="part-detail" class="detail">
Part-time info.
</div>
<input type="text" id="computed-value"/>
<script>
$(function() {
"use strict";
function computeValueBasedOn( opt ) {
// Evaluate the computed value here...
return opt ? "do" : "stuff";
}
$("#time-select").change(function(evt) {
$(".detail").hide();
$("#"+ this.value +"-detail").show();
$("#computed-value").val( computeValueBasedOn( this.value ) );
});
});
</script>

JavaScript Giving 'Object Expected' Error

I am writing some code that shows or hides a calendar based on a drop down select form. I have it set to run my showHideCalendar() function as an onchange action on the drop down selection. When I change the selected option I receive an "Object expected" error. I have included the relevant HTML and JavaScript code.
<script type="text/javascript" language="javascript">
function showHideCalendar(element) {
document.getElementById("calendar").style.display = "none";
if (document.getElementById("dropdown").selectedIndex === 13) {
cal5.popup();
document.getElementById("textField").value = "";
document.getElementById("calendar").style.display = "inline";
}
}
</script>
<FORM NAME='Labs' METHOD='POST' ACTION="">
<select id="dropdown" name='TimeFrame0' onchange='showHideCalendar(document.Labs.TimeFrame0)'>
<option value='NoReorder'>Do Not Reorder</option>
<option value='2012-06-14 08:40:39.067'>Today</option>
<option value='2012-06-21 08:40:39.067'>1 Week</option>
<option value='2012-06-28 08:40:39.067'>2 Weeks</option>
<option value='2012-07-05 08:40:39.067'>3 Weeks</option>
<option value='2012-07-12 08:40:39.067'>4 Weeks</option>
<option value='2012-07-26 08:40:39.067'>6 Weeks</option>
<option value='2012-07-14 08:40:39.067' selected>1 Month</option>
<option value='2012-08-14 08:40:39.067'>2 Months</option>
<option value='2012-09-14 08:40:39.067'>3 Months</option>
<option value='2012-10-14 08:40:39.067'>4 Months</option>
<option value='2012-12-14 08:40:39.067'>6 Months</option>
<option value='2013-03-14 08:40:39.067'>9 Months</option>
<option value='custom' id='custom'>Calendar Select</option>
</select>
<div id='calendar' style='display:inline'>
<input type=text name='StartDate' value='' size=20 onchange='inputChanged()' onkeydown='inputChanged()' onblur='inputChanged()' id='textField'>
<a href='javascript:cal5.popup();' onmousedown='inputChanged()'> <img src='/jscalendar/img/cal.gif' width='16' height='16' border='0' alt='Click Here to Pick up the date'></a>
</div>
<input type=checkbox name=SameDate value='on' checked onClick='SetTimeFrame(document.Labs.TimeFrame0)'> Use Same Date For All Labs
<input class='btnsave' type=button name=Save value='Reorder Labs' onClick=javascript:document.Labs.action='/LabReview/Reorder.php?PROV=PROVID&MaxCount=2&Text=1';document.Labs.submit();>
<input class='btncancel' type=button name=Cancel value=Cancel onClick=javascript:top.window.close()>
</FORM>
Does anyone see any reason why this is not working. The error is thrown on the line <select id="dropdown" name='TimeFrame0' onchange='showHideCalendar(document.Labs.TimeFrame0)'>.
One of the answerers thinks the error isn't in my new code, but rather something else on the page. I am editing my question to add the rest of the javascript that is on the page.
<script type="text/javascript" language="javascript">
function showHideCalendar(element) {
document.getElementById("calendar").style.display = "none";
if (document.getElementById("dropdown").selectedIndex === 13) {
cal5.popup();
document.getElementById("textField").value = "";
document.getElementById("calendar").style.display = "inline";
}
}
function inputChanged() {
document.getElementById("dropdown").selectedIndex = 13;
}
function SetTimeFrame(element)
{
if (document.Labs.SameDate.checked==true)
{
var Elements=document.Labs.elements.length;
for (var i=0; i<Elements; i++)
{
if (document.Labs.elements[i].type=='select-one')
{
document.Labs.elements[i].options[element.selectedIndex].selected=true;
}
}
}
}
if (top.window.opener.document.getElementById("Complete<?php echo($_GET['Item']); ?>"))
{
if ('<?php echo($Reviewed); ?>' == 'yes')
{
window.opener.document.getElementById("Complete<?php echo($_GET['Item']); ?>").style.visibility='visible';
window.opener.document.getElementById("Partial<?php echo($_GET['Item']); ?>").style.visibility='hidden';
}
else if ('<?php echo($Reviewed); ?>' == 'partial')
{
window.opener.document.getElementById("Partial<?php echo($_GET['Item']); ?>").style.visibility='visible';
window.opener.document.getElementById("Complete<?php echo($_GET['Item']); ?>").style.visibility='hidden';
}
}
else
{
var temp=top.window.opener.location.href;
top.window.opener.location.href=temp;
top.window.opener.top.window.location.reload();
}
function DateCheck(element)
{
var xx = element.value;
var re = new RegExp("^[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]$");
var re2 = new RegExp("^[0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]$");
var re3 = new RegExp("^[0-9][0-9]/[0-9]/[0-9][0-9][0-9][0-9]$");
var re4 = new RegExp("^[0-9]/[0-9]/[0-9][0-9][0-9][0-9]$");
var error = "";
var maxdays = new Array(0,31,29,31,30,31,30,31,31,30,31,30,31);
var retval = true;
if(element.value != "")
{
if(xx.search(re) < 0 && xx.search(re2) < 0 && xx.search(re3) < 0 && xx.search(re4) < 0)
{
error = "Invalid Date Format " + xx + ". Please enter dates in the format mm/dd/yyyy."
retval = false;
element.value = ""
}
else
{
var list = xx.split("/");
var month = list[0];
if(month.charAt(0) == "0")
month = month.substr(1);
if( list[0] < 1 || list[0] > 12)
{
error = "Invalid Month " + list[0];
retval = false;
element.value = ""
}
else
if(list[1] < 1 || list[1] > maxdays[month])
{
error = "Invalid Day " + list[1];
retval = false;
element.value = ""
}
else
if(list[2] < 1900)
{
error = "Invalid Year (Must be greater than 1900) " + list[2];
retval = false;
element.value = ""
}
}
if(!retval)
alert(error);
return retval;
}
}
</script>
Change:
<select id="dropdown" name='TimeFrame0' onchange='showHideCalendar(document.Labs.TimeFrame0)'>
To:
<select id="dropdown" name='TimeFrame0' onchange='showHideCalendar(this)'>
It turns out the problem was caused by the following block of code.
if (top.window.opener.document.getElementById("Complete<?php echo($_GET['Item']); ?>")) {
if ('<?php echo($Reviewed); ?>' == 'yes')
{
window.opener.document.getElementById("Complete<?php echo($_GET['Item']); ?>").style.visibility='visible';
window.opener.document.getElementById("Partial<?php echo($_GET['Item']); ?>").style.visibility='hidden';
}
else if ('<?php echo($Reviewed); ?>' == 'partial')
{
window.opener.document.getElementById("Partial<?php echo($_GET['Item']); ?>").style.visibility='visible';
window.opener.document.getElementById("Complete<?php echo($_GET['Item']); ?>").style.visibility='hidden';
}
}
else
{
var temp=top.window.opener.location.href;
top.window.opener.location.href=temp;
top.window.opener.top.window.location.reload();
}
When I removed that from the code, it worked like a charm. Thanks to everyone for their suggestions and thoughts.

Categories

Resources