Using .click instead of onclick and getting a variable value - javascript

I have seen that the inline/html events like onclick, mouseover etc are being used less and less and it is advised to register events using Javascript.
I currently have some HTML like:
<ul id="supported-locations">
<li onclick="setLocationId(32);">Mexico</li>
<li onclick="setLocationId(35);">Mongolia</li>
</ul>
Which works fine but I want to now do this without the "onclick" in the HTML but still be able to retrieve the ID number.
The <li> elements are retrieved via AJAX while the user types into an input box it queries the database and retrieve the data without loading the page.
When the user clicks on one of the countries it will run the setLocationId function which just simply sets a hidden HTML form element with the ID of the selected country so I can use that once the form is submitted.
How do you register an event listener for these <li>'s when the countries and their ID's will always be different and changing depending on what the user types into the box?

Use a data attribute to hold the number. On the onclick event, read the attribute on the element that was clicked.
HTML:
<ul id="supported-locations">
<li data-code="32">Mexico</li>
<li data-code="35">Mongolia</li>
</ul>
JavaScript:
$("#supported-locations").on("click", "li", function() {
var li = $(this);
console.log(li.data("code"));
});
Example:
JSFiddle

<ul id="supported-locations">
<li data-id="32">Mexico</li>
<li data-id="35">Mongolia</li>
</ul>
in jQuery
$('#supported-locations').on('click','li',function(){
setLocationId($(this).data('id'));
})

<ul id="supported-locations">
<li data-id="32">Mexico</li>
<li data-id="35">Mongolia</li>
</ul>
jQuery(function(){
$('#supported-locations li').click(function(){
alert($(this).data('id'))
})
})

