Getting started with jQuery -- hiding an element - javascript

Have you noticed that every 10 questions on this site is about jQuery?
Anyway...
I'm using jQuery for the first time. I don't know if I loaded it correctly. When I run this code:
<script type="text/javascript">
function allDayClicked() {
if (jQuery) alert("loaded");
var allday = document.getElementById("allDayEvent");
var start = document.getElementById("<%=startTimeSelector.ClientID%>");
$('allDayEvent').hide();
}
</script>
The alert appears, saying "loaded", but nothing else happens; the html checkbox doesn't go invisible. I get no kind of error in my javascript output.
Is it possible I haven't successfully loaded jQuery? I added a reference to it in my visual studio project and generated this by dragging it to default.aspx:
<script src="Scripts/jquery-1.6.1.min.js" type="text/javascript"></script>
Otherwise, what's going on?

jQuery takes a css selector, not an id. If you want an id use the css form of declaring an id.
$('#allDayEvent').hide();

jQuery is loaded fine, you're just using it incorrectly. You should be doing either:
$('#allDayEvent') // recommended, the '#' means ID
Or:
$(allday) // since you already grabbed it with getElementById
jQuery can take a lot of different objects with $(). The options are listed here.

You are missing the # in your ID selector.
Change $('allDayEvent').hide();
to
$('#allDayEvent').hide();

