Use the value of span class in if/else statement - javascript

Trying to get the value (AUD) and using it in the if statement below.
<span class="name" data-name="">AUD</span>
<script>
function myFunction() {
var currency = document.getElementsByClassName("name")[0]
if (currency = AUD) {

In order to compare the currency value to "AUD" in the conditional, you want to do if (currency == "AUD") (this is called a loose comparison) or if (currency === "AUD") (this is called a strict comparison).
Though you need to first get the .innerText of currency. Right now, currency is the first node that was found by getElementsByClassName. So change this to var currency = document.getElementsByClassName("name")[0].innerText to get the text value of the node, and then you can do the conditional like above.
function myFunction() {
//check the first 'name' text
var currency = document.getElementsByClassName("name")[0].innerText;
if (currency == "AUD") {
console.log('currency is AUD');
} else {
console.log('currency is not AUD');
}
//check the second 'name' text
var currency2 = document.getElementsByClassName("name")[1].innerText;
if (currency2 == "AUD") {
console.log('currency is AUD');
} else {
console.log('currency is not AUD, it is ' + currency2);
}
}
myFunction();
<span class="name" data-name="">AUD</span>
<span class="name" data-name="">USD</span>

You could try doing a for loop like this
var currency = document.getElementsByClassName("name");
for(var i = 0; i < currency.length; i++) {
if(currency[i].innerHTML == "AUD") {
}
}

Try this:
function myFunction() {
var currency = document.getElementsByClassName("name")[0].innerHTML;
if (currency == 'AUD'){
console.log(true)
}
}
myFunction();

Try this.
And don't forget to call myFunction() to make it work.
<span class="name" data-name="">AUD</span>
<script>
function myFunction() {
let currency = document.getElementsByClassName('name')[0];
let value = currency.innerText;
let AUD = 'AUD';
if (value == AUD) {
console.log('yes')
}
}
myFunction();
</script>

Related

Input number auto change value by stepUp and stepDown

I have this input type="number"
</div>
<input id="data-filter" class="form-control form-control" type="number" value="2021"/>
</div>
What i need is a script that change the input value using the stepUp and stepDown buttons from "2021" to "2022" and then "2021" again. This because i have a function related to that input and the function doesn't read the default value of element input. It happens only if i fill the input text with "2021" again, or i use the stepUp/stepDown buttons.
Edit:
I use that input to perform a search in a table-rows, what i need on the page load is to filter only the rows that contains the year 2021. The function works great, but it doesn't on page load using a default value. So i need to change manualty the input value.
the filter:
$('#data-filter').on('load', function () {
changeFilter.call(this, 'data');
});
the function changeFilter:
function changeFilter(filterName) {
filters[filterName] = this.value;
updateFilters();
}
update filters function:
function updateFilters() {
$('.task-list-row').hide().filter(function () {
var
dataValue = $(this),
result = true;
Object.keys(filters).forEach(function (filter) {
if (filters[filter] && (filters[filter] != 'Tutti') && !filters[filter].includes('-')) {
result = result && dataValue.data(filter).toLowerCase().includes(filters[filter].toLowerCase())
}
else if (filters[filter] && (filters[filter] != 'Tutti') && filters[filter].includes('-')) {
result = result && convertDate(filters[filter]) === dataValue.data(filter);
}
if (filters[filter] === '') {
result = true;
}
});
return result;
}).show();
}
function setUp() {
let dataValue = document.getElementById('data-filter').value;
document.getElementById('data-filter').value = ++dataValue;
}
function setDown() {
let dataValue = document.getElementById('data-filter').value;
document.getElementById('data-filter').value = --dataValue;
}
function setUp()
{
dataValue = document.getElementById('data-filter').value;
document.getElementById('data-filter').value = ++dataValue;
}
function setDown()
{
dataValue = document.getElementById('data-filter').value;
document.getElementById('data-filter').value = --dataValue;
}

Check for partial match in JavaScript if statement

I've got elements set up something like this:
<div class="cat" data-cat="example-cat, test-cat, test-category">
...
</div>
<div class="cat" data-cat="test-category">
...
</div>
<div class="cat">
...
<div class="cat" data-cat="example-cat, test-category">
...
</div>
<div class="cat" data-cat="test-category, one-more-cat">
...
</div>
</div>
Using JavaScript, I need to check each bit of text between commas for a match with a user selected value. For example, if the user selected "test-cat," I need to check each div to see if data-cat matches the selection. If it does, I need to add class="active" to each matching div.
Part of the trick is that if the user selects test-cat, a div with a data-cat of test-category should not return positive. Only exact matches should be consider matches.
I had already set up a complex filtering system with support for multiple filters, but the client wants to be able to set multiple categories per div, which is making this tricky. I have a script set up to show matches if the attribute is an exact match, and I'll be trying to modify this to work as I need it to:
$(document).ready(function() {
var changedOnce = false;
$("#filters select").change(function() {
$(".cat").each(function() {
$(this).attr("data-match", "true");
$(this).removeClass("open");
});
$("#filters select").each(function() {
var filter = $(this).attr("name");
var value = $(this).val();
$(".cat").each(function() {
if ($(this).attr("data-match") === "false") {
return true;
}
var attr = $(this).attr("data-" + filter);
var childAttr = $(this).find(".cat").attr("data-" + filter)
if ((typeof attr !== typeof undefined && attr !== false) || (typeof childAttr !== typeof undefined && childAttr !== false)) {
if ($(this).attr("data-" + filter) === value || $(this).find(".cat").attr("data-" + filter) === value || value === "") {
$(this).attr("data-match", "true");
$(this).parents(".cat").attr("data-match", "true");
} else {
$(this).attr("data-match", "false");
return true;
}
} else {
if (value !== "") {
$(this).attr("data-match", "false");
return true;
} else {
$(this).attr("data-match", "true");
$(this).parents(".cat").attr("data-match", "true");
}
}
});
});
});
});
My filters are set up something like:
<div id="filters">
<select name="cat">
<option value="test-cat">Test Cat</option>
<option value="example-cat">Example Cat</option>
...
</select>
...
<select name="nth-filter">
...
</select>
</div>
It's probably not the most elegant solution (I'm no JavaScript master), but it was working, until I made this most recent change. If you need more information, just let me know.
UPDATE: Here's my current script, using .data() and .split() as suggested. I'm having trouble getting the parent category to show as a miss if all its children are misses, but I'll post a separate question for that.
$(document).ready(function() {
$("#filters select").change(function() {
$(".cat").each(function() {
$(this).data("match", true);
$(this).css("opacity", "1");
// $(this).removeClass("open");
});
$("#filters select").each(function() {
var filter = $(this).attr("name");
var value = $(this).val();
$(".cat").not(".primary").each(function() {
if ($(this).data(filter)) {
var match = $(this).data("match");
var attributes = $(this).data(filter).split(", ");
var i = 0;
$(attributes).each(function() {
if (value && attributes[i] !== value) {
match = false;
} else {
match = true;
return true;
}
i++;
});
$(this).data("match", match);
}
if ($(this).data("match") === false) {
$(this).css("opacity", "0.25");
} else {
$(this).css("opacity", "1");
}
});
});
});
});
You can use the String's split function to split the comma-separated values into an array, and then use the Array's indexOf function to check for a match.
var attr = $(this).attr("data-" + filter);
if (attr && (attr.split(/[\s*,\s*]+/).indexOf() >= 0)) {
Note: I left out this part of the check: attr !== false. attr should either be a String or undefined, so it will never be false. Did you mean to check if it is the string "false"?
Also, when you call the following:
var childAttr = $(this).find(".cat").attr("data-" + filter)
You should be aware that .attr() will return the value of the first matched element, and from your markup it looks like there could be multiple matched elements.

I want to disable the button if specific text has been found in any label

I want to disable the button if specific text has been found in any label.
The following code doesn't run because aTags[i].innerText is not equal to searchText all the time which is wrong because the label has inner text = "a" and the searchText variable have "a" as text - I need it to run in IE
<html>
<script language="javascript">
$(document).ready(function () {
var aTags = document.getElementsByTagName("label");
var searchText = "a";
var found;
for (var i = 0; i < aTags.length; i++) {
if (aTags[i].innerText == searchText) {
document.getElementById('choose').disabled=true;
break;
}
else
{
alert("failed")
}
}
});
</script>
<label> a </label> <br/>
<label> b </label> <br/>
<label> c </label> <br/>
<input type='button' value='choose' id='choose' />
</html>
Seems like there should be easier ways to do that with jQuery
$(function () {
var searchText = "a";
$('#choose').prop('disabled', function() {
return $('label').filter(function(_,el) {
return $.trim( $(el).text() ) === searchText;
}).length > 0;
});
});
FIDDLE
The issue is that your label contains " a " (with the spaces), but you're comparing with "a" (no spaces).
If you want to ignore the spaces, you can use jQuery's $.trim(...) to trim the text off the innerText.
But as you're using jQuery, you can dramatically reduce that code:
$(document).ready(function() {
var searchText = "a";
var found = false;
$("label").each(function() {
found = $.trim($(this).text()) === searchText;
if (found) {
return false; // No need to keep looking
}
});
$("#choose").prop("disabled", true);
});
Since you're already using jQuery, you can do what you like with much less complexity.
This will work:
(function ($) {
var searchText = "a";
$('label').each(function(){
if ($.trim($(this).text()) === searchText) {
$('#choose').prop('disabled', true);
}
});
})(jQuery);
You have to trim label's text. Try with:
if (aTags[i].innerText.trim() == searchText)
or without trim method:
if (aTags[i].innerText.replace(/^\s+|\s+$/g, '') == searchText)
If you want to match if a substring exists you can try with
aTags[i].innerText.indexOf(searchText) > -1
instead of
aTags[i].innerText == searchText

How to write simplified and generic validation logics and rules in JQuery

I know there are tons of information out there over internet to validate form in JavaScript and JQuery. But I’m interested to write my own. Basically I want to learn this thing.
So here is my validation script I have written and its working fine.
function validate() {
var firstName = jQuery("#firstName").val();
var lastName = jQuery("#lastName").val();
var dateOfBirthy = jQuery().val("dateOfBirth");
if (firstName.length == 0) {
addRemoveValidationCSSclass("#firstName", false);
} else {
addRemoveValidationCSSclass("#firstName", true);
}
if (lastName.length == 0) {
addRemoveValidationCSSclass("#lastName", false);
} else {
addRemoveValidationCSSclass("#lastName", true);
}
}
function addRemoveValidationCSSclass(inputField, isValid) {
var div = jQuery(inputField).parents("div.control-group");
if (isValid == false) {
div.removeClass("success");
div.addClass("error");
} else if (isValid == true) {
div.removeClass("error");
div.addClass("success");
} else {
}
}
I want to achieve few things--
add validation message
More generic way to handle for every form.
And I want to add validation rule, like length, email validation,
date validation etc.
Now how can I achieve these?
Use jQuery validate. It does everything you want straight out of the box.
I did something similar to this, except that I wrote my rules in PHP since you need a server-side backup. When the PHP generates the form, it also generates some simple client-side validation that looks like this:
<!-- html field -->
<label for="first">
First Name: <input type="text" name="first" id="first">
<span id="first_message"></span>
</label>
Then the script is like this:
<script>
var formValid = true;
var fieldValid = true;
// Check first name
fieldValid = doRequiredCheck("first");
if (!fieldValid) {formValid = false};
fieldValid = doCheckLength("first", 25);
if (!fieldValid) {formValid = false};
function doRequiredCheck(id) {
var el = document.getElementById(id);
var box = document.getElementById(id + "_message";
if (el.value === "") {
box.innerHTML = "**REQUIRED**";
}
}
function doCheckLength(id,len) {
var el = document.getElementById(id);
var box = document.getElementById(id + "_message";
if (el.value.length > len) {
box.innerHTML = "Too long";
}
}
</script>
Create a simple function:
function validations(day, hour, tap1, tap2, employed){
if( day== "" | hour== "" | tap1== "" | tap2== "" | employed== "" ){
return false;
} else {
return true;
}

Javascript - verify the values of fields with dynamic names

I have a set of text fields qty with dynamic names: like qty541 ; qty542 ; qty957
formed by the word: "qty" and the product id
How can I verify if all my qty fields are empty or not with Javascript ?
Thanks a lot.
The easiest way is to use a javascript framework like JQuery, Protoype, etc. With this framework you can create a search pattern in reg expr manner. If you unable to use one, it does need more work:
One way:
var formObj = document.forms[0]; //as an example
var fields = formObj.getElementsByTagName("input");
for (i=0; i < fields.length, i++)
{
if (fiedls[i].name.indexOf("qty") > 1)
{
//do something
}
}
You can loop through the elements of the form:
var form = document.getElementById('theForm');
var index;
var field;
for (index = 0; index < form.elements.length; ++index) {
field = form.elements[index];
if (field.name.substring(0, 3) === "qty") {
// Check field.value here
}
}
Live example
The above assumes the form has an id, but however you get access to the form element, the rest follows.
Off-topic: A lot of this stuff is made much simpler by the utility functions available in various JavaScript libraries like jQuery, Prototype, YUI, Closure, or any of several others. They also smooth over browser differences (or outright browser bugs), allowing you to focus on the job in hand rather than worrying about browser inconsistencies.
Using:
<p>
<input type="text" name="qty3232" value="43"/><br/>
<input type="text" name="qty5532" value="as"/><br/>
<input type="text" name="qty5521" value=""/><br/>
<input type="text" name="qty3526" value="34"/>
</p>
<br/>
<h3>Log</h3>
<pre id="log"></pre>
Javascript (no jQuery):
var inputs = document.getElementsByTagName('input');
var log = document.getElementById('log');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'text' && inputs[i].name.substring(0,3) == 'qty') {
if (inputs[i].value == '') {
log.innerHTML += inputs[i].name + " value empty.\n";
} else {
log.innerHTML += inputs[i].name + " value not empty.\n";
}
}
}
http://jsfiddle.net/jxmMW/
This is much easier using a selector in jQuery, though.
var log = $('#log');
$('input[name^="qty"]').each(function(){
if (this.value == '') {
log[0].innerHTML += this.name + " value empty.\n";
} else {
log[0].innerHTML += this.name + " value not empty.\n";
}
});
http://jsfiddle.net/jxmMW/1/
Plain JS:
For example use class="quantity" on all fields and use getElementsByClassName - which almost takes us into jQuery mode
window.onbeforeunload=function() {
var elems = document.getElementsByClassName("quantity"); // needs help in some browsers
for (var i=0,n=elems.length;i<n;i++) {
if (elems[i].value!="") {
return "You have filled in a quantity");
}
}
}
window.onload=function() {
document.forms[0].onsubmit=validate;
}
function validate() {
var elems = document.getElementsByClassName("quantity");
for (var i=0,n=elems.length;i<n;i++) {
if (elems[i].value=="") {
alert("Please fill in a quantity");
elems[i].focus();
return false;
}
}
}
standard method:
function validate() {
var elem;
for (var i=0,n=this.elements.length;i<n;i++) {
elem = this.elements[i];
if (elem.name && elem.name.indexOf("qty")===0) {
if (elem.value=="") {
alert("Please fill in a quantity");
elem.focus();
return false;
}
}
}
return true; // allow submit
}

Categories

Resources