I recommend giving a class to the dynamically loaded elements, then use jquery .on(http://api.jquery.com/on/) method to register event listeneres to elements belonging to a class, even those that are dinamically loaded..
Then you could just read out the data stored in the element(in the form of data-something attributes).

<ul id="supported-locations>
<li id="32">Mexico</li>
<li id="35">Mongolia</li>
</ul>
//Jquery
$("#supported-locations > li").on('click',function(){
setLocationId($(this).attr('id'));
});

When you register your event, you still have the ability to use this, which is linked to the HTML element.
In other word, you still can do something like that
<li id="YOUR_ID">Mexico</li>
And get the id of the li tag

You can attach an event handler to the li:
<ul id="supported-locations">
<li id="location32">Mexico</li>
<li id="location35">Mongolia</li>
</ul>
$("#supported-locations li").click(function() {
alert($(this).attr("id"));
});
http://jsfiddle.net/puL95/

try this.
$("#supported-locations li").click(function() {
alert("me")
}

Related

JQuery on click link with href atribute

I have the following code structure. Its a set of wordpress tabs. I have many tabs all over the website, using Jquery i want to trigger a function when a user clicks one of the links, however i cant apply a ID atribute so my funtion below doesnt work...any suggestions?
JQUERY
$('#1485856532455-70ee0dfe').on('click', function() {
$('.otherdiv').css('background-image', 'url(http://placehold.it/200x200/ff0000)');
})
HTML
<ul class="vc_tta-tabs-list">
<li class="vc_tta-tab">
<span class="vc_tta-title-text">Title</span>
</li>
<li class="vc_tta-tab">
<span class="vc_tta-title-text">Title</span></li>
</ul>
You can't select them by ID because they don't have IDs. But you can use CSS Atrribute-Equal Selector to get them by href attribute. Like this:
$('[href="#1485856532455-70ee0dfe"]').on('click', function() {
// ...
}
More CSS Selectors here.
Working code snippet:
$('[href = "#1485856532455-70ee0dfe"]').click(function() {
alert("#1485856532455-70ee0dfe was clicked! Hoooray!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="vc_tta-tabs-list">
<li class="vc_tta-tab">
<a href="#1485856532455-70ee0dfe"> <span class="vc_tta-title-text">Title</span>
</a>
</li>
<li class="vc_tta-tab">
<span class="vc_tta-title-text">Title</span>
</li>
</ul>
Use attribute selector then :
$('[href="#1485856532455-70ee0dfe"]').on('click', function() {....});
$('#1485856532455-70ee0dfe').on('click', function() { - means that on page we have some element with id 1485856532455-70ee0dfe. In your html code no id with text 1485856532455-70ee0dfe, thats why your code not work.
You have two case to fix:
add id's to needed element
change js to $('[href="1485856532455-70ee0dfe"]').on('click', function() {
You cant give a id to a link like that. However you can select the link with jquery by doing $('[href="#1485856532455-70ee0dfe"]').on('click', function() {....});

jquery .click() function on specific attribute, returns multiple elements

I have a problem with jquery and the .click() function, when clicking on a <li data-link-url="..."> element, that shares the data-link-url attribute.
This is my HTML structure:
<nav class="fullListHover">
<ul>
<li class="oneHub">
<ul>
<li data-link-url="... /templateA.html">
<ul>
<li data-link-url="... /templateB.html"></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
And this is my jquery click() function:
<script type="text/javascript">
$("[data-link-url]").click(function(){
window.location.href=$(this).attr("data-link-url")
});
</script>
When I click on the li-tag with ".../templateB.html" I get redirected to ".../templateA.html".
So I debugged the whole thing and logged the $(this) variable. When I clicked on ".../templateB.html" the output was:
.../templateB.html
.../templateA.html
It seems like, the .click() function runs a second time.
How can I select just the templateB or prevent the click function to run a second time ?
P.S.: I hope my question is understandable. English isn't my primary language.
Your issue is because you have nested li elements with the data-link-url attribute, hence the click handler is invoked once for each element in the hierarchy as the event bubbles up the DOM. To fix this, call stopPropagation() in the event handler:
$("[data-link-url]").click(function(e) {
e.stopPropagation();
window.location.href = $(this).data('link-url');
});

jQuery update li class attribute href after ajax call

I'm using my Wordpress site and have a popup modal window that just presents some radio buttons (#input_1_1). When changing value of the radio button field an ajax call is run and performs a simple mySql table update. All goes well and I would like to perform a change of the text of the href I used to open the window in the first place.
Below is the javascript I got so far, but the second JQuery row from the bottom does not execute the change I want. Regardless of even just trying to change the simple target url.
jQuery(document).ready(function(){
jQuery("#input_1_1").change(function(){
jQuery("body").css("cursor", "wait");
var commitmentID = jQuery("#gform_1 input[type='radio']:checked").val();
jQuery('#popmake-710').popmake('close');
jQuery.ajax({
url:"<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php",
type:'POST',
data:'action=gf_submit_1_1&commitmentID=' + commitmentID,
success:function(results)
{
//Here is the problem I've been working on for too many hours/days now
jQuery("#et-secondary-nav > li.popmake-fast-select-commitment.current_commitment_text.menu-item.menu-item-type-post_type.menu-item-object-page.menu-item-563").attr('href',"http://www.TheSameUrlButILikeADifferentTextToIt.com");
//See line above
jQuery("body").css("cursor", "default");
}
});
});
});
This is how the HTML for that part of the page looks like
<div id="et-secondary-menu">
<ul id="et-secondary-nav" class="menu">
<li class="bp-menu bp-profile-nav menu-item menu-item-type-custom menu-item-object-custom menu-item-152"></li>
<li class="popmake-fast-select-commitment current_commitment_text menu-item menu-item-type-post_type menu-item-object-page menu-item-563" style="cursor: pointer;">
<a href="http://www.myoriginalurlisjustfine.com/">
<i class="wp-svg-heart heart"></i>
THIS IS THE TEXT THAT I WANT TO HAVE CHANGED BY THE JQUERY AND IS THE TEXT PRESENTED IN THE SECONDARY WORDPRESS MENU
</a>
</li>
while you use
jQuery("#et-secondary-nav > li.popmake-fast-select-commitment.current_commitment_text.menu-item.menu-item-type-post_type.menu-item-object-page.menu-item-563")
and this will just select the li which not has a href attr so you need to use (> a)
jQuery("#et-secondary-nav > li.popmake-fast-select-commitment.current_commitment_text.menu-item.menu-item-type-post_type.menu-item-object-page.menu-item-563 > a").attr('href',"http://www.TheSameUrlButILikeADifferentTextToIt.com");
jQuery("#et-secondary-nav > li.popmake-fast-select-commitment.current_commitment_text.menu-item.menu-item-type-post_type.menu-item-object-page.menu-item-563").attr('href',"http://www.TheSameUrlButILikeADifferentTextToIt.com");
you are seleting the li here not a
change it to
jQuery("#et-secondary-nav > li.popmake-fast-select-commitment.current_commitment_text.menu-item.menu-item-type-post_type.menu-item-object-page.menu-item-563 > a").attr('href',"http://www.TheSameUrlButILikeADifferentTextToIt.com");
Use
jQuery("#et-secondary-nav > li.popmake-fast-select-commitment.current_commitment_text.menu-item.menu-item-type-post_type.menu-item-object-page.menu-item-563 a").attr('href',"http://www.TheSameUrlButILikeADifferentTextToIt.com");
to change the href. As others pointed out, you weren't change the <a> but the <li>.
Check https://api.jquery.com/category/selectors/ for reference on jQuery selectors.

how to pick up string inside a <li> tag using jquery

I've a simple list and a form text-field:
<ul>
<li class="item">one</li>
<li class="item">two</li>
<li class="item">three</li>
<li class="item">four</li>
</ul>
<input id="field" type="text" />
When the user clicks on an <li> item, I want the string inside the li element to be assigned the value of the input field.
Something like:
$('.item').click( function(){
$('#field').val(/*put the string inside the li element just clicked*/);
});
So how do I get the string in the li element?
$('.item').click(function(){
$('#field').val($(this).html());
});
I'd personally suggest using a very similar suggestion to those already-posted, but with text() rather than html:
$('.item').click(
function(){
$('#field').val($(this).text());
});
It's a slim justification, but, as the docs note:
Unlike the .html() method, .text() can be used in both XML and HTML documents.
Otherwise they seem to be much the same.
Reference:
text();
.html() is what you're looking for. Please look it up in the API : http://api.jquery.com/html/
$('.item').click( function(){
$('#field').val($(this).html());
});
$('.item').click( function(){
$('#field').val($(this).html());
});

Creating a javascript function to switch classes between list elements depending on which one has been clicked

I am trying to create a function to change the class on a series of 5 list elements depending on which has been clicked. The goal is to change the style of the element depending on which one is the current element.
I had tried something like this:
function addClass(obj)
{
obj.className="highlight";
}
and then added this to my elements:
onclick="addClass(this);
but this only added the class to the first element in the list and then did not remove the class when a different one was clicked.
My list elements look like this:
<ul id="circularMenu">
<li id="strategy_link"><h3>Strategy</h3></li>
<li id="branding_link" onclick="addClass(this);"><h3>Branding</h3></li>
<li id="marketing_link" onclick="addClass(this);"><h3>Marketing</h3></li>
<li id="media_link" onclick="addClass(this);"><h3>Media</h3></li>
<li id="management_link" onclick="addClass(this);"><h3>Management</h3></li>
</ul>
When an item is clicked the url changes, maybe this could be the way to set up the function to change classes depending on the url? I am very new with javascript any ideas on how to make this work would be greatly appreciated.
The current way I have it coded is to change each item when hovered, but I would like the change to remain until a different item is clicked. It can be viewed here: http://perksconsulting.com/dev/capabilties.php The items I am referring to are the black dots on the left side of the page.
First, you should use the jQuery addClass() method. You don't need to write your own (your addClass() implementation is buggy, by the way).
Try this:
function selectInList(obj)
{
$("#circularMenu").children("a").removeClass("highlight");
$(obj).addClass("highlight");
}
Then:
<ul id="circularMenu">
<li id="strategy_link"><h3>Strategy</h3></li>
<li id="branding_link" onclick="selectInList(this);"><h3>Branding</h3></li>
<li id="marketing_link" onclick="selectInList(this);"><h3>Marketing</h3></li>
<li id="media_link" onclick="selectInList(this);"><h3>Media</h3></li>
<li id="management_link" onclick="selectInList(this);"><h3>Management</h3></li>
</ul>
Or even better, keep your html clean and let jQuery simplify things:
<ul id="circularMenu">
<li id="strategy_link"><h3>Strategy</h3></li>
<li id="branding_link"><h3>Branding</h3></li>
<li id="marketing_link"><h3>Marketing</h3></li>
<li id="media_link"><h3>Media</h3></li>
<li id="management_link"><h3>Management</h3></li>
</ul>
Then, somewhere in your page:
$(document).ready(function()
{
$("#circularMenu").children("a").click(function() { selectInList(this) });
});
Try this out.
function addClass(obj)
{
$(obj).addClass("Highlight");
}

Categories

Resources