I am trying to write a statement along the lines of: 'if given element does not contain the following text, do something'.
I have tried using :contains as such:
var openingHours = $('.opening-listing:nth-child(' + new Date().getDay() + ')');
if($(openingHours + ':contains("Closed")').length > 0){
//Do something
}
But am getting syntax errors.
Would anyone know what I've done wrong here, or if there is a better way of going about this?
openingHours is a jQuery object, not a css selector. You can use .text(), .indexOf(), which :contains() uses internally
if (openingHours.text().indexOf("Closed") === -1) {
// do stuff
}
Use the :not() CSS selector.
var openingHours = $('.opening-listing:nth-child(' + new Date().getDay() + ')');
if($(openingHours).find(':not(:contains("Closed"))').length > 0){
//Do something
}
They way I understand your question is that; you have an HTML element with some content (text or number). And you want to use that content in decision making such as if-statement.
Here is an example of the code I made in repl.it, click here.
I give each element a unique id name, so that I can call it in JavaScript for decision-making. Then I add onClick which invokes a function in JavaScript.
<form>
<div>
<input type="text" id="inputName" placeholder="Your name">
</div>
<input type="submit" onClick="getName()" value="Submit">
</form>
Next step is to use document.getElementById(tagName).value which receives the content you have written in the inputfield after you click on submit button. And set the value into a next variable instead of copying the whole line of code. Last but not least, I have also added an example if you have jQuery library, I prefer using jQuery approach because it is less code and easier to understand for beginners.
function getName(){
// Gets the value from HTML and inserts the result in new variable called inputName
var inputName = document.getElementById("inputName").value;
// This works only if you have jQuery library included in html part
//var inputName = $("#inputName").val();
// If-statement
if(inputName === "Peter"){
alert("Name is = " + inputName);
} else if(inputName === "Jacob"){
alert("Name is = " + inputName);
}
}
I hope this gives you different perspective on how to solve your problem. Good luck!
Related
I need to make a calculator using JavaScript, HTML and CSS. Everything worked out fine until I came to coding the compute (=) button.
This is my HTML:
<input type="button" value=" = " onclick="compute()">
This is my JS:
function compute() {
var input_var = document.getElementById('input');
ans = Math.floor(+eval(input_var.value));
document.getElementById('answer').value = '=' + 'ans';
}
If anyone that knows how to solve what's wrong, I would greatly appreciate it if you could reply.
First of all, you should post the whole code to get accurate solution!
Probably these could be some of the errors:
Set id attribute of your = button with value "input"
3rd line should be: ans = Math.floor(eval(+input_var.value));
4th line should be: document.getElementById('answer').value = '=' + ans; as StaticBeagle has also mentioned.
You should be lucky that you made the mistake to put the variable in quotes. That's why you don't get a value other than the literal string =ans(maybe, we don't know as you didn't post all code that's needed to give a better answer).
Back to why you're lucky.
Never use eval! eval is evil. (Unless you know what you do, but you don't the next couple of years). To parse a number, you'd use Number(input_var.value).
The next error is that you create a global variable by omitting one of var, let, const for your ans declaration.
The next thing you shouldn't do is to use inline javascript. We use eventListener instead. As said before, it's impossible to answer more specific as your question lacks too many details - however I'll show you how you get a value by pressing a button in the console.
document.getElementById('foo').addEventListener('submit', e => {
// prevent submitting the form (I guess another error in your code)
e.preventDefault();
const value = Number(document.getElementById('input').value);
console.log('The value is: ' + value);
}, false);
<form id="foo">
<input type="number" id="input">
<input type="submit" value=" = ">
</form>
Not sure if ans is a local or global variable, but if its intention is to be a local variable then you should have it like this:
var ans = Math.floor(eval(+input_var.value));
Also, because you're setting the value of your element to '=' + 'ans' you're actually setting it to the actual string 'ans'. If you want to refer to what ans is you should write it like this:
document.getElementById('answer').value = '=' + ans;
I have a variable that finds the data attribute of an element that is clicked on in a callback function:
var dropdown = document.getElementsByClassName('js-dropdown');
for (i = 0; i < dropdown.length; i++) {
dropdown[i].addEventListener("click", callBack (dropdown[i]));
}
function callBack (i) {
return function () {
var thisDropdown = i.getAttribute('data-dropdown');
//rest of the code here
}
}
I am basically trying to do this
$('#' + thisDropdown ).toggleClass('is-active');
...but in vanilla JS.
This works fine using jQuery however I would like a vanilla version.
So when a user clicks on an element that activates a drop down, I want it to dynamically find its relevant ID matching value within the document so it can toggle a show/hide class.
I've searched through a lot of SO questions and everyone replies with a jQuery answer which is not what I am looking for.
I've been trying to do something along the lines of
var idValue = document.getElementById(thisDropdown);
Then
var findId= idValue + thisDropdown;
findId.toggleClass('is-active');
Obviously that does not work the same way the jQuery statement works... any ideas?
Ignore the toggleClass method! Some of you may find this contradictory as I want vanilla JS.
To replace $('#' + thisDropdown ).toggleClass('is-active'); with plain js, use Element.classList. Like this:
const someElement = document.querySelector('#' + thisDropdown);
someElement.classList.toggle("is-active");
I like #kamyl's answer, but you might need backward compatibility. For that, see if you can find a polyfill.
If you have to write it yourself, use string.split(" ") to get your list of active attributes and iterate to find if it exists; add if not, remove if so...then array.join(" ") and replace the class attribute with it.
Please I have my Jquery code that I want to do few things since. I have a form with a bunch of textboxes. I want to validate each textbox to allow numbers only. To also display error where not number.
var validateForm = function(frm){
var isValid = true;
resetError();
$(":text").each(function(variable){
console.log("The variable is" , variable);
if(!isNormalInteger(variable.val))
{
$("#error"+variable.id).text("Please enter an integer value");
isValid = false;
}
});
if(!isValid)
return false;
};
The above fails. When I print the variable on my console I was getting numbers 0 - 9. My textboxes where empty yet, it returns numbers. I tried variable.val() still fails and return numbers. I modified my select to
$("input[type=text]", frm).each();
Where my form is my form selected by id. It also failed. Below is the example of my html label and textbox. I have about ten of them
<div class="grid-grid-8">
<input class=" text" id="id" name="name" type="text">
<br>
<p class="hint">Once this limit is reached, you may no longer deposit.</p>
<p class="errorfield" id="errorMAXCASHBAL"></p>
Please how do I select them properly? Moreover, my reset function above also returns incrementing integers for value. The p property is of class errorField and I want to set the text property. Please how do I achieve this? Previously I tried the class name only $(.errorField). It also failed. Any help would be appreciated.
var resetError = function(){
//reset error to empty
$("p errorfield").each(function(value){
console.log("the val", value);
//value.text() = '';
});
};
//filter non integer/numbers
function isNormalInteger(str) {
return /^\+?\d+$/.test(str);
}
The main problem is your selectors in javascript. And as laszlokiss88 stated wrong usage of .each() function.
Here is a working example of your code: jsFiddle in this example all .each() functions use $(this) selector inside instead of index and value
You are using .each wrong because the first parameter is the index and the second is the element. Check the documentation.
Moreover, the correct selector for the resetError is: p.errorfield
So, you should modify your code to look something like this:
var resetError = function(){
$("p.errorfield").each(function (idx, element) {
$(element).text("");
});
};
With this, I believe you can fix the upper function as well. ;)
I have a script that is taking too long to run and that is causing me This error on ie : a script on this page is causing internet explorer to run slowly.
I have read other threads concerning this error and have learned that there is a way to by pass it by putting a time out after a certain number of iterations.
Can u help me apply a time out on the following function please ?
Basically each time i find a hidden imput of type submit or radio i want to remove and i have a lot of them . Please do not question why do i have a lots of hidden imputs. I did it bc i needed it just help me put a time out please so i wont have the JS error. Thank you
$('input:hidden').each(function(){
var name = $(this).attr('name');
if($("[name='"+name+"']").length >1){
if($(this).attr('type')!=='radio' && $(this).attr('type')!=='submit'){
$(this).remove();
}
}
});
One of the exemples i found : Bypassing IE's long-running script warning using setTimeout
You may want to add input to your jquery selector to filter out only input tags.
if($("input[name='"+name+"']").length >1){
Here's the same code optimised a bit without (yet) using setTimeout():
var $hidden = $('input:hidden'),
el;
for (var i = 0; i < $hidden.length; i++) {
el = $hidden[i];
if(el.type!=='radio' && el.type!=='submit'
&& $("[name='" + el.name + "']").length >1) {
$(el).remove();
}
}
Notice that now there is a maximum of three function calls per iteration, whereas the original code had up to ten function calls per iteration. There's no need for, say, $(this).attr('type') (two function calls) when you can just say this.type (no function calls).
Also, the .remove() only happens if three conditions are true, the two type tests and check for other elements of the same name. Do the type tests first, because they're quick, and only bother doing the slow check for other elements if the type part passes. (JS's && doesn't evaluate the right-hand operand if the left-hand one is falsy.)
Or with setTimeout():
var $hidden = $('input:hidden'),
i = 0,
el;
function doNext() {
if (i < $hidden.length) {
el = $hidden[i];
if(el.type!=='radio' && el.type!=='submit'
&& $("[name='" + el.name + "']").length >1) {
$(el).remove();
}
i++;
setTimeout(doNext, 0);
}
}
doNext();
You could improve either version by changing $("[name='" + el.name + "']") to specify a specific element type, e.g., if you are only doing inputs use $("input[name='" + el.name + "']"). Also you could limit by some container, e.g., if those inputs are all in a form or something.
It looks like the example you cited is exactly what you need. I think if you take your code and replace the while loop in the example (keep the if statement for checking the batch size), you're basically done. You just need the jQuery version of breaking out of a loop.
To risk stating the obvious; traversing through the DOM looking for matches to these CSS selectors is what's making your code slow. You can cut down the amount of work it's doing with a few simple tricks:
Are these fields inside a specific element? If so you can narrow the search by including that element in the selector.
e.g:
$('#container input:hidden').each(function(){
...
You can also narrow the number of fields that are checked for the name attribute
e.g:
if($("#container input[name='"+name+"']").length >1){
I'm also unclear why you're searching again with $("[name='"+name+"']").length >1once you've found the hidden element. You didn't explain that requirement. If you don't need that then you'll speed this up hugely by taking it out.
$('#container input:hidden').each(function(){
var name = $(this).attr('name');
if($(this).attr('type')!=='radio' && $(this).attr('type')!=='submit'){
$(this).remove();
}
});
If you do need it, and I'd be curious to know why, but the best approach might be to restructure the code so that it only checks the number of inputs for a given name once, and removes them all in one go.
Try this:
$("[type=hidden]").remove(); // at the place of each loop
It will take a short time to delete all hidden fields.
I hope it will help.
JSFiddle example
Here I have get one error in JavaScript div_element is null or not an object.
I have given my code below:
function showLoading(id) {
div_element = $("div#" + id)[0];
div_element.innerHTML = loading_anim; // Error in this line
}
When I am debugging my script but it's working fine in other browsers including IE 8, but it's not working in IE 7. I don't understand what exact issue occur in this script.
First of all, you dont need to put a tag name infront of the jQuery, unless you have other elements with exact same id on other elements, in other pages.
Next, your statement div_element.innerHTML = loading_anim; is correct. So, the only explanation is that, there is no element with that ID, in the DOM.
Finally, since you are usign jQuery already, no need to mix up native JS and jQuery to create a dirty looking code.
function showLoading(id) {
div_element = $("#" + id);
console.log(div_element); //check the console to see if it return any element or not
div_element.html(loading_anim);
}
I think you don't select anything with your jquery selector (line 2)
try to display
id
"div#" + id
$("div#" + id)
$("div#" + id)[0]
You can use firebug javascript console or a simple alert like this:
alert($("div#" + id)[0]);
And see if you must id or class on your div ( use # or . selector)
I suppose, that nic wants to display some loader GIF animation, I confirm, that nic must use jQuery .html() method for DOM objects, and tusar solution works fine on IE6+ browsers. Also (it is obvious but anyway) nic must assign a value to loading_anim variable in script, lets say: var loading_anim = $('#loader').html(); before assigning its value to div_element.
Use .html() for jQuery objects. innerHTML work for dom objects, they wont work for jQuery objects.
function showLoading(id) {
div_element = $("div#" + id);
$(div_element).html(loading_anim); // Provided `loading_anim` is valid html element
}