Issue related to Jquery event - javascript

I have following Jquery
$('#txtSearch_text').attrchange(function (attrName) {
if (counter > 0) {
var contains = $('#txtSearch_text').attr('class').indexOf("validation");
if ($('#txtSearch_text').val() == '' && contains <= -1) {
$('#txtSearch_text').addClass('validation');
}
else if ($('#txtSearch_text').val() != '' && contains >= 0) {
$('#txtSearch_text').removeClass('validation');
}
}
//counter = 1;
});
The above jquery fires when txtSearch textbox changes any attribute. It works ok. but i want to fire above Jquery for multiple TextBoxes.. so if i have 4 TextBox then i will have to write Jquery 4 times for 4 different TextBox.
is there any way to write above jquery only one time for all TextBox ??
Thanks

You can pass comma seprated selector for all four textboxes. and inside use $(this) to get current object reference.Like this :
$('#txtSearch_text,#txtSearch_second,#txtSearch_third,#txtSearch_fourth').attrchange(function (attrName) {
if (counter > 0) {
var contains = $(this).attr('class').indexOf("validation");
if ($(this).val() == '' && contains <= -1) {
$(this).addClass('validation');
}
else if ($(this).val() != '' && contains >= 0) {
$(this).removeClass('validation');
}}});

Add a common class like txtSearch_text to all 4 elements then use it as a selector to target them
$('.txtSearch_text').attrchange(function (attrName) {
if (counter > 0) {
var contains = $(this).attr('class').indexOf("validation");
if ($(this).val() == '' && contains <= -1) {
$(this).addClass('validation');
} else if ($(this).val() != '' && contains >= 0) {
$(this).removeClass('validation');
}
}
//counter = 1;
});

Related

Alternative for DOMSubtreeModified jQuery

How can I write an alternative function for DOMSubtreeModified?
$('html').bind('DOMNodeInserted DOMNodeRemoved', function(event) {
var structure = $(event.target).closest(".form--group");
structure.find(".thevoornaam, .date_of_birth, .stepbirthVal, .livingkid, .right, .limitSelected, .pijlers, .total_pijlers").on("keyup change DOMSubtreeModified", function() {
if (structure.find(".thevoornaam").val().length > 1 && structure.find(".date_of_birth").val().length > 1 && structure.find('.stepbirthVal').html() == "" && structure.find(".livingkid").is(':checked') && structure.find(".right").is(':checked') && structure.find(".limitSelected:checked").val() == "1" && structure.find(".pijlers").val() != null && structure.find(".total_pijlers").val() != null) {
$("#stepbirth").removeClass("disabled");
} else if (structure.find(".thevoornaam").val().length > 1 && structure.find(".date_of_birth").val().length > 1 && structure.find('.stepbirthVal').html() == "" && structure.find(".livingkid").is(':checked') && structure.find(".right").is(':checked') && structure.find(".limitSelected:checked").val() == "0") {
$("#stepbirth").removeClass("disabled");
} else {
$("#stepbirth").addClass("disabled");
}
});
});
This function is working fine but i am getting this message in browser console.
[Violation] Added synchronous DOM mutation listener to a event. Consider using MutationObserver to make the page more responsive.
Can anyone help me with this?
Thanks in advance.

Rewrite script from js to jquery

I have a script that I want to make more bulletproof. At the moment the page breaks because class box-tip is not found. To make this bulletproof and not throw an error how can I rewrote the below code to jquery getting the same results as js
function applyRecommendedSleeveLength(selectedVal) {
if (selectedVal !== undefined) {
var recommendedVal = map[selectedVal.trim()];
var selected = $('.attribute__swatch--selected:first div').text().trim();
if (recommendedVal === null || recommendedVal === undefined) {
selectedVal = $('.attribute__swatch--selected:first div').text().trim();
recommendedVal = map[selectedVal.trim()];
}
if (selected === null || selected === '' || selected === undefined) return;
var recommendedLis = document.querySelectorAll('[class*="attribute__swatch--length-' + recommendedVal + '"] div');
recommendedLis.forEach(function(recommendedLi, i) {
if (recommendedLi !== null && recommendedLi !== undefined) {
recommendedLi.classList.add('showBorder');
$('.box-tip').show();
var currentPosition = $('.showBorder').parent().position().left;
var sleeveRecom = document.getElementsByClassName('box-tip');
var info = sleeveRecom.length ? sleeveRecom[0] : false;
info.style.paddingLeft = currentPosition + -75 + 'px';
}
});
}
}
If you want to check if the div exists, you can use this (using JQuery):
if ( $('.box-tip').length != 0 ){
//do something
}
OR- since you've edited your post- without JQuery:
if ( document.getElementsByClassName('box-tip').length != 0 ){
//do something
}
Just use jQuery for all of this. If the class doesn't exist the jQuery methods won't cause errors
function applyRecommendedSleeveLength() {
$('.box-tip').show().first().css('paddingLeft', (currentPosition - 75) + 'px');
}

