How can I check how many elements are inside one field? - javascript

I have a piece of code in my HTML:
<div class="all-homes">
<div class="home">RED</div>
<div class="home">WHITE</div>
<div class="home">GREEEN</div>
<div class="home">BLUE</div>
</div>
I need to remove home from the list only if in the class of all-homes there are more than 1 home. Otherwise there should be a warning message saying that you can't remove home because there is just 1 home in the list. Would that be possible?
I was try:
<script>
function myFunction() {
if (document.getElementsByClassName("all-homes") "how to gete the right informatuion here" ) {
event.run();
}else {
event.preventDefault(); // prevent form submit
swal({
title: "Remove Home",
text: " text",
icon: "warning",
});
}
}
</script>
My remove Button:
<p>{{home_at_homes_pk}}</p> //this is the home list
<form method='post' action="{% url 'home_at_homes_delete' home_at_homes_pk=home_at_homes_slug%}">
{% csrf_token %}
<button type="submit" onclick="myFunction()" id="remove-location" class="txt-button alert icon-link" style="margin-top: 0rem;">
<span class="icon">
<i class="fas fa-trash-alt"></i>
</span>
Remove Home
</button>
</form>
update from comment:
I want to remove the whole elements until one is left
Thank you very much

function myFunction() {
var all = document.getElementsByClassName("all-homes")[0];
while (all.children.length > 1) {
console.log(all.children.length)
all.children[0].remove();
}
}

