why is button toggle not working with class? - javascript

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>

Related

How to set on change as a default on page load jquery?

I have created a on change method for a select box of my project. On selecting particular option it is basically showing and hiding a div which is perfectly working fine. Now, my problem is when first time page is loading this show and hide not working for first default section of form. Can I make this onchange function also working when page load first time.
$('.contact-form').on('change', (e) => {
var selectedId = $(e.currentTarget).val();
var listofforms = $("#discount").data("display-for").split(",");
if (listofforms.indexOf(selectedId) !== -1) {
$("#discount").collapse('show');
}
else {
$("#discount").collapse('hide');
}
});
Here you go with a solution
function changeMethod(selectedId) {
var listofforms = $("#discount").data("display-for").split(",");
if (listofforms.indexOf(selectedId) !== -1) {
$("#discount").collapse('show');
}
else {
$("#discount").collapse('hide');
}
}
changeMethod($('.contact-form').val())
$('.contact-form').on('change', (e) => {
changeMethod($(e.currentTarget).val());
});
You need to move your code outside the change event, so I have kept your existing code within a method changeMethod.
Then call the method from to places
From you change event method
OnLoad of the JS file
Is it possible can I make my on change trigger on page load
Yes, you will just need to change your on change event from e.currentTarget to this as on page load e.currentTarget will be null, but this always points to the current element like:
$('.contact-form').on('change', function() {
var selectedId = $(this).val();
// Your other logic here
});
and to trigger this change event on page load, simply add .change() at last like:
$('.contact-form').on('change', function() {
var selectedId = $(this).val();
// Your other logic here
}).change(); //<---- here

Replace button text onclick JS

I'm trying to change button text on button click so that the text changes from 'Copy' to 'Copied!' as part of a custom clipboard setup. Here is the code I'm using:
HTML:
<button id="copyButton2">Copy</button>
JS:
<script>
jQuery(".copyButton2").click(function () {
jQuery(this).text(function(i, v){
return v === 'Copy' ? 'Copied!' : 'Copy'
})
});
</script>
which doesn't appear to be working correctly.
I have also tried modifying this solution to no avail. Is there an obvious reason why this isn't working?
You've set copyButton2 as the id of the element, yet you're using a class selector. You need to prefix the selector with #, not .
Also note that, depending on where you're running the jQuery code, you may also need to include a document.ready handler. Try this:
jQuery(function($) {
$("#copyButton2").click(function() {
$(this).text(function(i, v) {
return v === 'Copy' ? 'Copied!' : 'Copy'
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="copyButton2">Copy</button>
Please use id selector ("#copyButton2") instead of class selector as you have used id for the close button.
Here's a javascript solution while we're at it.
<script>
var testDiv = document.getElementById('test');
testDiv.onclick = function(){
testDiv.innerHTML = "Copied!"
};
</script>

Jquery: After removing content with a click how do I reset the button with the one I triggered the add function?

So I have this function where I add content on click to a "Favorites page", but when I click the button to remove it from the Favorites tab it removes the content but the button on the main page does not reset, the question is, how do I reset the button to it's original state after clicking the "Unfavorite" button?
https://jsfiddle.net/yjL7L6g7/3/
$(document).ready(function() {
$('button').click(function() {
if ($(this).html() == 'Favorite') {
var $favorited = $(this).parent().parent().parent().clone();
$(this).html('Favorited');
$favorited.find('button').html('Unfavorite');
$($favorited).click(function() {
$(this).remove();
});
$('#favorites').append($favorited);
}
});
});
And my second question related to this code is, how do I add a button to be on the same row with the content that is being added to the "Favorites"? I tried a simple .append(); but it did not suffice as the button got placed in a new row, will .css() suffice?
The questions might be stupid but I am still on my first steps in learning jquery
I'd avoid cloning if possible because there are simpler ways to do what you're trying to do. The code below will create a new button and add it to your favorites page. It will also attach an event to the Remove button to change the text of the Favorited button as well as remove itself after being clicked.
$(document).ready(function () {
$('button').click(function () {
if ($(this).html() == 'Favorite') {
var that = this;
$(this).html('Favorited');
var id = $(this).attr('id');
$('#favorites').append('<button id="' + id + 'Remove" class="ui-btn">Remove</button>');
$('#' + id + 'Remove').click(function () {
$(this).remove();
$(that).html('Favorite');
});
}
});
});
As for your second question, there is CSS that allows elements to live on the same line. For example, if you have two buttons that you want on the same line, it would look something like this:
<button style="display: inline;">Button1</button>
<button style="display: inline;">Button2</button>
Let me know if you have any questions.

How to update the value of data attribute using jquery

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);

How to hide a dom element after creating it on the fly with JQuery?

I am trying to build a form where users can add a text field by clicking on a "add option" button. They can also remove added fields by a "remove option" link created on the fly by Jquery, along with the text field.
JavaScript:
$(document).ready(function(){
$("#add_option").click(function()
{
var form = $("form");
var input_field = '<input type="text" />';
var delete_link = 'remove';
form.append(input_field + delete_link);
return false;
});
$("a").click(function()
{
alert('clicked');
return false;
});
});
When I click on the "add_option" button, a new text field and the "delete_link" appear. But when clicking on the "delete_link" created by JQuery, the browser follows the link instead of launching a pop-up displaying "clicked".
How do I hide a dom element after creating it on the fly with JQuery?
I'd use delegate because its uses less bubbling :
$(document).delegate("a", "click", function(){
alert('clicked');
});
EDIT , here is your code you need to change :
$(document).ready(function(){
$("#add_option").click(function(){
var form = $("form");
var input_field = '<input type="text" />';
input_field.addClass = "dynamic-texfield";
var delete_link = 'remove';
form.append(input_field + delete_link);
return false;
});
Then comes the delegate part :
$(document).delegate(".delete-trigger", "click", function(){
alert('ready to delete textfield with class' + $(".dynamic-texfield").attr("class"));
});
Try binding the handler for the <a> with "live"
$('a').live('click', function() { alert("clicked); });
You probably should qualify those <a> links with a class or something.
I don't get why you're using a <a> as a button to execute a function in jQuery. You have all the tools you need right in the framework to totally bypass well-worn traditions of HTML.
Just put a css cursor:pointer definition on the button you want to appear "clickable," add some text-decoration if that's your fancy, and then define your function with jQ:
$('.remove-button').live('click', function() {
$(this).parent().remove();
}

Categories