How to get just one value from array in javascript - 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.

Related

How to compare two divs for same number

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.

show div base on specific input text in multiple strings

Jquery question...So this is simple find the value if match from keyup show the button. But I want to ask for 2 questions to improve this:
Fiddle
$("#test").keyup(function () {
$("#yeah").css("display", this.value == "test" ? "block" : "none");
});
Where im stuck is:
Type test = good
type test here = nothing
I want to keep the display no matter how the string is place as long as its placed it will not go away
So Ex: I want to do some tests - will show
And the other question is how do you do multiple strings? like if i want to show it on test and something like test2?
Use a regular expression:
$("#test").keyup(function() {
$("#yeah").toggle(/test|something/.test(this.value));
});
#yeah {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="test">
<div id="yeah">
Yeah!
</div>
This regexp matches anything with test or something in it.
Here is another answer for your both questions.
$('input[name=amount]').keyup(function() {
var testStr = $(this).val();
var testStr2 = 'test';
var testStr3 = 'texts';
if (testStr.indexOf(testStr2) != -1 || testStr.indexOf(testStr3) != -1 )
$('#yeah').show();
else
$('#yeah').hide();
});

find ID of previous button

I'm looking to find the id of the previous button. It is pretty far away - lots of table rows, tables, divs, etc. between the target and the button but I thought this would still work:
alert( $(this).prevAll("input[type=button]").attr('id') );
Unfortunately this returns alerts 'undefined'. Help?
function getPrevInput(elem){
var i = 0,
inputs = document.getElementsByTagName('input'),
ret = 'Not found';
while(inputs[i] !== elem || i >= inputs.length){
if(inputs[i].type === 'button'){
ret = inputs[i];
}
i++;
}
return (typeof ret === 'string') ? ret : ret.id;
}
That probably isn't the most efficient solution, but it's the only one I can think of. What it does is goes through all the input elements and finds the one right before the one you passed into the function. You can use it like this, assuming you're calling it correctly and this is the input element:
getPrevInput(this);
Demo
That kind of lookup might be expensive. What about doing a select for all your input[type=button] elements, and traversing that array until you find the element matching your id. Then you can simply reference the array index - 1 to get your answer.
Is the previous button a sibling of the current button? If not, prevAll() won't work. The description of prevAll():
Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.
Depending on your DOM structure, you can use a combination of parents() and then followed by find().
This function looks up all input[type=button] elements and uses the jQuery index function to find your current element in this group.
If it could be found and there is a previous element it is returned.
$.fn.previousElem = function(lookup){
var $elements = $(lookup),
index = $elements.index(this);
if(index > 0){
return $elements.eq(index-1)
}else{
return this;
}
}
HTML:
<div><div><div><div>
<input type=button id=1 value=1 />
</div></div></div></div>
<div><div><div><div>
<input type=button id=2 value=2 />
</div></div></div></div>
JS:
alert ($("#2").previousElem('input[type=button]').attr('id'))
http://jsfiddle.net/SnScQ/1/
Here's a different version of Amaan's code, but jqueryfied and his solution wasn't looking for a button. The key to the solution is that jQuery returns the elements in document order, as do document.getElementsByTagName and similar functions.
var button = $('#c');
var prevNode;
$("input[type=button]").each(function() {
if (this == button[0]) {
return false;
}
prevNode = this;
});
alert(prevNode && prevNode.getAttribute('id'));
http://jsfiddle.net/crFy6/
have you tried .closest? ...
alert( $(this).closest("input[type=button]").attr('id') );

JQuery, a new Selection using the results

Is there a way to me do this?
<img id="example" src="anything.jpg" title="something" class="abc" />
$('.abc').each(function(){
//test if this result is something
if( $(this)...(???)...('[src^=anything]')) == 'anything.jpg'){
}
//another Jquery selector test for this one
if( $(this)...(???)...('#example').size() > 0){
}
});
This is just an example, what I need is pretty more complex.. But I would like to know if there is a way to make other jQuery selector test in the result of a first selector.. since "find" will find the children of $(this).. and .parent() get alot of brothers..
See what I mean?
Do you have any idea?
So sorry.. let me try again..
$('div').each();
get all "div", right?
But now in that function I need to make another "test" check if div class is "red" or "blue"..
See?
I need to test something else of the result based in Jquery selector..
I know I could do:
class = $(this).attr('class'); and then if(class=="blue"){} .. But I would like to do $('this[class=blue]').size()>0){}
The jQuery is() filter operates on a found set to detect if something is true or not.
The jQuery filter() method will further pare down a found set based on criteria.
var allDivs = $('div');
var greenOnes = allDivs.filter('.green');
var redOnes = allDivs.filter('.red' );
I think you need the is method:
$('.abc').each(function() {
$(this).is('[src^=anything]')
});
This is fairly simple though, but I can't really tell what you are trying to do by the description. Maybe this is enough to get you started though.
You can use the filter and is methods to filter/search within a jQuery object.
if( $(this).is('[src^="anything"]') ) {
}
elseif( $("#example").size() > 0) {
}
You could put $("#example") in a variable outside of the loop and then reference it inside the loop as well.
if(this.src.indexOf("anything") === 0) {
// source starts with 'anything'
}
if($("#example").length) {
// since there can be only one #example
// in a *valid* document
}
Based on your edit:
if($(this).hasClass("blue")) {
...
}
?

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