Validate method to choose atleast one item from the list - javascript

I have a textbox which is used like a dropdown (using Css). This text box works like google suggest. When I type in a letter the textbox will be populated with the words matching the typed in letter.
on the form submit I need to write a validation that checks whether the user has selected an item from the list or not. If not show an error message.
HTML :
<ul class="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content ui-corner-all" id="ui-id-2" tabindex="0" style="display: none; width: 251px; top: 143.59375px; left: 28.1875px;">
<li class="ui-menu-item" role="presentation"><a id="ui-id-7" class="ui-corner-all" tabindex="-1">Mau Ramir - mau.ramir#cor.tls.com</a></li>
<li class="ui-menu-item" role="presentation"><a id="ui-id-8" class="ui-corner-all" tabindex="-1">Mah Gov - mg#gmail.com</a></li>
<li class="ui-menu-item" role="presentation"><a id="ui-id-9" class="ui-corner-all" tabindex="-1">Mdu ira - mk#gmail.com</a></li>
<li class="ui-menu-item" role="presentation"><a id="ui-id-10" class="ui-corner-all" tabindex="-1">Mdh Kn - mn#gmail.com</a></li>
</ul>
This is what I tried so far (but not working):
$.validator.addMethod("validSmartSrch", function (value, element) {
var notValid = 0;
var carts = $("[id^='ui-id-']").children()
valid = false;
if (value == $.inArray(value, carts)) {
valid = true
}
return valid;
}, 'Please select at least on item from the list');

Try this:
$.validator.addMethod("validSmartSrch", function (value, element) {
var carts = $("[id^='ui-id-']").map(function() {
return $(this).text();
}).get();
return $.inArray(value, carts) != -1;
}, 'Please select at least one item from the list');
You don't need to call .children(), since the elements matching that selector have no children. You need to convert the list of elements into an array of strings. .map() will get the text of each of them and return a jQuery collection of them, .get() will convert that to an ordinary array.
$.inArray just returns the position of the element in the array, so you need to compare it with -1, not value.

I finally ended up solving it this way.
$.validator.addMethod("validSmartSrch", function (value, element) {
var items = [];
var valid = false;
// push all the values into an array
$("[id^='ui-id-']").each(function (i, e) {
items.push($(e).text());
});
// check if the item exist in the array
var itemIndex = $.inArray(value, items);
if (itemIndex != -1) {
valid = true;
}
return valid;
}, 'Please select at least one item from the list');

Related

Why do my links on the search bar results not work when clicking on them?

JavaScript
window.addEventListener("onload", function(e){
document.querySelector('searchbar').addEventListener('click', search_album()) //adds a listener for the click event, which runs the function search_album()
document.querySelector('searchbar').addEventListener('blur', hide_results()) //adds a listener for the blur event, where the user loses focus from the input field, running the function hide_results()
});
function search_album() { //function to find the album via search bar
let input = document.getElementById('searchbar').value //input is the searchbar value
input = input.toLowerCase(); //turned into lowercase
let x = document.getElementsByClassName('albums'); // and x is the list of albums with the same class name
for (i = 0; i < x.length; i++){ //looping around for the number of albums in the list found in the php page
if (!x[i].innerHTML.toLowerCase().includes(input)) { //checking that the value entered is not found in the list of albums in the php page
//do not display the list of items that matches
}
else{
x[i].style.display = 'list-item'; //display the list of items that matches
}
}
}
function hide_results() { //function to run when the user click anywhere else in the page, not in the input field
let listItems = document.getElementById('list');
listItems.style.display = 'none'; //hide the results list
document.getElementById("searchbar").value = ""; //empty input field
}
HTML Code
<input id="searchbar" type="text" name="search" placeholder="Search Something..."
onkeyup="search_album()" onblur="hide_results()">
<ol id="list">
<li class="albums" id="#red">Red - Taylor Swift</li>
<li class="albums" id="#allartists">All Artists</li>
<li class="albums" id="#allalbums">All Albums of all Artists</li>
<li class="albums" id="#taylor">About Taylor Swift</li>
<li class="albums" id="#taylor">Taylor Swift Albums</li>
<li class="albums" id="#gigs">Upcoming GIGS</li>
</ol>
I was trying to make a searchbar so the user could enter any key and matching results would start to show up based on if the letter they entered is found in the word, hiding the results when the user clicks outside of the searchbar, showing the results again if inputting letters again, and allowing this process to repeat.

Form will not submit and gives error message

