"label.error" seems to always be present on every bootstrap tab - javascript

I can't figure out why $('label.error') is showing up on every bootstrap tab when that particular element should only show on 1 tab. I have a field that's not passing validation on a bootstrap tab and thus a label with class error is being appended the DOM on the violating field. But, I can't seem to get my code to land on the specific tab that has the violating field. What am I doing wrong in the code below? isErrorPresent should only be true on 1 particular tab but EVERY tab is showing it to be true...
$("#" + formId).validate({ignore:""}).form(); // ignore:"" allows for hidden fields to be validated as well
$(".tab-content").find("div.tab-pane").each(function (index, tab) {
var id = $(tab).attr("id");
$('a[href="#' + id + '"]').click();
alert('processing tab ' + id);
var isErrorPresent = $('div.tab-pane, div.active').find('label.error').length > 0;
alert(isErrorPresent);
// if (isErrorPresent) {
// alert("label.error detected...");
// hasError = true;
// return false; // Break .each loop and return to page
// }
});

Without seeing more markup, this is what I am thinking:
You are doing this:
var isErrorPresent = $('div.tab-pane, div.active').find('label.error').length > 0;
The selector has a comma in it, meaning you want to checking on div.tab-pane && div.active
Is that what you wanted? Maybe you meant to do this (no comma and no space):
var isErrorPresent = $('div.tab-pane.active').find('label.error').length > 0;

Figured it out with #Red2678's help (thanks)...here's what's working for me now...
// Check all tabs for errors & show first tab that has errors
$(".tab-content").find("div.tab-pane").each(function (index, tab) {
var id = $(tab).attr("id");
$('a[href="#' + id + '"]').click();
$("#" + formId).validate().form();
var activeTab = $('div.tab-pane.active');
var isErrorPresent = false;
if ($(activeTab).find('label.error').length > 0) {
isErrorPresent = $(activeTab).find('label.error').css('display') !== 'none';
}
if (isErrorPresent) {
hasError = true;
return false; // Break .each loop and return to page
}
});

Related

While loop to hide div elements

