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;
Related
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
Someone knows how can I get all the radiobuttons inside a div? The div has a id as follows
<div id="quest{{ $groups }}" class="quest">
I'm using Laravel, therefore my idea is to get the values inside a div, and put in jQuery something like
var radios = $("input[type='radio'][id^='quest'"+groups+"]");
But this doesn´t work, so I want to know how to get all the radiobuttons inside a div an do a loop inside using .each I think.
I need to duplicate one group of questions and then be able to do a validation, but only works for the first group, the second group is not validated and I´ve checked the id value for each radiobutton and change to previousid_2, and the questionnaire is cloned. Also I want to know how can I reset the values when I clone the questionnaire, because if you have select YES NO YES NO, in the second group when you clone it, those results are selected and the disabled fields too.
You're actually asking for several things. Your code implies you have access to the current group in a variable called groups. so...
1) select all radio inputs within a div:
var div = $("div#quest"+groups);
var radiosBtns = div.find("input[type='radio']");
2) Loop over them, and do some work on each element:
var doSomeWork = function(i,radiobtn){
console.log('the value of radio button #' + i ' is ' + radiobtn.value);
};
$.each(radioBtns,doSomeWork);
3) Duplicate a group of radio buttons:
var fromgroup = $("div#quest"+groups);
var togroup = fromgroup.clone();
var insertionPoint = $('body');
var toGroupId = 'questXXX';
// set the ID so it can be targetted
togroup.prop('id',toGroupId);
// reset radio button values
togroup.find('input[type="radio"]').each(function(){
this.prop('checked',false);
});
togroup.appendTo(insertionPoint);
4) Run validation on a specific group
var validateGroup = function(elements){
// your validation logic goes here
var isValid = false;
$.each(function(){
console.log( this.name, this.value );
});
return isValid;
};
// run the validation on the newly inserted group
var targetElements = $("#"+toGroupId).find("input[type='radio']");
var groupIsValid = validateGroup( targetElements );
You can get all radio buttons and iterate on them like following
$("input[type='radio'][id^='quest']").each(function(){
// add your logic here
});
it's very simple using Id's
To get all the elements starting with "quest" you should use:
$("[id^=quest]")
To get those that end with "jander"
$("[id$=quest]")
and the complete answer is
var radios = $("input[type='radio'][id^='quest']");
the point is what if you want to wildcard class :( :(
$("[class^=quest]")
on a dom like
<pre>
<a class="btn quest primary">link</a>
<pre>
it won't work , thus you will need a more complex wildcard that you have to till me when you find it :D
the fact is you will not need it , whenever you need to get a list of element using classes just use a common class :D
hope i helped u well
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've got a simple application that requires a DIV to be clicked, and in turn it shows another DIV which needs to have its content updated.
There are around 40 items that will need to be clickable and show the correct label for each.
Here is what I need to happen...
User clicks a DIV (drag_me)
Information box DIV is then shown (flavour_box)
the default word 'Ingredients' is swapped out with the content from the "flavour_descrip" div
Also update the 'choc_flavour' div with the name of the ingredient (choc_label)
The data comes from a database, so I'm unable to set individual ID's.
I had a similar issue with draggable's, but that was fixed, and I've tried doign somethign similar to no avail.
Here is the clickable DIV (flavour_descrip is set as hidden in the CSS)
<li class="drag_me">
<div>
<img src="RASPBERRY.png" />
</div>
<div class="choc_label">
Raspberries
</div>
<div class="flavour_descrip">
Our description will appear here for the DB
</div>
</li>
Here is the HTML for the popup box...
<div id="flavour_box">
<p class"flavour_description">Ingredients</p>
<div class="flavour_add">Add To Mixing Bowl</div>
</div>
Here is the jQuery snippet for the click (i've commented out the code I had started to rejig, but essentially I need to change the draggable.find to something that will work!)
$(".drag_me").click(function () {
//var htmlString = ui.draggable.find('.choc_label').html();
//$('.choc2_flavour').text(htmlString);
// update the description of the item
//var htmlString = ui.draggable.find('.flavour_descrip').html();
//$('.flavour_description').text(htmlString);
// on click of jar make box pop
$("#flavour_box").toggleClass("visible");
});
Any ideas how I can achieve this?
Added extra question
Now I've had my problem resolved, I need to perform one more task.
Inside the div that gets the details passed using "this", I need to be able to pass one more items to a different piece of script.
The DIV 'flavour_add' is clickable and will need to grab the flavour name to use to update some bits on screen and update a URL on the fly.
<div id="flavour_box">
<p class="flavour_name_label">Label</p>
<p class="flavour_description">Ingredients</p>
<div class="flavour_add">Add To Mixing Bowl</div>
</div>
This is the jQuery I have, but using "this" doesn't seem to work
$(".flavour_add").click(function () {
// hide the ingredient box
$("#flavour_box").toggleClass("hidden");
// show the continue box
$("#added_box").toggleClass("visible");
// get the flavour name
var flavourLabel = $(this).find('.flavour_name_label').text();
// update flavour URL
var _href = $("a.to_step_3").attr("href");
$("a.to_step_3").attr("href", _href + '&flavour=' + flavourLabel);
//$("a.to_step_3").attr("href", _href + '&flavour=TestFromAdd');
// update the mixing bowl list with the ingredient
$('.choc2_flavour').text(flavourLabel);
});
Use $(this) to get the reference to the clicked element:
$(".drag_me").click(function () {
var txt = $(this).find('.choc_label').text();
$("#flavour_box > .flavour_descrip").text(txt);
$("#flavour_box").toggleClass("visible");
});
Besides, there was a "typo" in your html code, replace:
<p class"flavour_description">Ingredients</p>
By:
<p class="flavour_description">Ingredients</p>
You can easily achieve this using jQuery.
$(".drag_me").click(function () {
$('.flavour_description').text($('.flavour_descrip').html());
// on click of jar make box pop
$("#flavour_box").toggleClass("visible");
});
I cannot seem to be able to find the divs for step: 4. Also update the 'choc_flavour' div with the name of the ingredient (choc_label)
I will assume that you mean 'flavour_add' in which case the code should look like this:
$('.flavour_add').text($('.choc_label').html());
Try this:
$(document).ready(function() {
var $flavourBox = $('#flavour_box');
var $flavourDesc = $flavourBox.children('.flavour_description');
var $chocFlavour = $flavourBox.children('.choc_flavour');
$('.drag_me').on('click', function() {
var $this = $(this);
$flavourDesc.html($this.children('.flavour_descrip').html());
$chocFlavour.html($this.children('.choc_label').html());
$flavourBox.addClass('visible'); //toggleClass will remove the class if it is there
});
});
get the text by using "this" (the actual clicked element) and then get the child flavour_descrip div
$(".drag_me").click(function () {
$("#flavour_box").show();
$('.flavour_description').text($(this).find('.flavour_descrip').text());
});
then show the flavour_box div and set the value of the div with the flavour_description class
In the JSFiddle, I am trying to generate divs dynamically using javascript. Those divs will contain tables where the last two rows can be incremented using the add button.
I have tried the code in the fiddle.
The ins_row() function is used to add rows in the table which are generated within the divs.
The addEvent() function is used to generate divs
When the Add product button is clicked a div containing a table with one row will get generated.
When the add button is clicked the last two rows should keep on getting added as per the clicks. If the remove button straight to the div is clicked the whole table and div should be deleted.
When the remove button straight to the generated rows is clicked, only that row should be deleted and not the whole div.
Problem
The problem here is the divs with table are getting generated but I couldn't figure out how to add the rows in the table.
See it in action here
Expected output
Note: I have just pasted the external JS file into the javascript column of the above fiddle as I don't have the resource link.
Present output
I hope I have presented the question understandable, if anything is not clear, Please let me know
I believe I have properly understood your requirement.
Try out this fiddle http://jsfiddle.net/Kucuk/14/
It uses jquery though - its just a sample sort of thing that you could probably base your own code off. Its all doable in plain old JavaScript, if that's what you prefer. The styling is a bit off, but that you can handle I hope.
Do let me know if this helps you in some manner.
Generally, I use jQuery's appendTo() function alongwith a dummy html structure. I store this in a variable & follow it up with further attribute manipulation.
To get an idea of what I am talking about, just check this fiddle: http://jsfiddle.net/GGS4N/
This is in answer to another question Smooth out this jQuery toggle animation?. Focus on the methodology as listed below:
To create a dummy HTML structure(generic in nature).
On your desired event, triggering of population and manipulation of the dynamic elements into the dom, with giving them an identifiers and manipulating other specific attributes, and as seen in the fiddle, even animating them.
If you prefer raw JS, as seen from your code, you can implement the same functionality in raw JS too! :)
Try this fiddle to see if it works for you.
In this example, when you click on add product, all 4 textboxes are created with an add more rows and remove div buttons.
When you click on add rows, last two textboxes are created with a remove row button.
Whenever the row count of a product is more than 1, the remove div button is hidden and is shown again when the row count is 1.
Is this more like what you expected?
http://jsfiddle.net/7AeDQ/81/
I achieved this by adding styles to widen the table and the cell containing the buttons. I also changed the buttons to input type="button".
Hope this works for you.
EDIT:
I have just noticed that I mixed up your expected output and present output. Working on expected output now.
Another pure js solution
<html>
<body>
<script>
var tblCount = 0
var tblIdStr = "productTbl";
function removeRow(id, rowNumber) {
var el = document.getElementById(id);
el.deleteRow(rowNumber);
}
function addTable() {
++tblCount;
tblId = tblIdStr + tblCount;
var args = "'" + tblId + "'";
var tblHtml = '<tr><td>Product name</td><td>Price</td><td>Competitor</td><td>Price</td></tr><tr><td><input type="text"></td><td><input type="text"><td><input type="text"></td><td><input type="text"></td><td><input type="button" value="Add" onclick="addRow(' + args + ')"></td><td></td></tr>'
var tbl = document.createElement("table");
tbl.setAttribute("id", tblId);
document.getElementById("container").appendChild(tbl)
document.getElementById(tblId).innerHTML = tblHtml;
}
function addRow(id) {
var el = document.getElementById(id)
var rowCount = el.rows.length;
var row = el.insertRow(rowCount);
//console.log(row)
var args = "'" + id + "'" + "," + rowCount;
var tblRowHtml = '<td colspan=2></td><td><input type="text"></td><td><input type="text"></td><td><input type="button" value="remove" onclick="removeRow(' + args + ')"></td>';
//el.rows[rowCount].setAttribute("id", rowId);
el.rows[rowCount].innerHTML = tblRowHtml
}
</script>
<input type="button" value="Add new product table" onclick="addTable()">
<div id="container">
</div>
</body>
</html>