How to compare two divs for same number - javascript

I need to compare two divs for the same number then do something
I am using .is function
jQuery(function ($) {
if ( $("#result").is(".count-entries") ) {
alert("true");
}
});
<div class="count-entries">2</div>
<div id="result">2</div>
The alert isn't firing when the numbers are the same in the divs

If you want to check if 2 divs have the same content, you can get the text of the div using text(), use trim() to remove extra spaces.
Note: .count-entries is a class, there could be multiple elements with this class. You might need to specify the id if that is the case.
if ($("#result").text().trim() === $(".count-entries").text().trim()) {
console.log("Content is the same");
} else {
console.log("Content is not the same");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="count-entries">2</div>
<div id="result">2</div>

$(function () {
var entries=$(".count-entries").val(); /*To get the value*/
var result=$("#result").val();
if ( entries==result ) {
alert("true");
}
});
<div class="count-entries">2</div>
<div id="result">2</div>
:D

You are thinking of checking the .text() of the divs, to see if they match.
if ($("#result").text() == $("count-entries").text()) {
alert("true");
};
Checking the actual content is not a good way of checking values, as any function which gets that info, returns the contents as a string, and if any space characters are included in only one of the two, the strings will not be equal, and it would not evaluate to true.
Give more info about your use case, and we will be able to provide better guidance.

Related

How to check if the 1st number is '0' in a string using jQuery?

I'm trying to create a simple calculator using jQuery.
I have a paragraph tag that I'm using as a display. After pressing 'AC' button that clears my display the paragraph tag contains '0'.
What I wanna do is when I press a button with a number I need this '0' to be replaced with the number I pressed because now it goes like '07' or '05'.
I tried:
$('#7').on('click', function() {
if ($('#mainline') == '0')) {
$('#mainline').remove('0');
}
$('#mainline').append('7');
})
But I guess I'm doing something wrong. How should I check if #mainline has '0'?
Using regexp is a good way,but if you do not understand regexp,you can try this:
$('#7').on('click', function() {
if ($('#mainline').text() == '0')) {
$('#mainline').text('7');
}else{
$('#mainline').append('7');
}
})
If '#mainline' is a input or textarea,use 'val()' instead of 'text()'
If #mainline is a DIV, get its text, then remove leading zeroes with a regexp, then append 7.
$('#7').click(function() {
$("#mainline").text(function(i, oldtext) {
return oldtext.replace(/^0+/, '') + '7';
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainline">0</div>
<button id="7">7</button>
If it's an input, use .val() instead of .text().
Maybe you can try to get the value $('#mainline').text() then parseInt() or parseFloat() if $('#mainline').text().indexOf('.') > -1.
parseInt() and parseFloat() will automatically remove the excessive ZEROs from head of your string.

Hiding content depending on variable value

I am making a price estimator.
How would correctly write a jQuery function that checks a variable and depending on that amount hides/shows a certain div element accordingly.
So if I had:
a HTML div with the ID 'Answer'
<div id="answer">Hide Me</div>
$("#answer")...
a variable (this variable would change)
var x = 30
Now I know the css to hide the div would be:
#answer{
visibilty:hidden;
}
What would be the correct way to hide the function checking these certain parameters? for example if x > 20 then hide etc
Now I know there will be many ways to do this and they may not require jQuery, please inform me if this is the case. Perhaps it just needs JS. I know there will be many ways to do it not just one so if you have a different way please comment as I am keen to learn.
Any help would be greatly appreciated.
Cheers
F
Note that you can also remove or add a class:
$('#answer').removeClass('hide');
$('#answer').addClass('hide');
But what you want to do is $('#answer').hide(); or $('#answer').show();
Execute this function providing the variable v:
var checkVar = function(v) {
var target = $('#answer');
if (parseInt(v) > 20) {
target.hide();
} else {
target.show();
}
}
For example, if the variable comes form a selection:
$('#selectId').on('change', function() {
checkVar($(this).val());
});
Remove the CSS. You can do it in jQuery
if(x>20){
$('#answer').hide();
}
You can use this one
$("#answer").hide();
#kapantzak's answer looks good. But keep your logic and style separated and if your not going to use the variable for the actual element twice, I wouldn't make it. So go:
var checkVar = function(var) {
var element = $('#answer');
if (parseInt(var) > 20) {
element.addClass('hidden');
}else{
element.removeClass('hidden');
}
}
And in your CSS go:
#answer.hidden{
display: none;
}
Also, depending on your preference, display: none; doesn't display anything of the object whereas visibility: hidden hides the object but the space the object was occupying will remain occupied.
HTML
<input id="changingValue">
...
<div id="answer">Hide Me</div>
CSS (not mandatory if you check values on loading)
#answer{ display:none;}
JS
var limit = 20;
$(function(){
$("#changingValue").change(function(){
if(parseInt($("#changingValue").val())<limit) { $("#answer").show(); }
else { $("#answer").hide(); }
});
});

How to get just one value from array in javascript

i'm learning javascript and i've tried something but i can't figure out how to make it work, here's my code so far:
HTML
<p>Busca tu auto:</p>
<input type="text" id="search"><span> </span><button>Submit</button>
<p class="hide h1" style="color:green">Your car is available.</p>
<p class="hide h2" style="color:red">Your car is not available.</p>
JS
$(document).ready(function(){
var cars = ['mercedes','nissan','ferrari','bmw','fiat','toyota','renault','peugeot','kia'];
$('.hide').hide();
$('button').click(function(){
if($('#search').val() == cars[x]){
$('.h1').show();
$('.h2').hide();
} else {
$('.h2').show();
$('.h1').hide();
};
});
});
What I want to do is that when you click the button check if the car is available (it's not real). For example, it you type "mazda" and click the button, h2 will show, but if you type "ferrari" and click the button, h1 will show.
I'm approaching to the solution with my code above or not?
NOTE: if you change the "x" in cars[x] for a number it works, but just with one car.
Array.prototype.indexOf
$(document).ready(function(){
var cars = ['mercedes','nissan','ferrari','bmw','fiat','toyota','renault','peugeot','kia'];
$('.hide').hide();
$('button').click(function(){
if(cars.indexOf($('#search').val()) !== -1){
$('.h1').show();
$('.h2').hide();
} else {
$('.h2').show();
$('.h1').hide();
};
});
});
http://jsfiddle.net/CWHDv/
You can search through arrays by using the Array.indexOf method:
if (cars.indexOf($('#search').val()) !== -1) {
//your code here
}
The Array.indexOf method will return -1 when no exact matches are found (this includes lowercase/uppercase differences), and otherwise it will return the index of the match in the array. That means that if the entered value is in your array, it will return something other than -1, so the if-statement will return true.
To make this case-insensitive, use the following:
if (cars.indexOf($('#search').val().toLowerCase()) !== -1) {
//available
} else {
//unavailable
}
that converts the input to lowercase first, and checks afterwards. For this to work, all values stored in the array would need to be in all lowercase letters too, like your example shows.
Since this question is also tagged jQuery:
From the jQuery docs:
jQuery.inArray( value, array [, fromIndex ] )
Which would be:
$.inArray(('#search').val(), cars) !== -1
This also has the advantage of working in IE8 and below, something that Array.prototype.indexOf does not.

How can I show/hide divs dynamically (on KeyUp, iTunes style) using Javascript/jQuery and a text or search field with case insensitive

I set out on a journey to create an iTunes-like search using Javascript. I learned about jQuery, and with some help from people on StackOverflow, I was successful.
I've come back here to share with you a very simple way to create a dynamic hide/show list based on the user input.
Let's search!
The entirety of the tutorial code can be found here.
And a JSFiddle for it is here!
So good to see Nick was successful on this experiment. good job on learning how to do it :)
Just in case you haven't encountered this jquery plugin, you might want to take a look at it too it's called Quick search.
https://github.com/riklomas/quicksearch
And I've used it on numerous pages and it works like a charm. example:
http://fedmich.com/works/types-of-project.htm
First, create a simple Div Layout with some text in the divs and search bar above it.
<div class="search_bar">
<form><!--The Field from which to gather data-->
<input id="searchfield" type="text" onclick="value=''" value="Case Sensitive Search">
</form>
</div>
<!--Containers With Text-->
<div class="container">
<div class="container_of_hc">
<div class="horizontal_containers">Cat</div>
<div class="color">Black</div>
<div class="color">White</div>
<div class="color">Orange</div>
</div>
<div class="horizontal_containers">Dog</div>
<div class="horizontal_containers">Rat</div>
<div class="horizontal_containers">Zebra</div>
<div class="horizontal_containers">Wolf</div>
</div>
CSS:
.container {
width: 100%;
}
.horizontal_containers {
height:10%;
border: solid 3px #B30015;
font-size: 45px;
text-align: center;
}
Second, you will make a script utilizing jQuery. Remember the title says this is a Dynamic Search, meaning (for us) we want to update the search with each key typed:
$("#searchfield").keyup(function() {
Note: Need a selector refresher?
Then we will set a variable to the value in #searchfield:
var str = $("#searchfield").val(); //get current value of id=searchfield
To ensure we show all the divs in our list when there is nothing in the searchfield we create an if statement based on the length of our new variable (str):
if (str.length == 0) {
//if searchfield is empty, show all
$(".horizontal_containers").show();
}
Last, we do the actual hiding of the divs if the length of str is not 0:
else {
//if input contains matching string, show div
//if input does not contain matching string, hide div
$("div:contains('" + str + "').horizontal_containers").show();
$("div:not(:contains('" + str + "')).horizontal_containers").hide();
}
});
The div:contains() and div:not(:contains()) statements are what set the conditions. It's essentially an if statement. They search the text contained within the div, not the div attributes. If you want to search a deeper div structure you can use more than one selector in the script's jQuery statements like so:
if (str.length == 0) {
//if searchfield is empty, show all
$(".container .color").show();
} else {
//if input contains matching string, show div
//if input does not contain matching string, hide div
$(".container div:contains('" + str + "').color").show();
$(".container div:not(:contains('" + str + "')).color").hide();
}
Replace the script statement you already have to give it a try.
Note: The nesting structure of your divs must match that in your selector.
And that's essentially it. If you have tips to improve this, know how to change it to a case insensitive search, or anything else you can think of, please let me know!
Thanks to MrXenoType I have learned case insensitivity for the :contains function.
To create a case insensitive search for this project simply add:
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
This creates a pseudo for the contains function. Place this code above your other script (within the same script) to make true for only this script.
Try:
$.expr[":"].contains_nocase = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
for adding a :contains_nocase() selector with jQuery 1.8

Show field if true, hide field if false?

Want to have a notification box displayed if amount in fieldA is higher than amount in fieldB.
Currently have some code working but the notification box toggles on and off not depending on the actual amount.
What am I missing?
jquery:
$(document).ready(function() {
$('#fieldA').change(function(){
if($(this).val()>$('#fieldb').val()){
//display it on the form
$('.labelNotification').toggle();
$('.labelNotification').append('Not recommended to have FieldA figure higher than FieldB.');
}
})
});
HTML:
< p style="display: none;" class="error labelNotification">
This is tailor-made for the toggle(boolean) method. Also, you have to be careful about appending to the notification label ... what if the user changes his answer twice? It's better to have multiple notification objects, each of which can contain stuff for a single type of notification.
$(function() {
$('#fieldA').change(function() {
var isLarger = +$(this).val() > +$('#fieldB').val(); // Note: convert to number with '+'
var $labelNotification = $('.labelNotification');
$labelNotification.toggle(isLarger);
if (isLarger) {
//display it on the form
$labelNotification.html('Not recommended to have FieldA figure higher than FieldB.');
}
})
});
If you're comparing numerical values (which it seems like you are), you should use parseInt or parseFloat to convert the (string) value returned by val() to an integer. According to the documentation for val, the function always returns a string value.
I found the problem ,
First thing is you need to have semicolon properly as below
$('#fieldA').change(function () {
if ($(this).val() > $('#fieldB').val()) {
alert("its greater");
//display it on the form
$('.labelNotification').append('Not recommended to have FieldA figure higher than FieldB.');
$('.labelNotification').show();
}
else {$('.labelNotification').hide();
$('.labelNotification').html('');}
});
Second thing , when you toggle it it won't show for the second time
if 40 > 30
and again if you entery 50 and 50 > 30 it won't show
this is second problem
final problem is empty the label all the time
$('.labelNotification').html('')'
Toggle is not the best approach for your situation.
You want to compare and then decide.
Since you are looking at numbers I would strongly suggest using a number type to do the comparison, either using parseInt() or parseFloat().
The text in the notification label only needs to be set once, since you don't have any comment for it showing something when B > A. I would suggest setting this in your HTML.
<span class="labelNotification" style="display:none">Your Warning Text</span>
<!-- if your CSS class has `display:none` remove the style attribute -->
as for the jQuery.
$(function() {
$("#fieldA").change(function() {
var a = parseInt($(this).val());
var b = parseInt($("#fieldb").val());
// handle if a or b is not a number --> isNaN(a) || isNaN(b)
if( a > b ) {
$('.labelNotification').show()
} else {
$('.labelNotification').hide()
}
});
});

Categories