I am trying to create searchable content with the help of some JS yet am having trouble hiding the content when there is no input in the search field.
Here is my script:
var $searchContainer = $("#search");
var $contentBoxes = $searchContainer.find(".content");
var $searchInput = $searchContainer.find("#search-input");
var $searchBtn = $searchContainer.find("#search-btn");
$searchBtn.on("click", searchContent);
$searchInput.on("input", searchContent);
while($searchInput == null) {
for($contentBoxes) {
hide();
}
}
function searchContent(){
var userInput;
//Check if call comes from button or input change
if($(this).is(":button")){
userInput = $(this).siblings("input").val();
} else {
userInput = $(this).val();
}
//make the input all lower case to make it compatible for searching
userInput = userInput.toLowerCase();
//Loop through all the content to find matches to the user input
$contentBoxes.each(function(){
var headerText = $(this).find(".title").text();
var contentText = $(this).find(".description").text();
//add the title and content of the contentbox to the searchable content, and make it lower case
var searchableContent = headerText + " " + contentText;
searchableContent = searchableContent.toLowerCase();
//hide content that doesn't match the user input
if(!searchableContent.includes(userInput)){
$(this).hide();
} else {
$(this).show();
}
});
};
I understand a while loop could have a condition where if userInput is equal to null it would loop through each content box and hide the element.
Something like this maybe?
while($searchInput == null) {
$contentBoxes.each(function(){
hide();
}
}
Any help would be greatly appreciated.
You would need to update your userInput variable every cycle of the loop because the userInput value never gets updated. Nonetheless this not a good way to do this because you will block your entire application.
There is no need for a loop, just use an if statement. Also, because this function gets executed when the value of the input is changed, there is no need to use this.
You could put this block of code beneath your $contentBoxes.each function:
$contentBoxes.each(function(){
var headerText = $(this).find(".title").text();
var contentText = $(this).find(".description").text();
//add the title and content of the contentbox to the searchable content, and make it lower case
var searchableContent = headerText + " " + contentText;
searchableContent = searchableContent.toLowerCase();
//hide content that doesn't match the user input
if(!searchableContent.includes(userInput)){
$(this).hide();
} else {
$(this).show();
}
});
if (userInput === null) {
$contentBoxes.each(function(){
$(this).hide();
});
}
I think it will be work like this. You just check if search input !== null and dont hide any content in this case
if($searchInput != null && !searchableContent.includes(userInput)){
$(this).hide();
} else {
$(this).show();
}

Error message append only once

I am trying to append an error message to html once there was no match in the search bar. I have a list and once there is no match the list items get display:none; That's when i want to have the message. The problem is that being inside a loop to iterate through the list this message is appended the same number of times as the number of list items.
Updated code: it seems the error message doesn't appear each time i search for a student that is not a match...unless i refresh the page. Also sometimes even when i have the matching student the error shows although it shouldn't.
//add search bar
$( ".page-header" ).append('<div class="student-search"></div>');
$( ".student-search" ).append('<input id="input-search" placeholder="Search for students..."/><button id="search">Search</button>');
$('.page').append('<div class="error"></div>');
$('.error').append('<p>"Student not found!"</p>');
$('.error').hide();
var found = true;
//myFunction
function myFunction() {
var input = document.getElementById("input-search");
var filter = input.value.toUpperCase();
var ul = document.getElementsByClassName("student-list");
var li = document.getElementsByTagName("li");
for (var i = 0; i < li.length; i++) {
var h = li[i].getElementsByTagName("h3")[0];
if (h.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
found = true;
} else {
li[i].style.display = "none";
console.log('Hello! Student is not found!');
found = false;
}
}
$('.pagination').hide();
if (found === false) {
$('.error').show();
}
}
//myFunction end
// when the input is empty return to page 1, empty the error div, show pagination,
$('#input-search').on('keyup', function() {
if($(this).val() === '') {
$('.error').empty();
go_to_page(0);
$('.pagination').show();
}
});
$('#search').click(function(){
myFunction();
});
Thanks,
Alina
I made a demo for you, I hope it's what you want:
https://jsfiddle.net/jondion/xpdof2jh/14/
First, every time the user makes a search, we need to remove all the previous errors. I added a variable found to track if the username matches the filter. I added conditions to show the search results.
Reset the .error when the input is empty.
$('input').on('keyup', function() {
if($(this).val() === '') {
$('.error').empty()
}
});

Input is not detecting that it is empty if removing text with "ctrl + a + backspace"

I am doing some easy div filtering with jQuery and input field. It is working, however it is not detecting that it is empty if I remove input using " Ctrl + a + backspace ", in other words if I select all text and remove it. What causes this?
It is not reordering divs back to default if using the keyboard commands but is going back to normal if you backspace every character.
This is how I do it:
$('#brandSearch').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis.length == 0) {
$('.card').show();
} else {
$('.card').each(function() {
var text = $(this).text().toLowerCase();
(text.indexOf(valThis) >= 0) ? $(this).parent().show(): $(this).parent().hide();
});
};
});
Your if block that handles the empty string is not showing the same elements that the else block hides. The else block calls .parent() but the if block does not.
So the else case shows or hides the parent of each .card element, but the if case shows the .card elements themselves—without unhiding their parents. See my comments added to the code (I also reformatted the conditional expression in the else for clarity):
$('#brandSearch').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis.length == 0) {
// Show all of the .card elements
$('.card').show();
} else {
$('.card').each(function() {
var text = $(this).text().toLowerCase();
// Show or hide the *parent* of this .card element
text.indexOf(valThis) >= 0 ?
$(this).parent().show() :
$(this).parent().hide();
});
};
});
Since it sounds like the non-empty-string case is working correctly, it should just be a matter of adding .parent() in the if block so it matches the others:
$('#brandSearch').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis.length == 0) {
// Show the parent of each .card element
$('.card').parent().show();
} else {
// Show or hide the parent of each .card element
$('.card').each(function() {
var text = $(this).text().toLowerCase();
text.indexOf(valThis) >= 0 ?
$(this).parent().show() :
$(this).parent().hide();
});
};
});
This is the kind of situation where familiarity with your browser's debugging tools would pay off big time. The .show() or .hide() methods manipulate the DOM, and by using the DOM inspector you could easily see which elements are being hidden and shown.
In fact, as a learning exercise I recommend un-fixing the bug temporarily by going back to your original code, and then open the DOM inspector and see how it reveals the problem. While you're there, also try out the JavaScript debugger and other tools.
If you use Chrome, here's an introduction to the Chrome Developer Tools. Other browsers have similar tools and documentation for them.
It seems to be working just fine:
$('#brandSearch').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis.length == 0) {
$('.card').show();
console.log("input is empty");
} else {
console.log("input is not empty");
$('.card').each(function() {
var text = $(this).text().toLowerCase();
(text.indexOf(valThis) >= 0) ? $(this).parent().show(): $(this).parent().hide();
});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="brandSearch">

make an anchor toggle function which appends data to textarea on click and removes on reclick

i m trying to make an anchor toggle function which appends data to textarea on click and removes on reclick. here is the jsfiddle.
`
function btnsInit()
{
var i, a = document.getElementById('btns').getElementsByTagName('a');
for (i = 0; i < a.length; ++i)
{
var str=document.getElementById('ta').value;
var index= str.indexOf(a[i]);
if(index!=-1)
{
a[i].onclick = btnClick;
}
else
{
str.replace(a[i],"_");
}
}
}
function btnClick(e)
{
document.getElementById('ta').value += this.firstChild.nodeValue + ',';
xPreventDefault(e);
return false;
}
`Please reply ASAP
Here is new js code, you can use it -
<div id='btns'>
<p>
<!-- adding id to element, helps to maintain the list
of element which have been clicked, and also helps in
distinguishing between two elements have same text.
Dont forget to add href="#' or href="javascript:void(0)"
else your page may refresh and form data will be lost -->
<a id="a1" href='#'>category</a>
</p>
<p>
<a id="a2" href='#'>url</a>
</p>
</div>
<textarea id='ta' rows='10' cols='20'></textarea></body>
Javascript -
window.onload = btnsInit;
var selected = {};//keeps list of selected links
function btnsInit() {
var i, a = document.getElementById('btns').getElementsByTagName('a');
for (i = 0; i < a.length; ++i) {
a[i].onclick = btnClick;
}
}
function btnClick(e) {
if (selected[this.id]) {
delete selected[this.id];//deleting if already been clicked
} else {
selected[this.id] = this.innerHTML;//adding to the selected list
}
updateTextArea();
xPreventDefault(e);
return false;
}
function updateTextArea() {
var ta = document.getElementById('ta');
var val = "";
for ( var id in selected) {
val += selected[id] + ",";
}
ta.value = val;//updating from selected list
}
function xPreventDefault(e) {
if (e && e.preventDefault)
e.preventDefault();
else if (window.event)
window.event.returnValue = false;
}
Problems with your code -
btnsInit was not actually assigning onclick listeners to <a> elements.
Re click on a link was not handled or not handled properly(if handled).
Use attribute/value href=' ' for a tag which is refreshing the page.
Update - questions asked in comments
Was my code not working as it was refreshing the page?
No, It was not. It was missing reclick handling and btnsInit was not working properly.
Is delete a predefined function?
delete is a JavaScript keyword, which delete an object property.
About delete keyword
What is the use of 'this'?
this is another keyword which holds the reference of the object in context, in this case it holds the element clicked.
More about this keyword

how to select all class except the clicked element in JQuery?

I have a website developed on Drupal. I use a module called collapsiblock (it is basicly a JQuery plugin) to achieve accordion like effect. It is working fine with me (although it is in Beta). But I want to modify it so that when the user clicks on one item of the accordion the other items will collapsed.
In its current stats, it is working in a way that when the user click on one item, it will check if the item is already collapsed or expanded and it will make the item the opposite. That means if the user clicks on one item it will expand and if he/she clicks on another item it will also expand, but it will not collapse the previously clicked item.
You can see the code below. I know where should I add the code to collapse and how to collapse and expand. My question is: How do I select all the items that have the class '.collapsiblock' except the one that the user has clicked??
Note: the item that has the class '.collapsiblockCollapsed' get collapsed and if this class is removed from the item it get expanded.
// $Id: collapsiblock.js,v 1.6 2010/08/18 19:17:37 gagarine Exp $
Drupal.Collapsiblock = Drupal.Collapsiblock || {};
Drupal.behaviors.collapsiblock = function (context) {
var cookieData = Drupal.Collapsiblock.getCookieData();
var slidetype = Drupal.settings.collapsiblock.slide_type;
var defaultState = Drupal.settings.collapsiblock.default_state;
var slidespeed = parseInt(Drupal.settings.collapsiblock.slide_speed);
$('div.block:not(.collapsiblock-processed)', context).addClass('collapsiblock-processed').each(function () {
var id = this.id;
var titleElt = $(':header:first', this).not($('.content :header',this));
if (titleElt.size()) {
titleElt = titleElt[0];
// Status values: 1 = not collapsible, 2 = collapsible and expanded, 3 = collapsible and collapsed, 4 = always collapsed
var stat = Drupal.settings.collapsiblock.blocks[this.id] ? Drupal.settings.collapsiblock.blocks[this.id] : defaultState;
if (stat == 1) {
return;
}
titleElt.target = $(this).find('div.content');
$(titleElt)
.addClass('collapsiblock')
.click(function () {
var st = Drupal.Collapsiblock.getCookieData();
if ($(this).is('.collapsiblockCollapsed')) {
$(this).removeClass('collapsiblockCollapsed');
if (slidetype == 1) {
$(this.target).slideDown(slidespeed);
}
else {
$(this.target).animate({height:'show', opacity:'show'}, slidespeed);
}
// Don't save cookie data if the block is always collapsed.
if (stat != 4) {
st[id] = 1;
}
}
else {
$(this).addClass('collapsiblockCollapsed');
if (slidetype == 1) {
$(this.target).slideUp(slidespeed);
}
else {
$(this.target).animate({height:'hide', opacity:'hide'}, slidespeed);
}
// Don't save cookie data if the block is always collapsed.
if (stat != 4) {
st[id] = 0;
}
}
// Stringify the object in JSON format for saving in the cookie.
var cookieString = '{ ';
var cookieParts = [];
$.each(st, function (id, setting) {
cookieParts[cookieParts.length] = ' "' + id + '": ' + setting;
});
cookieString += cookieParts.join(', ') + ' }';
$.cookie('collapsiblock', cookieString, {path: Drupal.settings.basePath});
});
// Leave active blocks uncollapsed. If the block is expanded, do nothing.
if (stat == 4 || (cookieData[id] == 0 || (stat == 3 && cookieData[id] == undefined)) && !$(this).find('a.active').size()) {
$(titleElt).addClass('collapsiblockCollapsed');
$(titleElt.target).hide();
}
}
});
};
Drupal.Collapsiblock.getCookieData = function () {
var cookieString = $.cookie('collapsiblock');
return cookieString ? Drupal.parseJson(cookieString) : {};
};
UPDATE:
Problem has been solved by adding the following code:
$('.collapsiblock').not(this).each(function(){
$(this).addClass('collapsiblockCollapsed');
$(this.target).animate({height:'hide', opacity:'hide'}, slidespeed);
});
just above the following line:
$(this).removeClass('collapsiblockCollapsed');
Use the not selector.
Example:
$('.collapsiblock').click(function(){
$('.collapsiblock').not(this).each(function(){
$(this).slideUp();
});
$(this).slideDown();
})
Try this,This is a better way because if you use each function it will load and in the future when you have more than a thousand div it will take a long time to slide up and slide down.
Example:
$('.collapsiblock').click(function(){
$('.collapsiblock').not(this).slideUp();
$(this).slideDown();
});
You could keep track of which element has already been clicked with your own jquery click handler and jquery's data(...) function. Then filter iterating your .collapsiblock items with jquery's filter (...) function to include the items you need.

Categories

Resources