Building a similar setup to Twitters Follow/Unfollow button and can't quite get it working with jQuery.
Complete so far;
- jQuery on a single known ID for a <button> for updating all the details needed
- API powering the server side logic
- Everything else server side is working perfectly
Can't figure out;
- How to expand the functionality I have for a single known ID to multiple unknown IDs.
Here's the code I have working for the known single point;
//Update Links
$("#api-follow-button").html(buttonText);
$("#api-follow-button").attr("currentState", currentState);
The above code is wrapped in a function with a whole host of other code which is triggered by;
$(document).on("click", "#api-follow-button", followButton());
This works perfect as I know the ID. The challenge being, how to expand this when the ID that is to be updated is unknown?
I've tested so many variations using $(this) and I'm not getting anything working. I'm sure I'm just missing something blindingly obvious here.
So imagine this code as an example;
<button id="button-idxxx">Text 1</button>
<button id="button-idxxx">Text 2</button>
<button id="button-idxxx">Text 3</button>
Then whenever someone clicks on one of the <button>, then the 'Text X' would change to something else
Ideas?
This $(this) you mention probably works correct (although you did not post your relevant code).
The error seems to be in $(document).on("click", "#api-follow-button", followButton()); where the () should be missing from the followButton method.
So try with
$(document).on('click', '[id^="button-id"]', followButton);
(the [id^="button-id"] selector matches elements with an id attribute that starts with button-id text)
Your followButton should be something like this
function followButton(e){
e.preventDefault();
// define buttonText and currentState here
// unless they come from elsewhere
$(this)
.html(buttonText)
.attr("currentState", currentState);
}
(Thinking out loud) You could potentially use the Attribute Starts With Selector found in the linked article. With this selector, you can select all the buttons that may contain a specific prefix (i.e. button-id) from your example without knowing the entire id of the element.
From the attribute starts-with selector docs:
Description: Selects elements that have the specified attribute with a value beginning exactly with a given string.
For example:
jQuery(function ($) {
$(document).on('click', '[id^="button-id"]', function () {
alert($(this).text());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="button-id12345">
Text 1
</button>
<button type="button" id="button-id678910">
Text 2
</button>
<button type="button" id="button-id1112131415">
Text 3
</button>
Thanks all. The code in the fiddle for alert($(this).text()); works perfectly but when doing anything like updating the text on the page this didn't seem to work for some reason. With a bit of fiddling around based on the helpful info here's what I came up with which worked;
HTML Buttons
<button type="button" class="btn btn-lg btn-success" id="api-follow-button-uniqueID-xxx" currentState="NotFollowing">
<button type="button" class="btn btn-lg btn-success" id="api-follow-button-uniqueID-xxx" currentState="NotFollowing">
<button type="button" class="btn btn-lg btn-success" id="api-follow-button-uniqueID-xxx" currentState="NotFollowing">
jQuery Code
$(document).ready(function () {
$(document).on('click', '[id^="api-follow-button"]', function followButton(e) {
e.preventDefault();
var currentState = $(this).attr("currentState");
//This line below ensures that you can then use the ID selector to update the relevant part of the HTML as needed, see note below
var buttonID = $(this).attr("id");
var buttonText = "";
var currentState = "";
buttonText = "Unfollow";
currentState = "Following";
//Update Links
//This part from comment above
$("button[id=" + buttonID + "]")
.html(buttonText)
.attr("currentState", currentState);
});
}
});
});
Looks like it's all done what is needed now. I've removed a bunch of code from above to simplify things
Thanks all
Related
I am trying to remove a 'Pending' label and want to add a new 'Done' label.
Please find below the code I have written so far. This code works but the Pending label is now along side the Done label. I thought the former can be removed.
$(document).on('click','.pending', function() {
var li_node = $(this).parent();
li_node.append('<span class="label success">Done!</span>');
li_node.remove('<span class="label pending">Pending</span>');
li_node.addClass('completed');
});
Screenshots of my work. Can I get rid of the Pending label and leave only the Done label?
This is the html code: I am following an online tutorial that seems to have been designed for you to have a seasoned JS coach with you;
<div id="container">
<h1>Wish List</h1>
<ol id="items">
<!-- Items will be added here -->
</ol>
<span class="total"></span>
<br/>
<input type="text" id="item"/>
<button id="add-to-list">Add to list</button>
</div>
Something tells me I should be starting a new topic for the addition to this question but that would mean duplicating all the previous code...let me know if I am breaking the rules please.
I don't have an idea how to write a jQuery selector that selects all the pending labels, using the .length property, in the JavaScript console. I am using all the previous codes and this is the screenshot of the list on my browser that I am working with. I need to get the number of pending labels and number of completed labels.
$(document).on('click','.pending', function() {
var li_node = $(this).parent();
li_node.append('<span class="label success">Done!</span>');
li_node.children(".label.pending").remove();
li_node.addClass('completed');
});
Instead of adding and removing things, just change the class and text of the label in place:
$(document).on('click','.pending', function() {
var li_node = $(this).parent();
li_node.children('.label.pending').removeClass("pending").addClass("success").text("Done!");
li_node.addClass('completed');
});
Here is a working solution, I use a $ before the variable
name when it is a jQuery object. If you remove the item after
you get the selector for its parent element. then call remove on $(this) it works.
$(document).on('click', '.pending', function () {
var $li_node = $(this).closest('li');
$(this).remove();
$li_node.append('<span class="label success">Done!</span>').addClass('completed');
});
I am attempting to create a simple math quiz application for a child with on screen number keys that will append to an input field for the answer. I want to use jQuery event listener linked to a class so I do not have to call an onClick function for each number. I found this question elsewhere but I am unable to comment to further ask issue I am having as I have just joined stacked overflow and it states my reputation isn't high enough.
Link to other question: append value to an input field in JQuery
When I attempt to append I get an undefined when I attempt to click my buttons and I cannot see where the error in my code is. Any assistance would be greatly appreciated.
My jQuery:
$(".userIn").click(function() {
var usrIn = $(this).data('usrIn');
$("#answer").val(function() {
return this.value + usrIn;
});
});
Sample of my buttons:
<button type="button" class="btn btn-primary btn-block userIn" data-number="0" id="zero">0</button>
Here is the JSfiddle with all my linked style sheets and external js.
Change var usrIn = $(this).data('usrIn'); to var usrIn = $(this).attr('data-number');
Fiddle: https://jsfiddle.net/969r1gp0/4/
Your data attribute is called data-number, not data-userin, so you should write:
var usrIn = $(this).data('number')
But as the text of the buttons really is what you want to add, you could do without the data attributes all together, and just do:
var usrIn = $(this).text();
try this both, it's working
document.getElementById("input_id").value = you_value;
document.getElementById("input_id").textContent = you_value;
very new to coding here, apologies for the basic question. trying to complete the odin project's build-a-calculator challenge (http://www.theodinproject.com/javascript-and-jquery/on-screen-calculator)
and struggling to make numbers appear after they are clicked. Also, how would I store the value in a variable or array to then be used in a calculation later?
Here's the excerpt of my JS:
$(".numbers").on("click", function() {
$+(this).text()
;});
And my HTML (note I'm using jsfiddle, hence the lack of html opening and closing tags etc:
<script src="jquery-1.11.3.min.js"></script>
<div class="numbers">
<button type="button">0</button>
<button type="button">1</button>
<button type="button">2</button>
<button type="button">3</button>
<button type="button">4</button>
<button type="button">5</button>
<button type="button">6</button>
<button type="button">7</button>
<button type="button">8</button>
<button type="button">9</button>
</div>
<div class = "operators">
<button type="button">+</button>
<button type="button">-</button>
<button type="button">*</button>
<button type="button">/</button>
<button type="button">=</button>
<button type="button">clear</button>
</div>
To store the value of the buttons in a variable you could do this.
$('button').on('click', function(){
var i = $(this).text();
console.log(i); // print the value of i in the console
});
Once you have the value you'll need to be able to put the value of each button clicked in order on the "display" of the calculator like so.
HTML
<div class="display"></div>
JavaScript
$('button').on('click', function(){
var i = $(this).text();
var display = $('.display');
display.text( display.text() + i );
});
Hopefully that helps point you in the right direction.
I am not sure how you want to display your numbers. Are you using a TextArea?
For storing values, inside your function do something like
var num=$+(this).text()
Other than that, you need to be more specific.
The following jsfiddle demonstrated how to do what you want.
// array is defined outside the click handler
var clickedArray = [];
$('button').on('click',function() {
// get the button that was clicked
var buttonClicked = $(this).html();
console.log(buttonClicked);
// store it as the last element in the array
clickedArray.push(buttonClicked);
console.log(clickedArray);
// and output it to the screen
$('.js-calc-out').append(buttonClicked);
});
Points to note:
The array is defined outside the click event handler so it can be used without being reset each time a click event is fired. This array will exist until the page is refreshed or it is purposely unset and you can access it as you need it.
The html() function retrieves the contents of any given HTML element, in this case it's the clicked button, which is retrieved using $(this) (any element an event is fired on is retrieved using this which is then converted to a jquery object using the $() function).
The push() function is used to append the latest clicked element to the end of the array mentioned in point 1.
.js-calc-out is an HTML element to which we append() the latest click to, meaning the sequence of clicks are output.
The console.log declarations output some stuff into the inspector which should help you see the process develop.
PS. this is a simplified solution that takes into account your current position on the learning curve; ideally you'd want to use objects to encapsulate data and functionality in javascript and keep out of the global namespace.
I am trying to to retrieve the full DOM structure when only a button element(which is obviously part of the DOM) is available?
$(this) = <button class="btn" id="addBtn" data-toggle="modal" data-target="#addModal"><span class="add"></span> Add...</button>
Thanks
$("html").bind("DOMSubtreeModified", function()
{
// when a change is made in the DOM, this gets fired
if($('#idOfYOurElement')!==undefined)
{
var oEntireDom = $('html').html(); // if you want the content in html
});
$("html").html();
Will give you the full DOM
OK I have THREE count them (3) things I want to toggle using a Javascript or Jquery using bootstrap.
Fiddle not working CAN SOMEONE TELL ME WHY I got it to work locally and online.
JavaScript does work here in this example
Javascript
function toggleLink(obj)
{
var idCount = obj.id;
idCount = idCount.replace( new RegExp('cont', 'g'), '');
var elem = document.getElementById("show"+idCount);
var hide = window.getComputedStyle(elem, null).display =="none";
if (hide) {
elem.style.display="block";
}
else {
elem.style.display="none";
}
}
Simple CSS
[id^="show"] {
display: none;
}
HTML
<button class="btn btn-primary" id="cont1" href="javascript:void(0)"
onclick="toggleLink(this)">More </button><P><P>
<div id="show1">
CONTENT AREA #1</div><P><P>
<button class="btn btn-default" id="cont2" href="javascript:void(0)"
onclick="toggleLink(this)">More </button><P>
<div id="show2">
CONTENT AREA #2<p></div>
So what this does now is toggle the visibility of the DIV beginning with "show(i)" from any button or link with the beginning "cont(i)"
I want the following 3 things to toggle:
Toggle the content
Change the label or Text of the button from "More" to "Less"
Assign a different bootstrap button theme (default, primary, whatever)
Got a start any help much appreciated. TIA.
I hope you don't botter to use jquery, because I made a sample using it, take a look
The main piece that you need to pay attention is the follow code that are inside the toggleLink() function:
if($(obj).text()==='More'){
$(obj).text("Less");
$(obj).attr("class","btn btn-primary");
}else{
$(obj).text("More");
$(obj).attr("class","btn btn-default");
}
I'm using two functions of jquery:
text(): Used to change the text inside a html element, this only put text no more;
attr(): Change any attribute of an html element;
I hope this help you!