.each function () for cloned inputs - javascript

Trying to create the Preview form and do not understand why each function () not working in this script. Or works but only for the last cloned row and ignore the zero values ​​in the previously cloned inputs.
$('input[id^=Mult_factor_]').each(function () {
var MultFactor = $(this).val();
var TotPoints = $('#Tot_points').val();
var exp1 = "Overload";
var exp2 = "Load is: ";
if (MultFactor < 1 || TotPoints > 100) {
$('#ExemptionLimitsText').text(exp1).show();
$('#PrwTotPointsText').hide();
} else {
$('#ExemptionLimitsText').text(exp2).show();
$('#PrwTotPointsText').text($('#Tot_points').val()).show();
}
});
JSfiddle
I need: If at least one of cloned MultiFactor value is zero show "Overload"

Based on your comment, you want to display the word "Overload" if either the "Additional" field is over 100 or if any of the multifactor fields is 0.
However, your loop continues to process if either of these conditions are met.
Do not use a loop, instead search specifically for a multifaktor value of 0.
var totalPoints = parseInt($('#Tot_points').val());
if(totalPoints > 100 || $('input[name="MultFaktor"]').filter(function(){return this.value=='0'}).length > 0) {
$('#ExemptionLimitsText').text("Overload").show();
$('#PrwTotPointsText').hide();
} else {
$('#ExemptionLimitsText').text("Load is: ").show();
$('#PrwTotPointsText').text(totalPoints).show();
}

Return false on overload
var valid = true;
var exp1 = "Overload";
var exp2 = "Load is: ";
var TotPoints = $('#Tot_points').val();
$('input[name=MultFaktor]').each(function () {
var $this = $(this);
if ($.trim($(this).val()) == '0' || TotPoints > 100) {
valid = false;
} else {
$('#ExemptionLimitsText').text(exp2).show();
$('#PrwTotPointsText').text($('#Tot_points').val()).show();
}
});
if (valid == false) {
e.preventDefault();
$('#ExemptionLimitsText').text(exp1).show();
$('#PrwTotPointsText').hide();
}

Related

jQuery multi-faceted filter issue.

I'm building a simple faceted filter to help users find the right condo. A few days ago I got a basic slider to filter out condos by square footage. The next part was getting the checkboxes to work which I posted to SO here and got some help from icecub. Since then I've been working on getting them to work in tandem (for example, checking 2 bedrooms and sliding the slider down to 800 sqft filters the condos by both variables). Got this to work yesterday.
The only issue I'm having is that now the slider only works when one of the two checkbox's are checked. If both or none are checked the slider doesn't work. I'm not sure exactly where my logic is flawed.
Here's a fiddle https://jsfiddle.net/baskinco/mwqkztn8/
and here's the JS
// FUNCTIONS
//make slider textbox equal to slider value
function printValue(sliderID, textbox) {
var x = document.getElementById(textbox);
var y = document.getElementById(sliderID);
x.value = y.value;
}
//get bdrm and slider values
function getValues() {
var bdrm1 = false;
var bdrm2 = false;
var sliderValue;
if($("#1bdrm").is(':checked')){
bdrm1 = true;
}
if ($("#2bdrm").is(':checked')){
bdrm2 = true;
}
sliderValue = $("#rangeValue").val();
runFilter(bdrm1, bdrm2, sliderValue);
}
function runFilter(bdrm1, bdrm2, sliderValue) {
$.each($('.condo-box'), function() {
$this = $(this);
condoData = $this.data();
if(bdrm1 && !bdrm2){
if ((condoData.bdrms == 1) && (condoData.sqft <= sliderValue)){
$this.show();
} else {
$this.hide();
}
} else if(bdrm2 && !bdrm1){
if ((condoData.bdrms == 2) && (condoData.sqft <= sliderValue)){
$this.show();
} else {
$this.hide();
}
} else {
$this.show();
}
});
}
// Set values for units
$('#jackson').data({
id:1,
sqft:897,
bdrms:2
});
$('#nicholl').data({
id:2,
sqft:808,
bdrms:2
});
$('#atwood').data({
id:3,
sqft:1020,
bdrms:2
});
//etc
//MAIN SCRIPT
$(document).ready(function() {
//print slider value to slider textbox
printValue('slider','rangeValue');
//when a bdrm box is checked ..
$("#1bdrm, #2bdrm").click(function(){
getValues();
});
//when the slider is moved
$("#slider").change(function() {
getValues();
});
});
Your else condition isn't checking the sqft and slider, it should be:
else {
if ((condoData.sqft <= sliderValue)){
$this.show();
} else {
$this.hide();
}
}
https://jsfiddle.net/mwqkztn8/1/
Or, even simpler, that whole thing could just be:
$.each($('.condo-box'), function() {
$this = $(this);
condoData = $this.data();
var sqftFilter = (condoData.sqft <= sliderValue);
var bedFilter = (!bdrm1 && !bdrm2) || (condoData.bdrms == 1 && bdrm1) || (condoData.bdrms == 2 && bdrm2);
$this.toggle(sqftFilter && bedFilter);
});
https://jsfiddle.net/mwqkztn8/3/

