How to update the value of data attribute using jquery - javascript

I have the following bootstrap data toggle markup and I want to change the icon and the text to change on toggle. I can get the text to change but not the icon. What I'm I doing wrong?
<div id="collapseDiv" >
<dl>
<dt>...</dt>
<dd>...</dd>
</dl>
</div>
Show More
Jquery code is as follows
$('#collapseDiv').on('shown.bs.collapse', function () {
$('.icon-before').data('icon', '&#xf147').text('Show Less');
});
$('#collapseDiv').on('hidden.bs.collapse', function () {
$('.icon-before').data('icon', '&#xf196').text('Show More');
});

Try using attr()
attr('data-icon', '&#xf147')
Also check this excellent answer
EXPLANATION
Check the following example.
If you click on span#one the attribute changes with attr() function, if you click on span#two we will try to change the attribute with data() function.
When you try to select the element with [data-test="false"] only the first element has changes it's data attribute.
Only the element with data-test="false" will get red:
$(document).on('click', 'span', function() {
var that = $(this);
var id = that.attr('id');
if (id == 'one') {
//Try with attr()
that.attr('data-test', 'false');
} else if (id == 'two') {
//Try with data()
that.data('test', 'false');
}
$('[data-test="false"]').css({'color':'red'});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="one" data-test="true">one</span>
<span id="two" data-test="true">two</span>

You should update the attribute value, rather than updating data property:
$('#collapseDiv').on('shown.bs.collapse', function () {
$('.icon-before').attr('data-icon', '&#xf147').text('Show Less');
});
$('#collapseDiv').on('hidden.bs.collapse', function () {
$('.icon-before').attr('data-icon', '&#xf196').text('Show More');
});

You should also update class of .ui-icon inside.
var oldIcon = $('.icon-before').data('icon'),
newIcon = '&#xf147';
uiIcon = $('.icon-before').data('icon', newIcon).find('.ui-icon');
uiIcon.removeClass('ui-icon-' + oldIcon).addClass('ui-icon-' + newIcon);

Related

why is button toggle not working with class?

When I change my button toggle from ID-Name to Class-Name, the function is not working anymore. Does anyone know why?
I need a class since this button is multiple times on the page and loads in separately via css and sliders. The function and content is still the same.
$(document).ready(function(){
$('.infoBtn').on('click', function () {
var text=$('.infoBtn').text();
if(text === "info"){
$(this).html('close');
} else{
$(this).text('info');
}
});
});
The issue is your use of selector inside the click event:
$('.infoBtn').text();
Pointy:
Your code should use $(this), not $('.infoBtn') inside the handler.
What you have now will get the text only from the first one on the
page.
If you change that to $(this), it should work as required:
$(this).text();
$(document).ready(function(){
$('.infoBtn').on('click', function(){
//REM: Use $(this) and not $('.infoBtn')!
let text = $(this).text();
$(this).text((text === 'info') ? 'close' : 'info')
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class = 'infoBtn'>initial</button>
<button class = 'infoBtn'>initial</button>

click anywhere except a specified class

I need to show an alert if there is a click anywhere except on .m1wrap div.
Why this doesn't work? Alert appears even if I click on .m1wrap
$(document).on("click", function(e) {
if (e.target.class !== "m1wrap") {
alert ("323");
};
})
In e.target there is no property class (it returns undefined), you can use property e.target.className (Note it returns all classes from class attribute), however in jQuery there is method .hasClass .
Also you can use classList with .contains method e.target.classList.contains('m1wrap')
$(document).on('click', function (e) {
if (!$(e.target).hasClass('m1wrap')) {
console.log('not m1wrap');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="m1wrap">m1wrap</div>
<p>test</p>
You need to use className to address the class attribute.
So either use jQuery's hasClass() or vanilla JS className.
Note: This example using className is only checking if the class does not equal "m1wrap", rather than does not contain "m1wrap".
$(document).on("click", function(e) {
if (e.target.className !== "m1wrap") {
alert ("323");
};
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="m0wrap">m0wrap</div>
<div class="m1wrap">m1wrap</div>
<div class="m2wrap">m2wrap</div>
There is no class in e.target, only className is available.
Code snippets:
$(document).on("click", function (e) {
if (e.target.className !== "m1wrap") {
alert("323");
};
})
But the following code snippets is the best way if there is multiple class names for an element.
$(document).on("click", function (e) {
if (!$(e.target).hasClass('m1wrap')) {
alert("323");
};
})
Event.target returns Element, which has not class property.
So you can use className property or getAttribute() method to get Element's class name.
If you want to use jQuery API, you can use hasClass() method
Try this,
<div>
<div class="m1wrap">
Non Clickable area
</div>
Clickable area
Clickable area
Clickable areaClickable areaClickable
Clickable areaClickable
Clickable area
</div>
JS
$(('body')).on('click',function(e) {
if ($(e.target).hasClass('m1wrap')) {
return false;
}
alert("hello");
})
DEMO

how to set to hide initially - javascript

I have this code that shows initially how do I change it to be hidden initially?
$(document).ready(function() {
$('#hideshow').click(function() {
var anchor_value = $('#hideshow').text();
if (anchor_value == 'Hide') {
$('#hideshow').text('Show');
$('#message').hide();
}
if (anchor_value == 'Show') {
$('#hideshow').text('Hide');
$('#message').show();
}
});
});
I suggest you to reconsider your code by:
first of all, look at the basics of js/jQuery
check the visibility of the detail element or use a class instead of check the text of it
use the built in jQuery method toggle to toggle the visibility
to initially hide an element use css a set up accordingly the page
Code:
$(document).ready(function () {
$('#hideshow').click(function () {
if ($("#message").is(":visible")) {
$('#hideshow').text('Show');
} else $('#hideshow').text('Hide');
$('#message').toggle();
})
});
Demo: http://jsfiddle.net/IrvinDominin/CFExY/

Change the OnClick event using Javascript

I have an HTML anchor tag like
<a href="anchorid" onclick="callEvent(1)">
Here I call the Javascript function like
<script>
function callEvent(anchor) {
alert("Anchor ID is - "+anchor);
document.getElementById("anchorid").onClick = function () { callEvent(0) }; // BY using this code, update the onclick callEvent(0), like toggle
}
</script>
I wants to update the anchor tag like
<a href="anchorid" onclick="callEvent(0)">
When using this code, it is not updating as per my requirement.
document.getElementById("anchorid").onClick = function () { callEvent(0) };
How do I get it to update?
for using document.getElementById("anchorid").. you need to have id in your element, which you currently dont have, try doing:
//add id to your anchor
<a href="javascript:void(0);" id="anchorid" onclick="return callEvent(1);">
test
</a>
and js
<script type="text/javascript">
function callEvent(num) {
alert("Anchor ID is - "+num);
document.getElementById('anchorid').onclick = function () { callEvent(0) };
}
</script>
Store the toggle value in tag itself and then use.
<script>
function callEvent(val) {
var val = document.getElementById("myId").getAttribute('data-val');
alert(val);
// toggle value
val = val==1?0:1;
document.getElementById("myId").setAttribute('data-val',val);
}
</script>
<a id="myId" data-val="0" onClick="callEvent()">Click</a>
here value is stored in data-val value so that is toggled in the callEvent function itself, so no need to rebind the event.
See Example fiddle
try:
document.getElementById("anchorid").onclick
Better:
document.getElementById("anchorid").addEvenetListener('click', function(){
});
Tested: http://jsfiddle.net/Yca5W/
document.getElementById("anchorid").onclick =
function () {
alert("clicked");
};
if you only change parameter of calling function then you dont have to change complete event. You can do it like this:
HTML
<a id="anchorid" href="#">click me !</a>
JS
<script>
var anchor = 1;
document.getElementById("anchorid").onclick = function(){
alert("Anchor ID is: " + anchor);
anchor = anchor == 1 ? 0 : 1; //toggle 0 and 1
}
<script>
try This:
var anchor= document.getElementById('anchorid');
anchor.addEventListener('click', function() {
callEvent(0);
});
OR
$( "#anchorid" ).click(function() {
callEvent(0);
});
if you only want changes passing parameter from 1 to 0 or vice verse then do this one:
<input type="hidden" name="para" id="para" value="1" >
<a href="anchorid" onclick="callEvent($('#para').val())">
$( "#anchorid" ).click(function() {
if ($('#para').val()==1) {
$('#para').val(0)
} else {
$('#para').val(1)
}
});
try this, it may solve your problem demo Fiddle
Add id="anchorid" to your anchor tag
When you click it next time it will callEvent by argument 0,
function callEvent(anchor) {
alert("Anchor ID is - "+anchor);
var ele = document.getElementById("anchorid");
ele.setAttribute("onclick","callEvent(0)");
}
It will update your link like you wanted
<a href="anchorid" id="anchorid" onclick="callEvent(0)">

Confused with calling JQuery custom function

I have html like so
<span rel='comm' val='12'>click</span>
<span rel='comm' val='82'>click</span>
and I am using JQuery to do this
$('span[rel*=comm]').cust();
and the custom function is as such
$.fn.cust = function () {
$(this).click(function(e) {
alert($(this).val());
});
}
The value of this is 12 even when I click on 2nd span which should give me 82
Any help would be appreciated.
You'll need to return a seperate function for each element in the collection, normally done with return this.each ...
$.fn.cust = function () {
return this.each(function() {
$(this).click(function(e){
alert($(this).val());
});
});
}
And value is not a valid attribute for a span element.
This should work better:
$.fn.cust = function () {
$(this).click(function (e) {
alert($(this).attr('val'));
});
}
span does not have value.
http://jsfiddle.net/dREj6/
Also if you want to make your method chainable you should return an jQuery instance:
$.fn.cust = function () {
return $(this).click(function (e) {
alert($(this).attr('val'));
});
}
$('span[rel*=comm]').cust().css('color', 'red');
http://jsfiddle.net/dREj6/1/
rel are for links (anchor element) - use class
use data attribute instead of custom attributes
http://jsbin.com/ogenev/1/edit
<span class='comm' data-val='12'>click</span>
<span class='comm' data-val='82'>click</span>
$.fn.cust = function(){
$(this).click(function(){
alert(this.dataset.val);
});
};
$('.comm').cust();
It works if you use .attr('val')
$.fn.cust = function () {
$(this).click(function(e){
alert($(this).attr('val'));
});
}
$('span[rel*=comm]').cust();
http://jsfiddle.net/fW7FT/
.val() is for input since they're the only one accepting the val attribute officialy
The call $('span[rel*=comm]') returns a JQuery wrapper for all spans matching the selector - the two ones you have in your example are picked both.
Now inside the definition of cust, $(this) refers to the wrapped array, which causes your issue. Use
$(this).each( function() {
$(this).click (...
});
Inisde each $(this) will point to each separate span element in the selection, so they will have the click handler individually attached and working as you expect.
You can achieve what you're looking for with this:
HTML:
<span rel='comm' val='12'>click</span>
<span rel='comm' val='82'>click</span>
JS:
var cust = function(source) {
alert($(source).attr('val'));
}
$('span[rel*=comm]').click(function(e) {
cust(this);
});
The JSFiddle working: http://jsfiddle.net/ejquB/

Categories