Jquery if keyup else default value

I have a textbox whose value comes from database but if a user changes the value then this value needs to be used in a calculation.
$('#ecost input.ecost').keyup(function(){
if (!isNaN(this.value) && this.value.length != 0) {
var Cost = $(this).val();
}
});
and
var cost = $('input.ecost1').val();
I need if keyup function for user enter value (first code example) else default database value (second code example). How can I write this if/else condition?
i need
if ($('#ecost input.ecost').keyup(function(){
if (!isNaN(this.value) && this.value.length != 0) {
var Cost = $(this).val();
}
}); )
else {
var cost = $('input.ecost1').val();
}
i know in if() code is wrong but above logic how to corrected
If I understand correctly, this is what is required.
var valueFromDB = getValueFromDB(); //Your function for calling database
var Cost = 0;
$('#ecost input.ecost').keyup(function(){
if (!isNaN(this.value) && this.value.length != 0) {
Cost = $(this).val();
}
else{
Cost = valueFromDB;
}
});
if-else in javascript works like this:
if(expression) {
//do this if expression is true
} else {
//do this if expression is false
}
Is it that you want?
var Cost = $('input.ecost1').val();
$('#ecost input.ecost').keyup(function(){
if (!isNaN(this.value) && this.value.length != 0) {
Cost = $(this).val();
}
}
You do not need to include the else if you provide a default value before you evaluate your input:
UPDATE as per comments below.
var Cost = 123; // default value;
$('#ecost input.ecost').keyup(function(){
if (!isNaN(this.value) && this.value.length != 0) {
Cost = this.value;
}
});
Thank you for the answers, I have this problem also and I edit #onerror answer. It works well
var search = $("#teacher_year_filter").val();
$("#teacher_year_filter").on("keyup", function() {
if (!isNaN(this.value) && this.value.length != 0) {
search = this.value
}
var table_1 = table1.column(3).search(search).draw();
});
var table_2 = table1.column(3).search(search).draw();
It will filter the default value in the input, and once we type (keyup), then it will filter using the current input.

wordwrap for textarea using javascript or jquery

I need functionality that textarea should contain max 5 lines and
each line should contain max 15 chars, when user writes 2 words
e.g. 123456 123456789 and if that line char limit exceeds 15, then
it should bring the 2nd word in next line along with \n char in first line
(means 123456 will be in first line along with \n and 123456789 will be in 2nd)
,
I need to maintain \n(replacing <br>) in my db for some reasons.
i wrote this code, which gives fuzzy result in some conditions
<textarea onkeypress="charCountTextarea('txt1',event,'75','14')" id="txt1"></textarea>
var countLines=0;
var newLines;
function charCountTextarea(textAreaId,e,limit,lineLen)
{
newLines = $("#"+textAreaId).val().split("\n").length;
var t = $("#"+textAreaId)[0];
var lineIndex = t.value.substr(0, t.selectionStart).split("\n").length-1;
//console.log("new lines"+lineIndex);
if(newLines >= 5 && $("#"+textAreaId).val().split("\n")[lineIndex].length>lineLen)
{
if( e.keyCode!=8 && e.keyCode!=46 && e.keyCode!=33 && e.keyCode!=34 && e.keyCode!=35 && e.keyCode!=36 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
{
e.preventDefault();
return false;
}
}
else
if($("#"+textAreaId).val().split("\n")[lineIndex].length>=lineLen) // which will count the total line char condition
{
console.log($("#"+textAreaId).val().split("\n")[lineIndex][lineLen-1]);
if($("#"+textAreaId).val().split("\n")[lineIndex][lineLen-1].indexOf(" ")==-1 && e.keyCode!=8 && e.keyCode!=46 && e.keyCode!=33 && e.keyCode!=34 && e.keyCode!=35 && e.keyCode!=36 && lineIndex != 4 && newLines<5)
{
// to bring the word in next line
var str = $("#"+textAreaId).val(), replacement = '\n';
str = str.replace(/ ([^ ]*)$/,replacement+'$1');
$("#"+textAreaId).val(str);
}
else
if(e.keyCode!=8 && e.keyCode!=46 && e.keyCode!=33 && e.keyCode!=34 && e.keyCode!=35 && e.keyCode!=36 && lineIndex!=4 && newLines<5)
{
// to insert next line
insertTextAtCaret(document.getElementById(textAreaId), "\n");
}
}
if(e.keyCode == 13 && newLines >= 5)
{
//linesUsed.css('color', 'red');
e.preventDefault();
return false;
}
}
function charCountTextarea(textAreaId,e,limit,lineLen)
{
var code = e.charCode || e.keyCode;
newLines = $("#"+textAreaId).val().split("\n").length;
var t = $("#"+textAreaId)[0];
var lineIndex = t.value.substr(0, t.selectionStart).split("\n").length-1;
console.log('val t :'+$("#"+textAreaId).val()+' line index : '+lineIndex+' new lines '+newLines);
if(lineIndex == 10 && $("#"+textAreaId).val().split("\n")[lineIndex].length>(lineLen+1) && code!=8 && code!=46 && code!=33 && code!=34 && code!=35 && code!=36 && code!=37 && code!=38 && code!=39 && code!=40)
{
$("#"+textAreaId).val(($("#"+textAreaId).val()).substring(0, $("#"+textAreaId).val().length - 1));
alert('You are reached to limit');
return false;
}
if(lineIndex<5)
{
$("#"+textAreaId).val($("#"+textAreaId).val().wordWrap(lineLen, "\n", 0));
}
var countLine1 = $("#"+textAreaId).val().split("\n")[0].length;
if($("#"+textAreaId).val().split("\n")[lineIndex].length>lineLen) // which will count the total line char condition
{
console.log("In condition : ");
if(code!=8 && code!=46 && code!=33 && code!=34 && code!=35 && code!=36 && code!=37 && code!=38 && code!=39 && code!=40)
{
// to insert next line
insertTextAtCaret(document.getElementById(textAreaId), "\n");
}
}
}
You can not know if the input will be fed using keyboard. I could just use the mouse to paste a text there.
I would rely on a function that would constantly check the input and take the action you want, which I would execute using the setInterval() function once the textarea is focused, which then gets cleared using clearInterval() once the textarea loses focus.
And this function would use a RegExp to process the input and split it into necessary lines.
EDIT: Here's what I mean.
$('body').on('focus','#txt1',function(e) {
$(this).data('int',setInterval(checkInput,1));
}).on('blur','#txt1',function(e) {
clearInterval($(this).data('int'));
$(this).removeData('int');
});
function checkInput() {
var val = $('#txt1').val();
// process val here
$('#txt1').val(val);
}

Looping through javascript function

I'm trying to loop my if statements inside a while loop through my function. But it will only hit the first if statement and stop looping.
Sample:
while(No.length == 0 || Name.length == 0 || Tel.length == 0
|| Date.length == 0 || Email.length == 0) {
alert("Don't leave blank!");
if (No.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
return false;
}
if(Name.length == 0) {
document.getElementById('Name').style.visibility = 'visible';
return false;
}
//continues same if statement for rest of the elements variables.
}
It will only go to the first if statement and will not loop through it.
You are returning from inside the loop; that breaks the loop. If you want to continue on to the next round of the loop, use continue instead. If you want to break out of the loop, but not return from the entire function, use break.
Now if you are using a jQuery loop, because it's really just a function, you do use return:
$.each([1,2,3,4], function(index, x) {
if (x < 4) return true; // equivalent to continue
if (x == 4) return false; // equivalent to break
});
but that's only for jQuery loops, not Javascript standard ones.
The first error I can see is you should escape your alert with '\' for example :
alert('Don\'t leave blank!');
And the loop with just continue if you write this :
while(No.length == 0 || Name.length == 0 || Tel.length == 0 || Date.length == 0 || Email.length == 0) {
if (No.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
}
if(Name.length == 0) {
document.getElementById('Name').style.visibility = 'visible';
}
return true;
}
Could also try:
while(No.length == 0 && Name.length == 0 && Tel.length == 0 && Date.length == 0 && Email.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
document.getElementById('Name').style.visibility = 'visible';
continue;
}
Maybe this?
function test_all_fields() {
var No = document.getElementById('No');
var Nos = document.getElementById('Nos');
var Name = document.getElementById('Name');
// ...
Nos.style.visibility = (No.value.length==0) ? 'visible':'hidden';
Names.style.visibility = (Name.value.length==0) ? 'visible':'hidden';
//...
//continues same if statement for rest of the elements variables.
if (No.value.length >0 && Name.value.length >0 && Tel.value.length>0 && Date.value.length >0 && Email.value.length>0) {
return true;
}
else {
alert("Don\'t leave blank!");
return false;
}
}

Categories