Combining Javascript Validation Functions

Alright I need help combining the two JavaScript Functions... I have tried multiple times and am not coming up with any luck. There almost identical functions except the fact that I change one number so that it thinks there different textboxes. I tried putting a variable in its place but then it always only validates to the ending number of the loop. Please show me how I may be able to combine these two functions. (Its my only work around and I can not find any examples similar to mine)
First:
<script type="text/javascript">
var QnoText = ['abc_1']; // add IDs here for questions with optional text input
function doSubmit_1() {
var ids_1 = '';
flag_1 = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids_1 = QnoText[i]+'Certificate_1';
if (CkStatus && document.getElementById(ids_1).value == '') {
alert('Please enter certificate number 1.');
document.getElementById(ids_1).focus();
flag_1 = false;
alert('return flag_1');
}
}
return flag_1;
}
</script>
Second:
<script type="text/javascript">
var QnoText = ['abc_2']; // add IDs here for questions with optional text input
function doSubmit_2() {
var ids_2 = '';
flag_2 = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids_2 = QnoText[i]+'Certificate_2';
if (CkStatus && document.getElementById(ids_2).value == '') {
alert('Please enter certificate number 2.');
document.getElementById(ids_2).focus();
flag_2 = false;
alert('return flag_2');
}
}
return flag_2;
}
</script>
You can pass a parameter in your function with the number of the textbox, like this:
var QnoText = ['abc_2']; // add IDs here for questions with optional text input
function doSubmit(n) {
var ids = '';
flag = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids = QnoText[i]+'Certificate_' + n;
if (CkStatus && document.getElementById(ids).value == '') {
alert('Please enter certificate number ' + n + '.');
document.getElementById(ids).focus();
flag = false;
alert('return flag_' + n);
}
}
return flag;
}
doSubmit(1); // for your submit 1
doSubmit(2); // for your submit 2
Is this what you wanted? because is not very clear. If is not feel free to explain.

jQuery "keyup" crashing page when checking 'Word Count'

