How to change a hidden value and the text of the - javascript

I am currently attempting to make a dropdown menu where selecting one of the links from the menu will change the hidden value as well as the text of the hyperlink. This is based upon Twitter's Bootstrap dropdown, and uses jQuery:
<div id="periodChooser" class="btn-group">
<input type="hidden" value="1" name="dtype" id="dtype1"></input>
<a data-toggle="dropdown" href="javascript:;">Weekend</a>
<ul class="dropdown-menu">
<li>Weekend</li>
<li>Week</li>
<li>Midweek</li>
</ul>
</div>
The script that I have attempted to write is as follows:
<script>
jQuery(function($){
$('#periodChooser').each(function() {
$('.dropdown-menu a').click(function() {
$('.btn-group').find('input[type=hidden]').val($(this)
.data('value')).change();
$('.btn-group').find('.btn:eq(0)').text($(this).text());
});
});
});
</script>
Unfortunately, whilst it doesn't return any specific error, the code does not work. Any suggestions?

Bind event out side each
<script>
$('#periodChooser .dropdown-menu a').click(function() {
$('.btn-group').find('input[type=hidden]').val($(this)
.data('value')).change();
$('.btn-group').find('.btn:eq(0)').text($(this).text());
});
</script>

I think that this can be optimized and made more re-usable.
First of all, you are using jQuery selectors like $('.btn-group') very ineffectively.
Secondly it will break, if you will use more than one "widget", because the context is whole document and it will find all elements with that class .btn-group.
Thirdly it would be more effective to use single event handler that is being binded to the parent <ul> element instead of each <a> element. It's called "event delegation". http://api.jquery.com/delegate/
<script>
$('#periodChooser').each(function() {
var $input = $('input', this),
$select = $('>a', this);
$('ul', this).on('click', 'a', function() {
var $this = $(this);
$input.val($this.data('value')).change();
$select.html($this.html());
});
});
</script>
I made this code available in JSBin: http://jsbin.com/welcome/38724/edit
What I did here?
<script>
$('#periodChooser').each(function() {
// Find and store input and "select" element only once.
var $input = $('input', this),
$select = $('>a', this); // This finds only direct child element <a>
// Find the <ul> element inside the #periodChooser
// Bind a click event that will "bubble up" from <a> elements that are children of it
$('ul', this).on('click', 'a', function() {
// Wrap a jQuery around the <a> element
var $this = $(this);
// Set the input value and execute "change" event(s)
$input.val($this.data('value')).change();
// Change the "select" title. Doesn't matter if you use html() or text() - choose yourself!
$select.html($this.html());
});
});
</script>
Now, you can use this to make multiple widgets inside single page! :)
<script>
$('.btn-group').each( /* Well, you know, the function goes here... */ );
</script>
Of course, threre are many other things that has to be done here, like opening and closing the "option list", scrolling and probably many other things...

Related

Get Child Attribute using JQUERY

