How to find span with biggest data-item using jQuery - javascript

I have a div with spans inside. They have data-item attr. How to find div with the biggest data-item attr. They are numbers starting from 0. For example I have:
<div class="wrapper">
<span data-num="0">text</span>
<span data-num="1">text</span>
<span data-num="2">text</span>
<span data-num="3">text</span>
</div>
Updated: This is part of my code, it's about uploading files and one of the input fields is multiple. And I show in a div with separate spans image names of the files. Use should add multiple files so I need to find the biggest data-num and increment it for the next file.
function getFiles(document, window, index) {
var inputs = document.querySelectorAll( '.app-file' );
input.addEventListener( 'change', function( e )
{
var fileName = '';
var num = 0;
if( this.files && this.files.length > 1 || $(this).next().next().html()) {
var fileName = [];
for (var i = 0; i < this.files.length; ++i) {
fileName.push(this.files.item(i).name);
var comma = '';
if($(this).next().next().html()) {
comma = ',';
}
divName.innerHTML = divName.innerHTML + comma + '<span class="image_name" data-num="'+num+'">' + this.files.item(i).name + '</span><span class="glyphicon glyphicon-remove remove-file" data-toggle="tooltip" data-placement="top" title="Remove"></span>';
num++;
}
} else {
fileName = e.target.value.split('\\').pop();
divName.innerHTML = '<span class="image_wrapper"><span class="image_name" data-num="'+num+'">' +fileName + '</span><span class="glyphicon glyphicon-remove remove-file" data-toggle="tooltip" data-placement="top" title="Remove"></span></span>';
var maxIndexItem = $.makeArray($('#wrapper [data-num]')).reduce(function(result, item) {
return $(item).data('num') > $(result).data('num') ? $(item) : result;
});
alert(maxIndexItem.text());
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="file-name" data-input="corporate_document" id="corporates"></div>

HTML
<div class="wrapper">
<span data-num="0">text1</span>
<span data-num="1">text2</span>
<span data-num="2">text3</span>
<span data-num="3">text4</span>
<span>text5</span>
<span data-num="">text6</span>
</div>
JS
$(document).ready(function(){
var arr = [];
$(".wrapper span").each(function(){
var dataNum = $(this).data("num");
if (dataNum != null) {
arr.push(dataNum);
}
}).promise().done( function(){
var max = Math.max.apply(Math, arr);
alert( $(".wrapper").find("[data-num=" + max + "]").text());
} );
});
Refer Fiddle

I think this code can helps you:
var maxIndexItem = $.makeArray($('.wrapper [data-num]')).reduce(function(result, item) {
return $(item).data('num') > $(result).data('num') ? $(item) : result;
});
alert(maxIndexItem.text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="wrapper">
<span data-num="0">text 0</span>
<span data-num="1">text 1</span>
<span data-num="2">text 2</span>
<span data-num="3">text 3</span>
</div>

Related

Dynamic search by class name with JQuery

I want to make a dynamic search input according to the class names in the I'd like to span tags. However, I am having trouble listing the class name I found.
My aim; Displaying the class names matching the value entered in the input into the screen. Would you help me with this topic?
jQuery.expr[':'].contains = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
$(document).ready(function() {
$("#searchinput").keyup(function() {
var inputvalue = $("#searchinput").val();
var spantags = $("#iconlist span");
if (inputvalue.length == 0) {
spantags.show();
} else {
if (spantags.hasClass(inputvalue)) {
$("#iconlist span").hide();
}
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="search" placeholder="Ara" id="searchinput" />
<div id="iconlist">
<span class="test1">Deneme-1</span>
<span class="test2">Deneme-2</span>
<span class="test3">Deneme-3</span>
<span class="test4">Deneme-4</span>
</div>
You could try and use something like this to display the span where the class matches the input.
spantags.filter(function() {
return $(this).attr("class").indexOf(inputvalue) > -1;
}).show();
Demo
jQuery.expr[':'].contains = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
$(document).ready(function() {
$("#searchinput").keyup(function() {
var inputvalue = $("#searchinput").val();
var spantags = $("#iconlist span");
spantags.hide();
spantags.filter(function() {
return $(this).attr("class").indexOf(inputvalue) > -1;
}).show();
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="search" placeholder="Ara" id="searchinput" />
<div id="iconlist">
<span class="test1">Deneme-1</span>
<span class="test2">Deneme-2</span>
<span class="test3">Deneme-3</span>
<span class="test4">Deneme-4</span>
</div>
In the case that you're looking for an exact match, eg "test1" then you cause use
spantags.filter(":not(." + inputValue + ")").hide()
which says to hide everything that does not have the class you entered
(in the case where you want to match any letter, eg "t", use .attr("class").indexOf as in the other answer.
Updated snippet:
$(document).ready(function() {
$("#searchinput").keyup(function() {
var inputValue = $("#searchinput").val();
var spantags = $("#iconlist span");
spantags.show();
if (inputValue !== "") {
spantags.filter(":not(." + inputValue + ")").hide()
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="search" placeholder="Ara" id="searchinput" />
<div id="iconlist">
<span class="test1">Deneme-1</span>
<span class="test2">Deneme-2</span>
<span class="test3">Deneme-3</span>
<span class="test4">Deneme-4</span>
</div>

Using document.getElementById() to load images in Rails

Wanting to use document.getElementById() to load images into HTML in Rails.
Section of HTML code
<div id="dealersCards">
<span id = "D0"></span>
<span id = "D1"></span>
<span id = "D2"></span>
<span id = "D3"></span>
<span id = "D4"></span>
<span id = "D5"></span>
<span id = "D6"></span>
<span id = "D7"></span>
</div>
Corresponding Javscript code
function displayPlayerOneInitialCards()
{
length = dealerCards.length;
for( dealerCount = 0; dealerCount < length; dealerCount++)
{
newCard = dealerCards[dealerCount]
if(dealerCount == 0)
{
var cardToDisplay = newCard.cardFaceDown;
}
if(dealerCount == 1)
{
var cardToDisplay = newCard.cardToDisplay;
}
dealerIdName = 'D';
dealerIdName = dealerIdName + dealerCount.toString();
fileNameCard= '<img width="80" height="128" src="images/'+ (cardToDisplay.trim())+'" alt="Card"/>';
document.getElementById(dealerIdName).innerHTML = fileNameCard;
}
}
Error message:
No route matches [GET] "/game/BlackJack/images/H3.gif"
images are in app/assets.

Loop through div children and bold specific text not working

I have a suggestion dropdown under an input field and I am trying to make the text in the suggestion divs bold for the portion that matches what is currently in the input field.
e.g
input: AB
dropdown: ABCDE
My current code doesn't seem to be replacing the div content with the span
JS:
BoldMatchedText(inputToMatch:string){
var outerDiv = document.getElementById("dropdown");
if(outerDiv != null){
var subDiv = outerDiv.getElementsByTagName("div");
for (var i = 0; i < subDiv.length; i++){
subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
html:
<form>
<input type="text" id="dropdown-input">
<div id="dropdown">
<div class="reg-list-item">{{reg1}}</div>
<div class="reg-list-item">{{reg2}}</div>
<div class="reg-list-item">{{reg3}}</div>
<div class="reg-list-item">{{reg4}}</div>
</div>
</form>
You need to assign the result of calling the function replace.
subDiv[i].innerHTML = subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
function BoldMatchedText(inputToMatch) {
var outerDiv = document.getElementById("dropdown");
if (outerDiv != null) {
var subDiv = outerDiv.getElementsByTagName("div");
for (var i = 0; i < subDiv.length; i++) {
subDiv[i].innerHTML = subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
BoldMatchedText('Go');
#strong {
font-weight: 700
}
<form>
<input type="text" id="dropdown-input">
<div id="dropdown">
<div class="reg-list-item">Ele</div>
<div class="reg-list-item">Gomez</div>
<div class="reg-list-item">Rod</div>
<div class="reg-list-item">Enr</div>
</div>
</form>
Try this working sample with a benchmark. Compared with the previous answer.
function BoldMatchedText1(inputToMatch) {
var outerDiv = document.getElementById("dropdown");
if (outerDiv != null) {
var subDiv = outerDiv.getElementsByTagName("div");
for (var i = 0; i < subDiv.length; i++) {
subDiv[i].innerHTML = subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
function BoldMatchedText2(inputToMatch) {
var outerDiv = document.getElementById("dropdown");
if(outerDiv !== null) {
// Use `getElementsByClassName` instead using `getElementsByTagName('div')` JS will traverse your entire HTML file and look for all div tags, may take a little longer if you have a lot
var items = outerDiv.getElementsByClassName("reg-list-item");
// Getting the iteration length before the loop will give you performance benefit since items.length will not be checked per iteration
var len = items.length;
// Using while loop evaluating only if len is any positive number (true) except 0 (false) with reverse iteration making it faster
while(len--) {
var item = items[len].innerHTML;
// ONLY replace the text that contains the `inputToMatch`
if(item.indexOf(inputToMatch) !== -1) {
items[len].innerHTML = item.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
}
console.time('filter1');
BoldMatchedText1('Gom');
console.timeEnd('filter1');
console.time('filter2');
BoldMatchedText2('Gom');
console.timeEnd('filter2');
#strong {
font-weight: 700
}
<form>
<input type="text" id="dropdown-input">
<div id="dropdown">
<div class="reg-list-item">Ele</div>
<div class="reg-list-item">Gomez</div>
<div class="reg-list-item">Rod</div>
<div class="reg-list-item">Enr</div>
</div>
</form>

Angular 4 shopping cart functionality onclick to render text

i am new to angular 4 i want to develop a shopping cart functionality with some different render functionality in html. i can't able to find any solution till now.
already tried with jquery append function but it wont work in edit functionality in feature.
Below gif image shows my requirement
if i click any catagory it will directly append to top of the list with selected catagory.
Then if i click another catagory for same person it will apply after i click apply button
component.html
<ul class="selected-friends" id="appendtext">
</ul>
<ul class="list-friends" id="listFriends">
<div *ngFor="let data of result" [attr.id]="'FriendList' + data.id" #item>
<li class="checkedCatagory">
<div class="sf-left">
<h3>{{data.fullName}}</h3>
<span id="appendCatagoryList"></span>
</div>
<div class="sf-right">
<div class="edit-con sf-icon" data-toggle="collapse" [attr.data-target]="'#list' + data.id">
<i class="fa fa-list" aria-hidden="true"></i>
</div>
<div class="del-con sf-icon" [attr.id]="'#list' + data.id" (click)="delete(data.id)">
<i class="fa fa-trash-o" aria-hidden="true"></i>
</div>
</div>
</li>
<!-- Main List started -->
<li class="mainlistname" data-toggle="collapse" [attr.data-target]="'#list' + data.id">
<label class="catagory_list" [attr.for]="data.id"><input type="checkbox" [attr.id]="data.id" [attr.value]="data.id">
{{data.fullName}}</label>
</li>
<ul class="sub-friends-list collapse" [attr.id]="'list'+data.id">
<p class="mainlistname">Assign Category to this participant</p>
<p class="checkedCatagory">Edit or Assign another category to this participant</p>
<li *ngFor="let catagoryDetail of catagoryList">
<label class="catagory_list">
<input type="checkbox" class="catagory_list_checkbox" (click)="resize(data.id, catagoryDetail.id);addToCart(data.id,catagoryDetail.id,data.fullName,catagoryDetail.title)" [value]="catagoryDetail.id" [attr.id]="'catagoryId'+catagoryDetail.id">
<span [attr.id]="'catagoryName'+catagoryDetail.id">{{catagoryDetail.title}}</span>
<span class="pull-right fnt-16">AED</span>
<span class="pull-right fnt-16" id="'fee'+catagoryDetail.id">{{catagoryDetail.fee}}</span>
<!-- <p>18-99 Years Male/Female</p> -->
<p *ngIf="catagoryDetail.gender === 1">{{catagoryDetail.ageMinMale}}-{{catagoryDetail.ageMaxMale}} Years Male</p>
<p *ngIf="catagoryDetail.gender === 2">{{catagoryDetail.ageMinFemale}}-{{catagoryDetail.ageMaxFemale}} Years Female</p>
<p *ngIf="catagoryDetail.gender === 3">{{catagoryDetail.ageMinFemale}}-{{catagoryDetail.ageMaxFemale}} Years Male/Female</p>
</label>
<span class="checkedCatagoryhidden">
<p *ngFor="let catagorySelected of catagoryList" [attr.id]="'catagorySelected'+catagorySelected.id">
{{catagorySelected.title}} :
<span *ngIf="catagorySelected.gender === 1">{{catagorySelected.ageMinMale}}-{{catagorySelected.ageMaxMale}} Years Male</span>
<span *ngIf="catagorySelected.gender === 2">{{catagorySelected.ageMinFemale}}-{{catagorySelected.ageMaxFemale}} Years Female</span>
<span *ngIf="catagorySelected.gender === 3">{{catagorySelected.ageMinFemale}}-{{catagorySelected.ageMaxFemale}} Years Male/Female</span>
<span class="pull-right fnt-16">AED {{catagorySelected.fee}}</span>
</p>
</span>
</li>
<li class="checkedCatagory" class="apply checkedCatagory quantity">
<span class="quantity_catagory">Qty: <span [attr.id]="'sectionquantity'+data.id"></span></span>
<span class="catagory_amount">Total: AED <span [attr.id]="'sectionprize'+data.id"></span></span>
<button class="btnapplyqnty">Apply</button>
</li>
</ul>
</div>
</ul>
component.ts
addToCart(id, catagoryId, fullName, catTitle){
var currentUserObj = <any>{};
var self = this;
var sum;
currentUserObj[id] = {};
currentUserObj[id].participantid = id;
currentUserObj[id].participantName = fullName;
// console.log(fullName)
this.cart.cartItems[id] = {};
if(jQuery("#catagoryId"+catagoryId).is(":checked")) {
currentUserObj[id]['categoryInfo'] = [];
currentUserObj[id]['categoryName'] = [];
currentUserObj[id]['categoryFee'] = [];
var totalPrize = 0;
jQuery('#list'+id).find('.catagory_list input:checked').each(function(){
var currentCategoryId = jQuery(this).val();
var currentCatagoryName = jQuery('.catagory_list input:checked+#catagoryName'+catagoryId).text();
currentUserObj[id]['categoryInfo'].push(currentCategoryId);
currentUserObj[id]['categoryName'].push(jQuery(this).next('').text());
currentUserObj[id]['categoryFee'].push(Number(jQuery(this).next().next().next().text()));
});
sum = currentUserObj[id]['categoryFee'].reduce(this.add, 0);
currentUserObj[id].quantity = currentUserObj[id]['categoryInfo'].length;
this.cart.cartItems[id] = currentUserObj[id];
currentUserObj[id].participantTotalPrize = sum;
console.log('sum',sum)
this.saveCart();
} else {
var currentCategoryId;
currentUserObj[id]['categoryInfo'] = [];
currentUserObj[id]['categoryName'] = [];
currentUserObj[id]['categoryFee'] = [];
jQuery('#list'+id).find('.catagory_list input:checked').each(function(){
currentCategoryId = jQuery(this).val();
currentUserObj[id]['categoryName'].push(jQuery(this).next().text());
currentUserObj[id]['categoryInfo'].push(currentCategoryId);
currentUserObj[id]['categoryFee'].push(Number(jQuery(this).next().next().next().text()));
});
sum = currentUserObj[id]['categoryFee'].reduce(this.add, 0);
currentUserObj[id].participantTotalPrize = sum;
currentUserObj[id].quantity = currentUserObj[id]['categoryInfo'].length;
this.cart.cartItems[id] = currentUserObj[id];
if(currentUserObj[id].quantity === 0) {
console.log("completed delete", this.cart.cartItems[id])
delete self.cart.cartItems[id];
}
this.saveCart();
}
}
add(a, b) {
return a + b;
}
saveCart() {
if (window.localStorage) {
console.log("tfgb",this.cart);
sessionStorage.setItem('cart',JSON.stringify(this.cart));
}
}
resize(id, catagoryId) {
let navObj = this;
var appendSelectedCatagory = document.getElementById('appendtext');
jQuery(appendSelectedCatagory).prepend(jQuery('#FriendList'+id));
if(jQuery("#catagoryId"+catagoryId).is(":checked")) {
this.displaySelectedList(id, catagoryId);
var totalPrize = 0;
navObj.quantity = 0;
jQuery('#list'+id).find('.catagory_list input:checked').each(function(){
var currentCategoryId = jQuery(this).val();
navObj.eventRegistrationService.getEventCatagoriesList(navObj.eventId)
.subscribe((res)=>{
for(let i in res.data){
var catList = res.data[i];
if(catList.id == currentCategoryId){
totalPrize += catList.fee
navObj.quantity += 1;
}
}
jQuery('#sectionprize'+id).html(totalPrize);
jQuery('#sectionquantity'+id).html(navObj.quantity);
})
})
} else {
this.eventChecked -= 1;
var totalPrize = 0;
navObj.quantity = 0;
jQuery('#list'+id).find('.catagory_list input:checked').each(function(){
var currentCategoryId = jQuery(this).val();
navObj.eventRegistrationService.getEventCatagoriesList(navObj.eventId)
.subscribe((res)=>{
for(let i in res.data){
var catList = res.data[i];
if(catList.id == currentCategoryId){
totalPrize += catList.fee
navObj.quantity += 1;
}
}
jQuery('#sectionprize'+id).html(totalPrize)
jQuery('#sectionquantity'+id).html(navObj.quantity)
})
})
this.checkedCatagory.pop(catagoryId);
let checkBoxList = '#appendtext #list'+id;
if(jQuery(checkBoxList+' :checkbox:checked').length == 0){
jQuery('#listFriends').append(jQuery('#FriendList'+id));
jQuery("#FriendList"+id+ " input[type='checkbox']").prop("checked", false);
sessionStorage.removeItem(id);
}
}
}
displaySelectedList(id, catagoryId){
this.eventChecked += 1;
let getselectList = sessionStorage.getItem('selectedFriends');
jQuery('#appendCatagoryList').append(jQuery('#catagorySelected'+catagoryId))
}
delete(id){
jQuery('#listFriends').append(jQuery('#FriendList'+id));
jQuery("#FriendList"+id+ " input[type='checkbox']").prop("checked", false);
console.log('asdasdsa',id);
//this.quantity = 0;
sessionStorage.removeItem(id);
}

Add and Remove class to click a dynamic Button

Trying to Add and Remove class to click dynamic Buttons, means this button <button class="one"></button> get class dynamically like this: <button class="one text1">text1</button>
So if button one has class .text1 and by click this add class .hide to list item <li class="text1"> like <li class="text1 show">
Same for button two <button class="two"></button> and by click add class <li class="text2 show">
Note: when click button two, then should remove class .show and add new class .hideto button one.
Main HTML:
<div id="main-id">
<button class="one"></button>
<button class="two"></button>
<ul>
<li>
<!--List 1-->
<div class="label">
text1
</div>
</li>
<li>
<!--List 2 is Same-->
<div class="label">
text1
</div>
</li>
<li>
<!--List 3 is different-->
<div class="label">
text2
</div>
</li>
</ul>
</div>
Script:
$('.label a').each(function() {
var $this=$(this);
$this.closest('li').addClass($this.text());
});
// Combine This
$('button').each(function(){
var liInd = 0;
var cl = '';
var txt = '';
var clses = [];
var ind = $('button').index($(this)) + 1;
$('li').each(function(){
if(clses.indexOf($(this).attr('class')) === -1){
clses.push($(this).attr('class'));
liInd = liInd + 1;
}
if(ind === liInd){
cl = $(this).attr('class');
txt = $(this).find('a').text();
return false; //break
}
});
$('button:nth-child(' + ind + ')').addClass(cl);
$('button:nth-child(' + ind + ')').text(txt);
});
See Example on Fiddle
I have tried this by add/remove class by click function, but problem is Buttons get class dynamically from List items, so I'm not able to target button.
Any suggestion for other way to do this by JS/ Jquery?
Here is an alternative solution
$('button').each(function () {
var liInd = 0;
var cl = '';
var txt = '';
var clses = [];
var ind = $('button').index($(this)) + 1;
$('li').each(function () {
if (clses.indexOf($(this).attr('class')) === -1) {
clses.push($(this).attr('class'));
liInd = liInd + 1;
}
if (ind === liInd) {
cl = $(this).attr('class');
txt = $(this).find('a').text();
return false; //break
}
});
if (txt != '') {
$('button:nth-child(' + ind + ')').addClass(cl);
$('button:nth-child(' + ind + ')').text(txt);
}
});
$('button').click(function () {
if ($(this).attr('class')[0] == 'all') {
showAll();
return false; // end this function
}
var allCls = $(this).attr('class').split(' ');
$('li').each(function () {
if (allCls.indexOf($(this).find('a').text()) > -1) {
$(this).closest('li').removeClass('show').addClass('hide');
} else {
$(this).closest('li').removeClass('hide').addClass('show');
}
});
});
function showAll() {
$('li').removeClass('hide').addClass('show');
}
Fiddle: https://jsfiddle.net/taleebanwar/yaLm4euk/13/
DEMO
$('.label a').each(function () {
var $this = $(this);
$this.closest('li').addClass($this.text());
});
// Combine This
$('button').each(function () {
var liInd = 0;
var cl = '';
var txt = '';
var clses = [];
var ind = $('button').index($(this)) + 1;
$('li').each(function () {
if (clses.indexOf($(this).attr('class')) === -1) {
clses.push($(this).attr('class'));
liInd = liInd + 1;
}
if (ind === liInd) {
cl = $(this).attr('class');
txt = $(this).find('a').text();
return false; //break
}
});
$('button:nth-child(' + ind + ')').addClass(cl);
$('button:nth-child(' + ind + ')').text(txt);
});
$(document).on('click', 'button',function(e){
var textClass = $.grep(this.className.split(" "), function(v, i){
return v.indexOf('text') === 0;
}).join();
console.log(textClass);
$('li').removeClass('show').addClass('hide')
$('li').each(function(){
if($(this).hasClass($.trim(textClass))){
$(this).removeClass('hide').addClass('show');
} else {
$(this).removeClass('show').addClass('hide');
}
})
})
.show{display:list-item;}
.hide{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="main-id">
<button class="one"></button>
<button class="two"></button>
<ul>
<li>
<!--List 1-->
<div class="label">
text1
</div>
</li>
<li>
<!--List 2 is Same-->
<div class="label">
text1
</div>
</li>
<li>
<!--List 3 is different-->
<div class="label">
text2
</div>
</li>
</ul>
</div>

Categories

Resources