Hopefully answer your question
const red = document.getElementById('red');
jQuery('#remove').on('click', () => {
const elements = $('#red').children('.home');
if(elements.length > 1) {
for( let i=0; i< elements.length - 1; ++i){
$(elements[i]).remove();
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="red">
<div class="home">WHITE</div>
<div class="home">GREEN</div>
<div class="home">BLUE</div>
</div>
<button id="remove">Remove home</button>

Related

Displaying elements based on search

I would like the .box elements to show/hide based on the words the user searches for, so for example if a user types in 'Title2 Title1' because those words exists inside box one and two they will remain visible with the renaming .box elements hiding. All the text within the .box elements needs to be searchable not just that in the .title element.
Below is how far I've got. It's almost there but it's not quite working as hoped.
Any help would be great.
Many thanks.
<input placeholder="Search" id="search" type="text" />
<div class="box">
<div class="title">Box Title1</div>
<div class="content">
Box title one content
</div>
</div>
<div class="box">
<div class="title">Box Title2</div>
<div class="content">
Box title two content
</div>
</div>
<div class="box">
<div class="title">Box Title3</div>
<div class="content">
Box title three content
</div>
</div>
<script>
$("#search").on("input", function () {
var search = $(this).val();
if (search !== "") {
var searchArray = search.split(" ");
searchArray.forEach(function(searchWord) {
$(".box").each(function () {
if($(this).is(':contains('+ searchWord +')')) {
$(this).show();
} else {
$(this).hide();
}
});
});
} else {
$(".box").show();
}
});
</script>
You need to use a different search method. :contains does not work as you expect. Consider the following example.
$(function() {
function filter(e) {
var term = $(e.target).val();
if (term.length < 3) {
$(".box").show();
return;
}
$(".box").each(function(i, el) {
if ($(".content", el).text().indexOf(term) >= 0) {
$(el).show();
} else {
$(el).hide();
}
});
}
$("#search").keyup(filter);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder="Search" id="search" type="text" />
<div class="box">
<div class="title">Box Title1</div>
<div class="content">Box title one content</div>
</div>
<div class="box">
<div class="title">Box Title2</div>
<div class="content">Box title two content</div>
</div>
<div class="box">
<div class="title">Box Title3</div>
<div class="content">Box title three content</div>
</div>
So for example if on is entered, no filtering is performed. If one is entered, the script will look inside the content class of each box and if one is found in the text, it will be shown otherwise, it is hidden. If the User clears their search out, all items are shown.
Hide all box before iterate, then only show when match any words:
$("#search").on("input", function () {
var search = $(this).val();
if (search !== "") {
var searchArray = search.split(" ");
// Hide all .box
$(".box").each(function () {
$(this).hide();
})
searchArray.forEach(function(searchWord) {
$(".box").each(function () {
if($(this).is(':contains('+ searchWord +')') ) {
$(this).show();
}
});
});
} else {
$(".box").show();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder="Search" id="search" type="text" />
<div class="box">
<div class="title">Box Title1</div>
<div class="content">
Box title one content
</div>
</div>
<div class="box">
<div class="title">Box Title2</div>
<div class="content">
Box title two content
</div>
</div>
<div class="box">
<div class="title">Box Title3</div>
<div class="content">
Box title three content
</div>
</div>
Loop through all .boxs and using regex pattern matching, check either the title or content matches the search query. Show all matched boxes and hide all others
I have also fiddled it here
$("#search").on("input", function () {
var searchables=$('.box');
console.log(searchables)
var query=$(this).val();
searchables.each(function(i,item){
var title=$(item).find('.title').text();
var content=$(item).find('.content').text();
var rgx=new RegExp(query,'gi');
if(rgx.test(title) || rgx.test(content))
{
$(item).show();
}
else
{
$(item).hide();
}
})
})

Remove class if id's the correct ID

Looking to remove a class if a certain button is clicked.
<div class="slide-container">
<section class="about" id="slide-0">
<div class="menu-total">
<nav class="nav">
<button class="nav_link home" onclick="slideTo('slide-2')">HOME</button>
<button class="nav_link about" onclick="slideTo('slide-0')">ABOUT</button>
<button class="nav_link fun-stuff" onclick="slideTo('slide-1')">FUN STUFF</button>
<button class="nav_link professional" onclick="slideTo('slide-3')">PROFESSIONAL</button>
<button class="nav_link contact" onclick="slideTo('slide-4')">CONTACT</button>
</nav>
<div class="hamburger">
<span class="hamburger__patty"></span>
<span class="hamburger__patty"></span>
<span class="hamburger__patty"></span>
</div>
</div>
The one I want to remove the class on is the HOME button. So "slideTo('slide-2)". If it's clicked on the others then the class is kept. I believe someone is either wrong with my loop or not getting the ID correctly of the items/
function slideTo(slideId) {
const slide = document.getElementById(slideId);
slide.scrollIntoView({
behavior: 'smooth'
})
// above this line works fine
let nonHome = document.querySelectorAll('.slide-container section');
let nonHomeID = document.getElementById('slide-2');
var i;
setTimeout(function(){
for (i=0; i < nonHome.length; i++ ){
// i believe it's somewhere here it is wrong
if (nonHome[i].id != nonHomeID){
nonHome[i].classList.add("nav-visibility");
} else{
nonHomeID.classList.remove("nav-visibility");
}
}
}, 1000)
}
If you can use jquery library, you can write in the HTML:
<button class="nav_link" data-value="home">HOME</button>
...
and then in the JS code:
$(".nav_link").on("click", function() {
var valueClicked = $(this).data("value"); // Get the data-value clicked
$(".nav_link").each(function() { // Loop through all elements of the class 'nav-link'
var v = $(this).data("value");
if (v == valueClicked) {
$(this).removeClass("nav-visibility");
} else {
$(this).addClass("nav-visibility");
}
)
}
Not much simpler, but the HTML is cleaner.
Simpler version if it is not required to browse through all buttons at each button click:
$(".nav_link").on("click", function() {
var valueClicked = $(this).data("value"); // The value of the button clicked by the user
if (valueClicked == "home") {
$(this).removeClass("nav-visibility");
console.log('remove')
} else { $(this).addClass("nav-visibility");
console.log('add')
}
});

jquery: read inside each div, span and input

I'm creating a project in ASP.NET MVC and jQuery. When a user click on addSentence button, I want to duplicate a div called copythis with all events and insert it in another div called myform.
in copythis I have two div: in the first there is a span called sentence where I insert the text in the input in the second the user can add more then one field with different text.
When the user clicks the button called save I want to read all copythis in myform and create a structure to send to a webapi.
I have a problem is the javascript because I can read properly each div.
$("#addSentence").on("click", function (event) {
if ($("#inputSentence").val() == "")
alert("Sentence must have a value");
else {
event.preventDefault();
var theContainer = $("#copythis");
if (theContainer != null) {
var clonedSection = $(theContainer).clone(true);
if (clonedSection != null) {
$(clonedSection).find("#sentence")
.text($("#inputSentence").val());
$(clonedSection).appendTo("#myform");
}
}
}
});
$("#save").on("click", function (event) {
$("#myform #copythis").children().each(function (index, element) {
var elm = $(this);
var sentence = elm.find('.row span#sentence').val();
if (sentence != '') {
console.log('Sentence: ' + sentence);
$("input").children().each(function (m, l) {
var txt = $(this).val();
if (txt != '') {
console.log('Example: ' + txt);
}
});
}
});
});
function makeRepeater(sectionsSelector, addClass, removeClass, AYSMsg) {
$(sectionsSelector + " " + addClass + "," + sectionsSelector +
" " + removeClass).on("click", function (event) {
// Avoiding the link to do the default behavior.
event.preventDefault();
// Get the container to be removed/cloned
var theContainer = $(this).parents(sectionsSelector);
if ($(this).is(addClass)) {
// Cloning the container with events
var clonedSection = $(theContainer).clone(true);
// And appending it just after the current container
$(clonedSection).insertAfter(theContainer);
} else {
// If the user confirm the "Are You Sure" message
// we can remove the current container
if (confirm(AYSMsg)) {
// Making fade out, hide and remove element a sequence
// to provide a nice UX when removing element.
$(theContainer).fadeOut('normal',
function () {
$(this).hide('fast',
function () { $(this).remove(); }
);
}
);
}
}
});
}
makeRepeater(
'.my-repeated-section-form', /* The container selector */
'.addform', /* The add action selector */
'.removeform', /* The remove action selector */
'Are you sure you want to remove this section?' /* The AYS message. */
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="row">
<div class="row">
<div class="col-lg-10">
<div class="input-group">
<input id="inputSentence" type="text"
class="form-control" placeholder="Sentence...">
<span class="input-group-btn">
<button class="btn btn-secondary"
type="button" id="addSentence">Add</button>
</span>
</div>
</div>
</div>
<div class="col-lg-12">
<div style="display: inline;">
<div class="group-of-repeated-sections" style="display: none;">
<div class="my-repeated-section">
<div id="copythis">
<div class="row">
<div class="col-lg-10">
<span id="sentence"></span>
</div>
<div class="col-lg-2">
<span>
+
-
</span>
</div>
</div>
<div class="my-repeated-section-form">
<div class="row">
<div class="col-lg-12">
<input type="text" />
<span>
+
-
</span>
</div>
</div>
</div>
<div style="height:25px;"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="myform"></div>
<button id="save">Save</button>

How do I make JS code not affect other DIV?

Hi I am try to make a list of item, I have "add" and "minus" button for each item. The problem is that the JS code I had control two items together. ex. if I click "add" for item1, then the item2 gets added as well.
Looks like that my JS functions works for all button elements. So when I click a "button" element, all buttons get triggered.
How can I do add them individually?
PS: I guess I need to do something like a specific ID for JS to trigger. My thought is add a unique ITEM ID for each one and trigger the button under that specific ID so other buttons under other ITEM ID don't get triggered.
Here is my HTML code:
<div class="row bb">
<div class="col-xs-12 food-container">
<img src="img/1.png" class="min-w img-responsive" />
<div class="food-detail">
<div class="food-name">test</div>
<div class="food-sales">test:233333</div>
<div class="food-price">
¥50
<div class="food-edit">
<button class="btn btn-info" value="50.55" id="minus">-</button>
<span class="num-sales"></span>
<button class="btn btn-info" value="50.55" id="add">+</button>
</div>
</div>
</div>
</div>
</div>
<div class="row bb">
<div class="col-xs-12 food-container">
<img src="img/1.png" class="min-w img-responsive" />
<div class="food-detail">
<div class="food-name">test</div>
<div class="food-sales">test:233333</div>
<div class="food-price">
¥50
<div class="food-edit">
<button class="btn btn-info" value="50.55" id="minus">-</button>
<span class="num-sales"></span>
<button class="btn btn-info" value="50.55" id="add">+</button>
</div>
</div>
</div>
</div>
</div>
Here is my JS:
var theTotal = 0;
var theSales = 0;
var minusButton = document.getElementById('minus');
if (theSales == 0) {
$(minusButton).hide();
}
$('button').click(function () {
var ID = this.id;
if (ID == "add") {
$(minusButton).show();
theTotal = Number(theTotal) + Number($(this).val());
theSales++;
var num = theTotal.toFixed(2);
$('.total').text("¥" + num);
$('.total-num-of-sales').text(theSales + "份");
$('.num-sales').text(theSales);
};
if (ID == "minus") {
theTotal = Number(theTotal) - Number($(this).val());
theSales--;
var num = theTotal.toFixed(2);
if ( theSales == 0 ) {
$('.total').text("");
$('.total-num-of-sales').text("");
$('.num-sales').text("");
$(minusButton).hide();
}
else if ( theSales > 0 ) {
$('.total').text("¥"+num);
$('.total-num-of-sales').text(theSales + "份");
$('.num-sales').text(theSales);
}
};
});
Don't use multiple id on same page
http://jsfiddle.net/bjc1c9tr/4/
Check this will help you
var theTotal = 0;
var theSales = 0;
var minusButton = $('.minus');
if (theSales == 0) {
$(minusButton).hide();
}
$('button').click(function(){
var ID = $(this).attr('data');
if (ID == "add") {
$(this).parent().find('.minus').show();
theTotal = Number($(this).parent().find('.num-sales').text()) + Number($(this).val());
theSales = Number($(this).parent().find('.num-sales').text()) + Number(1);
var num=theTotal.toFixed(2);
$(this).parent().find('.total').text("¥"+num);
$(this).parent().find('.total-num-of-sales').text(theSales+"份");
$(this).parent().find('.num-sales').text(theSales);
};
if (ID == "minus") {
theTotal = Number($(this).parent().find('.num-sales').text()) - Number($(this).val());
theSales= Number($(this).parent().find('.num-sales').text()) - Number(1);
var num=theTotal.toFixed(2);
if ( theSales == 0) {
$('.total').text("");
$(this).parent().find('.total-num-of-sales').text("");
$(this).parent().find('.num-sales').text("");
$(this).parent().find('.minus').hide();
}
else if ( theSales > 0) {
$(this).parent().find('.total').text("¥"+num);
$(this).parent().find('.total-num-of-sales').text(theSales + "份")
$(this).parent().find('.num-sales').text(theSales);
}
};
});
html (added new classes)
<div class="row bb">
<div class="col-xs-12 food-container">
<img src="img/1.png" class="min-w img-responsive" />
<div class="food-detail">
<div class="food-name">test</div>
<div class="food-sales">test:233333</div>
<div class="food-price">¥50
<div class="food-edit">
<button class="btn btn-info minus" value="50.55" data="minus">-</button>
<span class="num-sales"></span>
<button class="btn btn-info add" value="50.55" data="add">+</button>
</div>
</div>
</div>
</div>
</div>
<div class="row bb">
<div class="col-xs-12 food-container">
<img src="img/1.png" class="min-w img-responsive" />
<div class="food-detail">
<div class="food-name">test</div>
<div class="food-sales">test:233333</div>
<div class="food-price">¥50
<div class="food-edit">
<button class="btn btn-info minus" value="50.55" data="minus">-</button>
<span class="num-sales"></span>
<button class="btn btn-info add" value="50.55" data="add">+</button>
</div>
</div>
</div>
</div>
</div>
$('button').click(function(){
var ID = this.id;
if (ID == "add") {
$(minusButton).show();
theTotal = Number(theTotal) + Number($(this).val());
theSales = Number($(this).parent().find('.num-sales').text())+1;
var num=theTotal.toFixed(2);
$('.total').text("¥"+num);
$('.total-num-of-sales').text(theSales+"份");
$(this).parent().find('.num-sales').text(theSales);
};
if (ID == "minus") {
theTotal = Number(theTotal) - Number($(this).val());
theSales = Number($(this).parent().find('.num-sales').text())-1;
var num=theTotal.toFixed(2);
if ( theSales == 0) {
$('.total').text("");
$('.total-num-of-sales').text("");
$(this).parent().find('.num-sales').text("");
//$('.num-sales').text("");
$(minusButton).hide();
}
else if ( theSales > 0) {
$('.total').text("¥"+num);
$('.total-num-of-sales').text(theSales + "份");
$(this).parent().find('.num-sales').text(theSales);
//$('.num-sales').text(theSales);
}
};
$(this).parent().find('.num-sales').text(theSales);
By this way you can get the parent of clicked button and change the value of .num-sales of the selected parent
https://jsfiddle.net/s2u9eb36/ refer this one
You are mixing the elements because of your id and class selectors.
When you select elements through jQuery by class (like $('.num-sales')), jQuery gives you a collection of all elements that match the selector. In your case, that would be both class="num-sales" elements.
Whenever you then call a function (like .html(theSales)), it will apply that function to each element in the collection, that's why your code is affecting more than one element.
You will need to find a way to distinguish one element of the other. There's quite a few options here, but I like doing it by limiting the scope of my selectors. With this I mean I would first find the food-detail div that contains the clicked element, and then find .num-sales etc... only within that element.
Then you can do the following in your button clicks:
$('button').click(function(){
var ID = this.id;
var element = $(this) //make a jQuery object of the clicked button
// finds the first parent element with class food-detail
var container = element.closest('.food-detail');
// find .num-sales within container
var numSales = container.find('.num-sales')
// continue...
});
in short:
when a button is clicked, find the food-detail div the button is in
.find in only that container instead of using selectors on the entire document
Edit: you should really change the id="Add" and id="minus" on your buttons, ids should be unique on the entire document. You can simply add add or minus as a class instead and check for it with element.hasClass('add').

Angularjs View Not Updating, View Flickers on Button Click

I have written the following HTML & AngularJS code to update the Tree on HTML Page (View) on the Click of a Button.
When the Button is clicked, the changes appear for a fraction of second and disappear. I am not able to find the reason for this. Could you please let me know how I can overcome this problem?
Below is the HTML and JS Code. This is working in the Snippet Editor, but not in the Browser.
var module = angular.module('myapp', []);
module.controller("TreeCtrl", function($scope) {
$scope.categories = [];
$scope.$apply($scope.addTreeToView = function() {
$scope.categories = [{
title: 'Computers1',
categories: [{
title: 'Laptops1',
categories: [{
title: 'Ultrabooks1'
}, {
title: 'Macbooks1'
}]
}, {
title: 'Desktops1'
}, {
title: 'Tablets1',
categories: [{
title: 'Apple1'
}, {
title: 'Android1'
}]
}]
}, {
title: 'Printers1',
categories: [{
title: 'HP1'
}, {
title: 'IBM1'
}]
}];
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tree Example</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<div ng-app="myapp">
<div class="col-sm-10 col-sm-offset-1" ng-controller="TreeCtrl">
<form action="#" method="post" class="form-horizontal" id="commentForm" role="form">
<div class="form-group" id="div_submitComment">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn btn-success btn-circle text-uppercase" type="submit" ng-click="addTreeToView()"><span class="glyphicon glyphicon-send" id="qazwsx"></span> Create Tree</button>
</div>
</div>
</form>
<div class="page-header">
<h3 class="reviews">Tree</h3>
</div>
<script type="text/ng-template" id="categoryTree">
{{ category.title }}
<ul ng-if="category.categories">
<li ng-repeat="category in category.categories" ng-include="'categoryTree'">
</li>
</ul>
</script>
<ul>
<li ng-repeat="category in categories" ng-include="'categoryTree'"></li>
</ul>
</div>
</div>
<script src="self.js"></script>
</body>
try removing type="submit" from the buttom
I was using Form element type of Bootstrap. This has an action attribute. I removed the action attribute. Code works fine after removing it
< form method = "post"
class = "form-horizontal"
id = "commentForm"
role = "form" >
< div class = "form-group"
id = "div_submitComment" >
< div class = "col-sm-offset-2 col-sm-10" >
< button class = "btn btn-success btn-circle text-uppercase"
type = "submit"
ng - click = "addTreeToView()" > < span class = "glyphicon glyphicon-send"
id = "qazwsx" > < /span> Create Tree</button >
< /div>
</div >
< /form>
Because your html will be reloaded after you do "submit" action.So you have to replace "type="submit" by type="button" and disable "auto submit".

Categories