I have a word counter running on a DIV and after typing in a few words, the page crashes. The browser continues to work (par scrolling) and no errors are showing in Chrome's console. Not sure where I'm going wrong...
It all started when I passed "wordCount(q);" in "keyup". I only passed it there as it would split-out "NaN" instead of a number to countdown from.
JS:
wordCount();
$('#group_3_1').click(function(){
var spliced = 200;
wordCount(spliced);
}) ;
$('#group_3_2').click(function(){
var spliced = 600;
wordCount(spliced);
}) ;
function wordCount(q) {
var content_text = $('.message1').text(),
char_count = content_text.length;
if (char_count != 0)
var word_count = q - content_text.replace(/[^\w ]/g, "").split(/\s+/).length;
$('.word_count').html(word_count + " words remaining...");
$('.message1').keyup(function() {
wordCount(q);
});
try
{
if (new Number( word_count ) < 0) {
$(".word_count").attr("id","bad");
}
else {
$(".word_count").attr("id","good");
}
} catch (error)
{
//
}
};
HTML:
<input type="checkbox" name="entry.3.group" value="1/6" class="size1" id="group_3_1">
<input type="checkbox" name="entry.3.group" value="1/4" class="size1" id="group_3_2">
<div id="entry.8.single" class="message1" style="height: 400px; overflow-y:scroll; overflow-x:hidden;" contenteditable="true"> </div>
<span class="word_count" id="good"></span>
Thanks in advanced!
This is causing an infinite loop if (new Number(word_count) < 0) {.
Your code is a mess altogether. Just study and start with more basic concepts and start over. If you want to describe your project to me in a comment, I would be glad to show you a good, clean, readable approach.
Update:
Part of having a good architecture in your code is to keep different parts of your logic separate. No part of your code should know about or use anything that isn't directly relevant to it. Notice in my word counter that anything it does it immediately relevant to its word-counter-ness. Does a word counter care about what happens with the count? Nope. It just counts and sends the result away (wherever you tell it to, via the callback function). This isn't the only approach, but I just wanted to give you an idea of how to approach things more sensefully.
Live demo here (click).
/* what am I creating? A word counter.
* How do I want to use it?
* -Call a function, passing in an element and a callback function
* -Bind the word counter to that element
* -When the word count changes, pass the new count to the callback function
*/
window.onload = function() {
var countDiv = document.getElementById('count');
wordCounter.bind(countDiv, displayCount);
//you can pass in whatever function you want. I made one called displayCount, for example
};
var wordCounter = {
current : 0,
bind : function(elem, callback) {
this.ensureEditable(elem);
this.handleIfChanged(elem, callback);
var that = this;
elem.addEventListener('keyup', function(e) {
that.handleIfChanged(elem, callback);
});
},
handleIfChanged : function(elem, callback) {
var count = this.countWords(elem);
if (count !== this.current) {
this.current = count;
callback(count);
}
},
countWords : function(elem) {
var text = elem.textContent;
var words = text.match(/(\w+\b)/g);
return (words) ? words.length : 0;
},
ensureEditable : function(elem) {
if (
elem.getAttribute('contenteditable') !== 'true' &&
elem.nodeName !== 'TEXTAREA' &&
elem.nodeName !== 'INPUT'
) {
elem.setAttribute('contenteditable', true);
}
}
};
var display = document.getElementById('display');
function displayCount(count) {
//this function is called every time the word count changes
//do whatever you want...the word counter doesn't care.
display.textContent = 'Word count is: '+count;
}
I would do probably something like this
http://jsfiddle.net/6WW7Z/2/
var wordsLimit = 50;
$('#group_3_1').click(function () {
wordsLimit = 200;
wordCount();
});
$('#group_3_2').click(function () {
wordsLimit = 600;
wordCount();
});
$('.message1').keydown(function () {
wordCount();
});
function wordCount() {
var text = $('.message1').text(),
textLength = text.length,
wordsCount = 0,
wordsRemaining = wordsLimit;
if(textLength > 0) {
wordsCount = text.replace(/[^\w ]/g, '').split(/\s+/).length;
wordsRemaining = wordsRemaining - wordsCount;
}
$('.word_count')
.html(wordsRemaining + " words remaining...")
.attr('id', (parseInt(wordsRemaining) < 0 ? 'bad' : 'good'));
};
wordCount();
It's not perfect and complete but it may show you direction how to do this. You should use change event on checkboxes to change wordsLimit if checked/unchecked. For styling valid/invalid words remaining message use classes rather than ids.
I think you should use radio in place of checkboxes because you can limit 200 or 600 only at a time.
Try this like,
wordCount();
$('input[name="entry.3.group"]').click(function () {
wordCount();
$('.word_count').html($(this).data('val') + " words remaining...");
});
$('.message1').keyup(function () {
wordCount();
});
function wordCount() {
var q = $('input[name="entry.3.group"]:checked').data('val');
var content_text = $('.message1').text(),
char_count = content_text.length;
if (char_count != 0) var word_count = q - content_text.replace(/[^\w ]/g, "").split(/\s+/).length;
$('.word_count').html(word_count + " words remaining...");
try {
if (Number(word_count) < 0) {
$(".word_count").attr("id", "bad");
} else {
$(".word_count").attr("id", "good");
}
} catch (error) {
//
}
};
Also you can add if your span has bad id then key up should return false;
See Demo

jquery - filtering of html elements on page issue

I have created a javascript filter that is working but not all the time. To first see this in action, visit the following link. On the left side, click on the Bridgestone e6 link under "Brand Model". It returns nothing, but in reality it should return 3 products in the view.
The way the filter works is as follows. I grab the value of the item clicked on the sidebar, then I search the html elements in the main view to see if there are any matches. If there are, I only show those products in the view and hide the rest.
The javascript that takes care of this is (also you can see it here):
Is it some whitespace issue or something incorrect in my JS? I tried to use the jQuery trim function to no avail.
The javascript:
var noProductMatches = jQuery('.no-products-found');
jQuery('#filter-by-brand li a').click(function()
{
noProductMatches.hide();
var brandNameSelected = jQuery(this).html();
var productVendorFromCollection = jQuery("#product-vendor");
var productContainer = jQuery('#product-collection .productBoxWrapper');
if (brandNameSelected == 'All Brands' )
{
productContainer.fadeIn("slow");
}
else
{
var results = jQuery(".productBoxWrapper")
.fadeOut(100)
.delay(100)
.filter(function()
{
return jQuery(this).html().indexOf(brandNameSelected) > -1 || jQuery(this).html().indexOf(productVendorFromCollection) > -1;
})
.each(function(index, item)
{
jQuery(item).fadeIn("slow");
});
if (results.length == 0)
{
noProductMatches.fadeIn();
}
}
});
jQuery('#filter-by-model li a').click(function()
{
noProductMatches.hide();
var brandNameSelected = jQuery.trim(jQuery(this).html());
var productContainer = jQuery('#product-collection .productBoxWrapper');
if (brandNameSelected == 'Any Model' )
{
productContainer.fadeIn("slow");
}
else
{
var results = productContainer
.fadeOut(100)
.delay(100)
.filter(function()
{
return jQuery.trim(jQuery(this).html()).indexOf(brandNameSelected) > -1;
})
.each(function(index, item)
{
jQuery(item).fadeIn("slow");
});
if (results.length == 0)
{
noProductMatches.fadeIn();
}
}
});
jQuery('#filter-by-price li a').click(function()
{
noProductMatches.hide();
var priceRangeSelectedItem = jQuery(this).html();
var minSelectedPrice = parseInt( jQuery(this).attr("name") );
var maxSelectedPrice = parseInt( jQuery(this).attr("title") );
var productContainer = jQuery('#product-collection .productBoxWrapper');
if (priceRangeSelectedItem == 'Any Price')
{
productContainer.fadeIn("slow");
}
else
{
var results = jQuery(".productBoxWrapper")
.fadeOut(100)
.delay(100)
.filter(function()
{
var minProductPrice = parseInt( jQuery(this).find("#lowestPriceRange").html() );
var maxProductPrice = parseInt( jQuery(this).find("#highestPriceRange").html() );
//alert(minProductPrice);
//alert(maxProductPrice);
return (minProductPrice >= minSelectedPrice && maxProductPrice <= maxSelectedPrice);
})
.each(function(index, item)
{
jQuery(item).fadeIn("slow");
});
if (results.length == 0)
{
noProductMatches.fadeIn();
}
}
});
The problem is that it is mixed case. In the menu it says Bridgestone e6 but on the page it says Bridgestone E6, with an uppercase E. Either you have to make everything lowercase when you search our make sure they are equal in the menu and on the page.

jQuery password generator

I have the following JS code that checks a password strength and also creates a random password as well. What I want to do is edit the code so that instead of putting the generated password inside the password field it will put it inside a span tag with say an id of randompassword. In addition that I would like it so that by default there will be a random password inside the span tag and then when the user clicks the button it will generate another one. And also move the link to be next to span tag rather than the password box.
Thanks.
Here is the code:
$.fn.passwordStrength = function( options ){
return this.each(function(){
var that = this;that.opts = {};
that.opts = $.extend({}, $.fn.passwordStrength.defaults, options);
that.div = $(that.opts.targetDiv);
that.defaultClass = that.div.attr('class');
that.percents = (that.opts.classes.length) ? 100 / that.opts.classes.length : 100;
v = $(this)
.keyup(function(){
if( typeof el == "undefined" )
this.el = $(this);
var s = getPasswordStrength (this.value);
var p = this.percents;
var t = Math.floor( s / p );
if( 100 <= s )
t = this.opts.classes.length - 1;
this.div
.removeAttr('class')
.addClass( this.defaultClass )
.addClass( this.opts.classes[ t ] );
})
.after('Generate Password')
.next()
.click(function(){
$(this).prev().val( randomPassword() ).trigger('keyup');
return false;
});
});
function getPasswordStrength(H){
var D=(H.length);
if(D>5){
D=5
}
var F=H.replace(/[0-9]/g,"");
var G=(H.length-F.length);
if(G>3){G=3}
var A=H.replace(/\W/g,"");
var C=(H.length-A.length);
if(C>3){C=3}
var B=H.replace(/[A-Z]/g,"");
var I=(H.length-B.length);
if(I>3){I=3}
var E=((D*10)-20)+(G*10)+(C*15)+(I*10);
if(E<0){E=0}
if(E>100){E=100}
return E
}
function randomPassword() {
var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$_+?%^&)";
var size = 10;
var i = 1;
var ret = ""
while ( i <= size ) {
$max = chars.length-1;
$num = Math.floor(Math.random()*$max);
$temp = chars.substr($num, 1);
ret += $temp;
i++;
}
return ret;
}
};
$(document)
.ready(function(){
$('#password1').passwordStrength({targetDiv: '#iSM',classes : Array('weak','medium','strong')});
});
// you can use another improved version to generate password as follows
//Define
function wpiGenerateRandomNumber(length) {
var i = 0;
var numkey = "";
var randomNumber;
while( i < length) {
randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
if ((randomNumber >=33) && (randomNumber <=47)) { continue; }
if ((randomNumber >=58) && (randomNumber <=90)) { continue; }
if ((randomNumber >=91) && (randomNumber <=122)) { continue; }
if ((randomNumber >=123) && (randomNumber <=126)) { continue; }
i++;
numkey += String.fromCharCode(randomNumber);
}
return numkey;
}
// Call
var myKey=wpiGenerateRandomNumber(10); // 10=length
alert(myKey);
// Output
2606923083
This line:
$(this).prev().val( randomPassword() ).trigger('keyup');
is inserting the value after a click. So you can change that value to stick the password wherever you want it. For example you could change it to:
$('span#randompassword').html(randomPassword());
You could also run this when the page loads to stick something in that span right away:
$(document).ready(function(){
$('span#randompassword').html(randomPassword());
});
//Very simple method to generate random number; can be use to generate random password key as well
jq(document).ready( function() {
jq("#genCodeLnk").click( function() {
d = new Date();
t = d.getTime();
jq("#cstm_invitecode").val(t);
});
});

Categories