I have a form that contains clothing sizes. When a user selects a size, they are able to submit the form.
My issue is that the user is able to submit the form whether or not they have selected a size. The code is much more complicated but below is a break down of the form, with the add to bag button below.
<form>
<ul>
<li>
<ul>
<li class="size-value"></li>
<li class="size-value"></li>
<li class="size-value"></li>
<li class="size-value"></li>
</ul>
</li>
</ul>
</form>
<div class="mt10">
<input type="submit" class="modalAddToBagButton">
</div>
When a user selects a size, the class selected is added, so it would read class="size-value selected". This function is working fine. In my .js file I would like to add an if/else statement, where if an <li class="size-value"> has been given the class selected (the user has clicked this size), then the form will be submitted, however if NO <li> has the class selected, the form will throw an error message. Below is the section of my function that I believe I should add the if/else statement:
}).on('click', '.modalAddToBagButton', function(e) {
e.preventDefault();
// Add if/else statement here. if list items have a class selected, form can be submitted. if no list items have class selected, then display this error message.
$(this).closest("#dialog-addToBag").find('form').submit();
});
My question is: How do I write this if/else statement? I am not sure how to access the form and list items from my input button, since they are outside the div and are quite nested, and to listen for if any of the list items have been given the class selected so that the form can be submitted, and if not to throw an error message. Can anyone help with this?
UPDATE:
This function works in not submitting the form and displaying the error message when no size is selected, however even when a size is selected the error message still appears and the form will not submit. Can anyone figure out why?
.on('click', '.modalAddToBagButton', function(e) {
e.preventDefault();
var x = document.getElementsByClassName("es-value");
var i = x.length;
var selected = false;
while (i--) {
if (x[i].hasAttribute("selected")) {
selected = true;
}
}
if (selected == false) {
//Displays error
$("#errormessage").show();
} else {
$(this).closest("#dialog-addToBag").find('form').submit();
}
});
.on('click', '.modalAddToBagButton', function(e) {
e.preventDefault();
$form = $(this).closest("#dialog-addToBag").find('form');
if( $( ".size-value.selected" ).length ) { //ho
$form.submit();
} else {
$("#errormessage").show();
}
});
Try this one
How about
<div id="errorDiv"></div>
And inside your javascript function
}).on('click', '.modalAddToBagButton', function(e) {
e.preventDefault();
var x = document.getElementsByClassName("size-value");
var i = x.length;
var selected = false;
while(i--)
{
if (x[i].hasAttribute("selected"))
{
selected = true;
}
}
if(selected == false)
{
//Displays error
document.getElementById("errorDiv").innerHTML = "Please select a size.";
} else {
//Submit form
$(this).closest("#dialog-addToBag").find('form').submit();
}
});
This is how I would modify your HTML:
<form id="clothes-sizes">
<ul>
<li>
<ul>
<li class="size-value"></li>
<li class="size-value"></li>
<li class="size-value"></li>
<li class="size-value"></li>
</ul>
</li>
</ul>
<div class="mt10">
<input type="button" class="modalAddToBagButton">
</div>
</form>
And this is my jQuery that you can adapt, above I gave your form an id and using it in my jQuery below to locate it. I've also change the button type="button" and have moved it inside the <form>...</form> tag...
var form = $("#clothes-sizes");
var btn = form.find(".modalAddToBagButton");
btn
.unbind("click")
.bind("click", function ()
{
var selectedSizes = form.find("ul li.selected");
if (!selectedSizes.length)
{
alert("Please select a size.");
return false;
}
form.submit();
});
I modified your code a little bit :
$('.modalAddToBagButton').on('click', function(e) {
e.preventDefault();
var x = document.getElementsByClassName("size-value");
var i = x.length;
var selected = false;
while(i--) {
if (x[i].hasAttribute("selected")) {
selected = true;
}
}
console.log('selected: ',x[0].innerText);
if(selected == false) {
$("#errormessage").show();
} else {
$( "#dialog-addToBag").submit();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form>
<ul>
<li>
<ul>
<li class="size-value">1</li>
<li class="size-value" selected>2</li>
<li class="size-value">3</li>
<li class="size-value">4</li>
</ul>
</li>
</ul>
</form>
<div class="mt10">
<input type="submit" class="modalAddToBagButton">
</div>
See if this helps.

AngularJS ng-repeat with checkbox and filter

I have ng-repeat list, and I need to filter that list with checkbox. In checkbox I have three value, ERROR, WARNING, SUCCESS. If I check ERROR, show only error, if I check ERROR and WARNING show error and warning, same with success. But problem is, when I check ERROR box, list show only data with error, but when I check WARNING, they show all data in list, not only ERROR and WARNING data. For better explanation here is
> http://jsfiddle.net/ADukg/12574/
It's because of your toggleFilter() function
$scope.toggleFilter= function(filterValues) {
if ($scope.filterValue == undefined) {
$scope.filterValue = filterValues;
} else {
delete $scope.filterValue;
}
};
What is does:
When there is no filter, set the selected filter
When there is a filter, delete the current filter
So when you check ERROR, it sets ERROR as filter, but when you then click WARNING too, it triggers the else, and removes the current selection.
When you change your else to:
else {
delete $scope.filterValue;
console.log($scope.filterValue);
}
You can see it logs undefined when selecting more than 1 filter.
Because there is no any solution for this, here is my code how I fix this.
<div class="nav">
<div ng-repeat="filter in filters" ng-class="{sel: selection.indexOf(filterValue) == selected}">
<span class="filters_ct_status"></span>
<div ng-repeat="filterValue in filter.lists" style="float:left; padding: 5px">
<input type="checkbox" value="{{filterValue}}" ng-model="checked" ng-checked="selection.indexOf(filterValue) > -1" ng-click="toggleSelection(filterValue)">
<img ng-if="filterValue == 'Success'" src="assets/img/success.png" alt="success"/>
<img ng-if="filterValue == 'Warning'" src="assets/img/warning.png" alt="warning"/>
<img ng-if="filterValue == 'Error'" src="assets/img/error.png" alt="Error"/>
</div>
</div>
</div>
<div class="table_bench_info logBox" style="overflow-y: auto; height: 250px;">
<div class="list" ng-repeat="list in lists">
<span ng-if="listaFiltera.indexOf(list.class) !== -1">{{list.description}}</span>
</div>
</div>
and there is controller
$scope.filterValue = [];
// toggle selection for a given employee by name
$scope.toggleSelection = function(valueFilter) {
var idx = $scope.filterValue.indexOf(valueFilter);
if (idx > -1) {
$scope.filterValue.splice(idx, 1);
if($scope.filterValue.length == 0){
return $scope.listaFiltera = ['Error','Warning','Success'];
}else{
$scope.listaFiltera = $scope.filterValue.map(function(x) {
return x;
});
}
} else {
$scope.filterValue.push(valueFilter);
$scope.listaFiltera = $scope.filterValue.map(function(x) {
return x;
});
}
};
$scope.filters = [
{
lists: ['Error','Warning','Success']
}
];
We need push checked checkboxes to the array. And splice unchecked checkboxes from the array. Also, we need to check $scope.filterValue.length if we want multiple filters.

Matching input value with text inside span

I am able to match the input value with the span; however, I am only to retrieve the first span in the list I am comparing to. I need to compare to both list items. If the input is equal to either list item then it should be true. I am only getting a match for the first value.
HTML
<input id="search" type="text" class="input">
<ul> <li id="111" class="active" style="display: list-item;"><span style="display:none">111</span><span style="display: inline;">1-1-1</span></li>
<li id="222" style="display: list-item;"><span style="display:none">222</span><span style="display: inline;">2-2-2</span></li>
</ul>
JS
$('#search').on('input',function(){
if( $('#search').val() != $('ul li a span:eq(0)').text()){
return console.log('false')
}
else if( $('#search').val() == $('ul li a span:eq(0)').text()) { return console.log ('true') }
});
jsfiddle
I think that when you call .text() on a list of elements it will return the text of the first element. So you need to iterate through the spans you are interested in and check each one.
Here is an example:
$('#search').on('input',function(){
var found = false;
$('ul li a span:first-child').each(function (i, el){
if ($(el).text() == $('#search').val()) {
found = true;
return;
}
})
console.log(found);
});
Or, you could trim off all HTML tags with regex, and search the content.
function noTags(body) {
var regex = /(<([^>]+)>)/ig;
return body.replace(regex, "");
}

Alphabetically sort elements in sortable list with over 13 items

I'm using jQuery UI to create several, interconnected sortable lists
the html:
<div class="ulContainer">
<div class="liHdr">Unassigned</div>
<div class="ulWraper">
<ul class="connectedSortableUl un ui-sortable">
<li class="ui-state-default" style="">Frank Smith
<input type="hidden" class="rowName" value="frank.smith">
<input type="hidden" class="rowEmail" value="frank.smith#email.com">
<input type="hidden" class="rowId" value="8VNe0ZT1v0">
<input type="hidden" class="rowTeam" value="">
<div class="panel-options" style="float:right;"><i class="entypo-pencil"></i></div>
</li>
</ul>
</div>
</div>
and so on....several more of the same
the jQuery:
// create the sortable ui
$(".connectedSortableUl").sortable({
connectWith: ".connectedSortableUl",
placeholder: "ui-state-highlight",
create: function(event, ui) {
sort();
}
});
// custom sort function to sort our sortable lists
function sort() {
var sortableLists = $('.connectedSortableUl');
$(sortableLists).each(function(index, element) {
var listitems = $('li', element);
listitems.sort(function(a, b) {
var seeA = $(a).text().toUpperCase(); //just to see what's going on
var seeB = $(b).text().toUpperCase(); //just to see what's going on
return ($(a).text().toUpperCase() > $(b).text().toUpperCase())
});
$(element).append(listitems);
});
}
I expect this function to sort each list alphabetically with A at the
top and Z at the bottom
With short lists, 13 or fewer items, this function works as expected.
However, if a list has 14 or more items, something breaks down and the list is now longer sorted as expected.
Why does the logic break down with more than 13 list items, and what can I do to fix it or otherwise achieve the desired results?
jsFiddle example
Comparing two strings with > returns a boolean, but sort expects a number. Compare with localeCompare:
listitems.sort(function (a, b) {
var ta = $(a).text().toUpperCase();
var tb = $(b).text().toUpperCase();
return ta.localeCompare(tb);
});

Categories

Resources