Assuming that your checkbox has an id "allDayEvent", you just need the hash (#) in this line:
$('#allDayEvent').hide();

Related

0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'SumoSelect'

I'm getting the above error message when trying to call the SumoSelect function against a select option element on an aspx page.
I have the following references in my web page:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js" type="text/javascript"></script>
<script src="jquery.sumoselect.js" type="text/javascript"></script>
<link href="sumoselect.css" rel="stylesheet" />
With the files taken from:
https://github.com/HemantNegi/jquery.sumoselect/zipball/master
At present I have only included the following in my project from the download:
jquery.sumoselect.js
sumoselect.css
My jQuery is correctly locating one of the element with:
<script type="text/javascript">
$(document).ready(function () {
var elements = document.getElementsByTagName("*");
for (i = 0; i < elements.length; i++) {
element = elements[i];
name = element.id;
if (name.match(/FieldId_3/)) {
$(element).SumoSelect();
}
}
});
</script>
However, when it reaches $(element).SumoSelect(); it produces the error "0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'SumoSelect'"
I'm very new to jQuery/Javascript, but have tried multiple permutations of trying to call this function and pass the object, however none have worked.
Any ideas to help me get it working?
I'll be grateful for any assistance.
first of all, you are using jQuery, why bother using Vanilla JavaScript to get DOM Elements, and iterate over all collection, only to get one element by its id? (id property should be unique in the document)
You can refactor your code and initialize your plugin only on the elements that meet the selector criteria:
$(document).ready(function () {
$('#FieldId_3').SumoSelect();
});
If no elements meet the criteria, the plugin not will be initialized (safely), because jQuery return an empty like-array object.
And obviously, the element with id FieldId_3 must be a select element, as mentioned here: https://hemantnegi.github.io/jquery.sumoselect/
The method you are using to run SumoSelect is, as the others have said, somewhat overkill, to put it mildly.
However, I have tested your code and it does work, assuming that the jquery.sumoselect.js file is in the same directory as the HTML file in question.
I would suggest, then, that your problem is that the SumoSelect jQuery plugin is not being found.
Once that error is fixed, however, you should run SumoSelect in the manner suggested by Nick R.
(I work with Malieki and have picked this up, for completeness...) After a couple of hours trial and erroring, I found that when I comment out the code below, the sumoselect part starts working ok.
We where experimenting with Saplin.Controls DropDownCheckBoxes first and then found sumoselect but we left a control in the same aspx (for Saplin).
<asp:DropDownCheckBoxes ID="TypeCB" runat="server" OnSelectedIndexChanged="TypeCB_SelectedItemsChanged" AutoPostBack="True" Font-Size="7pt" font-family="Verdana" CssClass="txt_box"
AddJQueryReference="True" meta:resourcekey="checkBoxes2Resource1" UseButtons="True" UseSelectAllNode="False">
<Style2 SelectBoxWidth="160" DropDownBoxBoxHeight="230" DropDownBoxBoxWidth="200" />
<Texts OkButton="Ok" CancelButton="Cancel" SelectAllNode="ALL" SelectBoxCaption="Type" />
</asp:DropDownCheckBoxes>
When this control is removed the sumo jquery stuff all starts working ok.
I can only assume a conflict between them.
Thanks for the help though guys, we're both new to this.

jQuery function .prepend() don't work with wordpress nav menu item

I have a menu in Wordpress and I want to hook up Appointlet script to it. The code is here:
(function(e,t,n,r)
{
if(e)return;
t._appt=true;
var i=n.createElement(r),s=n.getElementsByTagName(r)[0];
i.async=true;i.src='//dje0x8zlxc38k.cloudfront.net/loaders/s-min.js';
s.parentNode.insertBefore(i,s)
})
(window._appt,window,document,"script")
<div data-appointlet="tfracine">
</div>
My idea is to create menu item with blank name, get its id (for example, "#menu-item-66"). Then add my code in front of it using jQuery function.prepend().
So I created custom js file, included it in the header.php file and the code inside the file was this:
$(document).ready(function(){
$( "#menu-item-66" ).prepend( "Test" );
});
I started with the word "Test" to figure out if it works.
Unfortunately, nothing happened and I have lack of skills to figure out why. Any suggestions or smarter way to do it?
The jQuery .prepend() function will prepend a jQuery element, not a string.
So, you have to create a jQuery element by doing:
var newElement = $('<p>New Element</p>');
In your case, what you could do is:
$(document).ready(function(){
$('#menu-item-66').prepend($('<p>This is a jQuery element</p>');
});
For a complete reference, check the .prepend() documentation out.
.prepend() and .prependTo() adds the specified content as the first child.
The question is bit not clear. Do you want to insert your script inside your
div ?

Dynamically change page title from h1 tag using Javascript

First off, thanks for taking the time to read this question. What a great community Stack Overflow has :)
I need to change the title tag of a page based on the text contained in the h1 element on that page.
I've been searching around, and I have found the "document.title" Javascript function. I've been playing around with it, trying to pull the text from my h1 element that has the class of "Category-H1".
<script type="text/javascript">
document.title = document.getElementsByClassName("Category-H1");
</script>
However, it is just setting the page title to "[object HTMLCollection]", which as I understand is a null value. Is JS the best was to do this? I know my code is jacked, any tips?
Thanks in advance! - Alex
Edit
I have been informed that line of code returns a collection object and not a string. It was pointed to a code example of:
setTimeout(function () { document.title = "iFinity User Profile - " + document.getElementById("test").outerText; }, 1000);
However, this code produces a page title of "iFinity User Profile - undefined". I have the h1 element on that page set to the id of "test".
You're almost there.
[object HTMLCollection] is not a null value--it is the string representation of a collection of html elements. You want to choose the first one and then get the inner html from it.
document.getElementsByClassName("Category-H1")[0].innerHTML
Also, make sure you do this after the document has loaded. You can either do this by adding the script at the end of your document, or have it run on the onload event of the body.
This should work:
document.title = document.getElementsByClassName("Category-H1")[0].innerHTML;
The getElementsByClassName() function returns a collections of elements ( [object HTMLCollection], so you need to get an element out of it, I'm assuming the first one.
A better solution may be the following:
<script type="text/javascript">
document.title = document.getElementsByTagName("H1")[0].innerHTML
</script>
This would save from setting a h1 class.
This is very close, but I found that - working with Firefox anyway, when you use the getElementsByTagName("H1") it gives you an array as you have recognized. However, it works better using:
<script type="text/javascript">
document.title = document.getElementsByTagName("H1").item(0).innerHTML;
</script>
Note the addition of the .item(0).innerHTML after getting the element rather than the [0].innerHTML.
I don’t know if you have any experience in it or not, but another alternative that seems to be very popular these days is the use of jQuery. As in the earlier discussions, the code below assumes that you are interested in grabbing the first instance of the “H1” tag or the “Category-H1” class. This is an important point because unless you target an “ID” attribute, you will get a collection of items.
This code also assumes that you have already implemented the inclusion of the jQuery library either directly from your website or by referencing a CDN.
<script type="text/javascript">
$(document).ready(function () {
document.title = $("H1")[0].innerText;
});
</script>
The $(document).ready will call it’s enclosed function only after the Document Object Model (DOM) has finished loading, and before the browser’s rendering engine displays the page.
The content inside the function will grab the inner text of the first instance of the “H1” tag and assign that text value to the document’s title tag in the head section.
I hope this adds another layer of help.

Help with JQuery conditional statement

I am trying to run some JQuery script on a particular page but only if a certain page loads.
The Scenario: We have one page that loads (i.e., webpage.aspx) and it loads different content based on the referring click. (i.e., webpage.aspx?contentId=1, webpage.aspx?contentId=2, webpage.aspx?contentId=3, etc). Here is my problem. I need to have a particular part of the page removed if only one specific contentId is pulled. I am trying to do this in JQuery and can't seem to figure it out.
Here's what i have been working with so far. I realize it's not correct but hopefully it gives you a starting point to work with.
Thanks.
CODE:
$(window).load(function() {
var $deleteNewRow = $("div.col.w140 tbody:first").find("td:first").parent().remove();
if($('#dealer-info h1').indexOf('Ferrari') != -1) {
$deleteNewRow
}
});
What you store in your $deleteNewRow variable isn't the jQuery method, that method will already execute. You want to do that method in your if statement, something like this (note that you are also missing the .text() in the if statement):
$(window).load(function() {
if($('#dealer-info h1').text().indexOf('Ferrari') != -1) {
$("div.col.w140 tbody:first").find("td:first").parent().remove();
}
});
You can use jQuery :contains selector to check for the existence. Here is the docs.
Then to delete find the element and then use remove.
$("div.col.w140 tbody:first").find("td:first").parent().remove();

Problem with jQuery - error when trying to find 2 tags

I have the following DOM structure:
/*:DOC += <div id='testDiv' class='testDivClass'><div id='innerTestDiv'></div></div><span id='testSpan' class='testSpanClass'><span id='innerTestSpan'></span></span>
Now I tried to run jQuery select against them as follow. The first one returned alright, but the second one failed:
// works
var result = $('#testDiv')[0];
alert(result.id);
// failed: id is null or not an object
var result2 = $('#testSpan')[0];
alert(result2.id);
I tried selecting id instead of class and got the same results.
My question is: how can I get the second select to work? Is there some sort of invisible iterator/pointer in jQuery which I need to reset to the beginning of the DOM before the second select?
Thanks.
EDIT: Ok this is the official "does not work" version. testDiv matched, but testSpan did not, hence I got an error saying id is null or not an object error in the second alert.
UPDATE: I did a test by swapping testDiv and testSpan in the html. Now BOTH select failed.
UPDATE2: I have changed the html back to what it used to look like. I'm using JsTestDriver to write up the test, but it is actually not calling anything at the moment. The actual html looks messier than this (more nested tags). I'm trying to get this simplified version to work first. It appears that jQuery was able to get into the first select, whether it'll be span or div, but couldnt get out of it to do the second select. I've replaced jQuery.js and jsTestDriver.jar to no avail.
Thanks.
The .className selector matches by class, not ID.
Therefore, $(span.testSpan) won't match any elements.
You need to change it to $('span.testSpanClass') ot $(span#testSpan') (using the #id selector, which matches ID).
For more information, read the documentation.
I don't know why, but for me your code worked well.
I added $(document).ready(function() { before that code, and when I opened the test page, the alert box showed up perfectly, both of them! I don't know when do you want this alert box showed, but if it is when visitor open the page, just add that code. Otherwise, add
function objectid() {
var result = $('#testDiv')[0];
alert(result.id);
var result2 = $('#testSpan')[0];
alert(result2.id);
}
That code worked well for me, too.
PS: Sorry if you don't understand my bad english.
More than likely, there is something else wrong with the HTML you're actually using. Since you're posting only a tiny bit of the html, we can't actually test your problem. Post the entire page, or at least the smallest piece of it that actually has the problem when you run your test.
I tested the jQuery code you reported on JS Bin, and the code worked fine. As the code is very basic, I don't think the problem is caused by the version of jQuery used.
What I ended up doing is wrapping the entire html with a div or span tag. I found that jQuery could not get out of a div/span tag once it gets into one (in my above example), so I just make it to go into a div/span tag once.
Not sure whether this is a patch or ugly fix, but it solved my problem for now.
Thanks for all the help!
Use "#" to select by id, use "." to select by class...

Categories

Resources