I am creating a link gallery.
HTML:
<div class="link">
<header>Test Header</header>
Click Here
</div>
I want to go to the A element's URL when clicking anywhere in the div.
Javascript with JQUERY 3.2.1:
$(function() {
$("div.link").click(function() {
$url = $this.children("a").attr("href");
alert($url);
});
});
It doesn't alert the URL
I have also tried:
$(function() {
$("div.link").click(function() {
$url = $this.find("a:first-child").attr("href");
alert($url);
});
});
It returns a collection instead of a single element so I tried the following:
$function() {
$("div.link").click(function() {
$url = $this.find("a");
alert($url[0].attr("href"));
});
});
Neither approach is working. I have confirmed the click selector is functioning by testing it with a simple alert("hello");
EDIT: I was using $this instead of $(this).
I want to goto the A element's URL when clicking anywhere in the div.
Based on the code you have shared, $this seems to be undefined
If you just want to fetch the href property of the child anchor tag, then simply
$("div.link").click(function() {
var href = $(this).find("a").attr( "href" ); //attr will fetch the attribute of first element in the result of find
});
If you want to click on the child anchor tag, then try using one of the following ways
$("div.link").click(function() {
$(this).find("a").first().click();
});
or
$("div.link").click(function() {
$(this).find("a").click();
});
or
$("div.link").click(function() {
$(this).find("a").trigger( "click" );
});
or if you just want to go the URL
$("div.link").click(function() {
window.location.href = $(this).find("a").attr( "href" );
});
If you want to get the href attribute when clicking on the div element, you can consider using the selector $(".nameOfDivClass"). On the element selected you will bind a function that will get your href.
$(".link").on("click", function(){
console.log($(this).children("a").attr("href"))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="link">
<header>Test Header</header>
Click Here
</div>
If you check your browser's console, you'll have an error saying $this is not defined. It should be $(this), in order to turn this (the raw HTML element clicked on) into a jQuery object on which you can the run jQuery methods such as .find() and .attr().
Additionally, this version will actually cause the navigation action rather than just alerting the URL:
$("div.link").click(function() {
$(this).find("a").click();
});

How can I show a DIV by it's attribute value using Jquery

I am working with a Jquery plugin and I would like to trigger the modal (div) by calling it's value instead of calling it's ID name.
So if the attribute value is "554" meaning attrId="554" I will display the modal with the matching "554" attribute. Please keep in mind that the attribute value could be a variable.
My JSFiddle Code Example is here
;(function($) {
// DOM Ready
$(function() {
// Binding a click event
// From jQuery v.1.7.0 use .on() instead of .bind()
$('#my-button').bind('click', function(e) {
// Prevents the default action to be triggered.
e.preventDefault();
// Triggering bPopup when click event is fired
$('#element_to_pop_up').bPopup();
});
});
})(jQuery);
Any help is appreciated. Thanks so much
You can use an attribute equals selector: [attribute="value"]
If your popup div has an attribute like this:
<div id="element_to_pop_up" attrId="554">
<a class="b-close">x</a>
Content of popup
</div>
You can use the following:
var x = '554';
$('div[attrId="' + x + '"]').bPopup();
jsfiddle
Ultimately it needs a unique selector unless you are okay with triggering multiple modals. One way to do it is to use the jQuery each function, and check each div for the matching attribute.
$( "div" ).each(function() {
var criteria = 'example_criteria';
if ($( this ).attr( "attributename" ) == criteria)
{
$(this).bPopup();
}
});

Dynamically created anchor links not receiving 'click' events?

I'm using JS to create the HTML below. (It's a bootstrap dropdown button)
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle my-status" data-toggle="dropdown">
Status <span class="caret"></span>
</button>
<ul class="dropdown-menu status-menu" role="menu">
<li>None</li>
</ul>
</div>
And in JQuery I'm trying to process clicks on the link inside there.
$('li').on('click', 'a.status', function(e) {
e.preventDefault();
alert("hi");
});
I've tried about 6 different ways to select those links, but nothing I do seems to be catching it.
Since they're created dynamically, I know I need to use the 'on' function, but it just doesn't seem to be working in the least.
I can get it to work in a JSFiddle, but the code there isn't created dynamically - which is the issue I think.
Is there something stupidly obvious that I'm missing here?
If that whole chunk of HTML is dynamic, then you need to target the container that HTML is appended to and use on
$(containerOfAppendedContent).on("click", ".btn-group li a", function() {
Assuming the entire block of code you posted is created dynamically, or even just the list, when you bind events to dynamically added elements, you need to bind to elements that are already in the DOM when the code is executed. Try:
$(document).on('click', 'a.status', function(e) {
e.preventDefault();
alert("hi");
});
$(document) is a worst case scenario, so if you have an element closer to the ones being added dynamically that exists when the jQuery is executed, use that over document.
Make sure you are selecting a static parent, so if li is dynamically created too, use its parent or its parent's parent
$('div.btn-group').on('click', 'ul li a.status', function(e) {
e.preventDefault();
alert("hi");
});
if that div is also dynamically created you could go up to the body or even document
$(document).on('click', 'ul li a.status', function(e) {
e.preventDefault();
alert("hi");
});
Why don't you generate the ancor tag with a onclick function?
<li>None</li>
<script>
function DoSomething(){
// Do your work
}
</script>
Hope this helps
Use this
change li to document
$(document).on('click', 'a.status', function(e) {
e.preventDefault();
alert("hi");
});

Get custom css property with a function

This is my code :
<html>
<body>
<button class="myclass" data-card-id="1">Save</button>
</body>
</html>
My question is how whould look like a function that when user click on any of "myclass" buttons submit a variable with data-card-id of the specific card in a php file.
Thank you ! :)
this is using Jquery:
$(".myclass").click(function(){
$(this).attr( "data-card-id" );
});
JSFIDDLE - http://jsfiddle.net/q5j8z/11/
see browser console for data display
// change the selector "ul li a" to your button
$('ul li a').click(function (e) {
e.preventDefault();
var value = $(this).data('value');
$('.button').data('value', value);
console.log($('.button').data('value'));
});
$('.button').click(function (e) {
e.preventDefault();
console.log($(this).data('value'));
});
This can be accomplished through an additional selection feature. I believe "data-card-id" is an attribute of your html tag, so you have two choices.
Bind the click to the element using the selector or delegate it to the body of the document, I think you'll see how either way works here.
Option 1. The advantage here is that when click events bubble up to the body this will check and execut appropriately, even if other buttons are added to the page after this code is executed. This is jquery's click delegation feature
$('body').on('click', 'button[data-card-id="1"]', function(){
//perform your action
});
Option 2. This binds the click event to the object itself. This can be more straight forward and has its advantage in simplicity.
$('button[data-card-id="1"]').click(function(){
// perform some action
});
And of course you have a plethora of other approoaches......
or
$('button').each(function(){
if($(this).attr("data-card-id") == '1'){
$(this).click(function(){
//some action
});
}
});
There are other approaches, too. Let me know if none of these seem to work.
JS FIDDLE DEMO
The most simpler would be to use this code -- >
just change this card-id to this cardid
HTML
<button class="myclass" data-cardid="1">Save</button>
<button class="myclass" data-cardid="2">Save</button>
JS
$(document).ready(function(){
$(".myclass").on('click',function(){
var cid = $(this).data("cardid");
alert(cid);
});
});

Elements appeneded not triggering events

I have a list
<ul id="list">
<li> element one <span class="remover">X</span></li>
<li> element two <span class="remover">X</span></li>
</ul>
and this list is dynamically appended with
<input type="text" id="adder">
<button id="add">Add</button>
<script>
$("#add").click(function(){
$("#list").append('<li>'+$("#adder").val()+' <span class="remover">X</span></li>');
});
</script>
but the problem is this with part
<script>
$(".remover").click(function(){
$(this).parent().remove();
});
</script>
The remove works perfectly with the static added items, but when it comes to the new appended items nothing happens on click, doesn't even trigger the function
I'd suggest:
$('#list').on('click', '.remover', function(e){
$(this).parent().remove();
});
JS Fiddle demo.
References:
on().
parent().
remove().
Call the click function on list and set remover as target like so:
$( '#list' ).on( 'click', '.remover', function (e) {
$(e.target).parent().remove();
});
You can't set a click event directly on it, it has to be set on the element that never is added to the page.
you should use
on('click',function(){})
not
.click()
refer to : http://api.jquery.com/on/
as click will relate to current item within document , while on is related to future items that will be added to document , however you should always use on with something that already exists in your document like for example the parent of the future added element so use something like
$("#parent").children("li").children('.remover').on("click",function(){bla bla bla;});

Categories

Resources