I have a button listener as follows:
$('body').on('click', '.showrecent', function() {
$('#display').toggle();
});
I have a json search(where I am appending a button):
var search = 0;
$.getJSON('data.json', function(data) {
if ((this.Name.toLowerCase()).indexOf(sr) > -1) {
id++;
//blah blah blah
var recent = "<button class = 'showrecent' onclick = 'showrecent(id)'>Recent Transaction</button>";
$('#founded').append(recent);
});
});
Basically, I want to pass id with showrecent function!
Any help is highly appreciated!
If you're wanting each one to have its own id in the function call, you need to concatenate.
var recent = "<button class = 'showrecent' onclick = 'showrecent(" + id + ")'>Recent Transaction</button>";
Another approach is to use jQuery to bind the handler.
id++;
var thisid = id;
$("<button>", {className:'showrecent',
text:" Recent Transaction",
click: function() {
showrecent(thisid);
}
}).appendTo('#founded');
var recent = "<button class='showrecent' onclick='showrecent(" + id + ")'>Recent Transaction</button>";
It is better if you do not use inline event handlers.
var recent = $("<button class ='showrecent'>Recent Transaction</button>");
recent.data("id",id);
recent.on("click",showrecent);
$('#founded').append(recent);
and the function
function showrecent() {
var btn = $(this);
var id = btn.data("id");
console.log(id);
}
If you want to do it the way you are doing it, build up the string.
var recent = "<button class = 'showrecent' onclick = 'showrecent(" + id + ")'>Recent Transaction</button>";
Related
I have this HTML:
<li class="sshjd839djjd blahclass"><a onclick="doSomething()">Blah Blah</a></li>
So when I click my link doSomething() is triggered and I want to grab sshjd839djjd. I have many links with different keys like this one which I need to grab correct data.
I don't know much about Javascript and jQuery but I need it to make admin panel which I would use to manage my data in Firebase, just to explain what I'm doing.
I tried to avoid onClick and use .click but that didn't work.
Can somebody help me a bit please?
So what should go in:
function doSomething() {
// grab class which is actually a child key from Firebase which I already implemented
// do Firebase magic, I will know this once I get that key
}
Keys/classes are added like this:
var resultVetRef = new Firebase("https://myappname.firebaseio.com/data/users");
resultVetRef.on("child_added", function(snapshot) {
var key = snapshot.key();
var data = snapshot.val();
var name = data.name;
var city = data.city;
$("#results").append($("<li class=\"" + key + " blahclass\">" + "<a onClick=\"grabVet()\">" + name + ", " + city + "</a></li>"));
});
add the key as data to the li
var resultVetRef = new Firebase("https://myappname.firebaseio.com/data/users");
resultVetRef.on("child_added", function(snapshot) {
var key = snapshot.key();
var data = snapshot.val();
var name = data.name;
var city = data.city;
$("#results").append($("<li class=\"" + key + " blahclass\" data-key=\""+ key +"\">" + "<a onClick=\"grabVet()\">" + name + ", " + city + "</a></li>"));
});
Then get it like:
<li class="sepcialKey blahclass" data-key="sepcialKey"><a>Blah Blah</a></li>
$('a').click(function(){
alert($(this).closest('li').data('key'));
});
Here is the Demo: https://jsfiddle.net/ffyLgg3s/
Specifically for your example
<li class="sshjd839djjd blahclass"><a>Blah Blah</a></li>
$('a').click(function(){
alert( $(this).closest('li')[0].classList.item(0) );
});
using classList and item method.
or if you want to use your own doSomething
<li class="sshjd839djjd blahclass"><a onclick="doSomething(this)">Blah Blah</a></li>
function doSomething(thisObj)
{
alert($(thisObj).closest("li")[0].classList.item(0));
}
ClassList method gives you an array with all classes of the element.
In your case it will return array ["specialKey", "blahclass"] for your <li> element.
function doSomething() {
// get the firs element of classList array and asign it to a variable
var specialKey = this.parentElement.classList[0]; // "this" keyword is the reference to clicked element, "parentElement" give you "li" element reference
// do Firebase magic, I will know this once I get that key
}
Or modify your append code:
var resultVetRef = new Firebase("https://myappname.firebaseio.com/data/users");
resultVetRef.on("child_added", function (snapshot) {
var key = snapshot.key();
var data = snapshot.val();
var name = data.name;
var city = data.city;
// create li element
var li = $("<li class=\"blahclass\"></li>");
// create a element
var a = $("<a>" + name + ", " + city + "</a>");
a.on("click", function () {
// when a clicked execute "doSomething" passing key as parameter
doSomething(key);
})
// append a to li
li.append(a);
//append li to #results
$("#results").append(li);
});
I am trying to get all span elements inside the form. The span elements are turning into input text fields and become editable. When you click away they are turning back into span elements. I will attached fiddle live example.
I gave it a go but the problem is that I am getting both ids but only value of the first span element.
Here is my html:
<span name="inputEditableTest" class="pztest" id="inputEditableTest" data-editable="">First Element</span>
<span name="inputEditableTest2" class="pztest" id="inputEditableTest2" data-editable="">Second Element</span>
<input id="test" type="submit" class="btn btn-primary" value="Submit">
And here is JavaScript with jQuery:
$('body').on('click', '[data-editable]', function () {
var $el = $(this);
var name = $($el).attr('name');
var value = $($el).text();
console.log(name);
var $input = $('<input name="' + name + '" id="' + name + '" value="' + value + '"/>').val($el.text());
$el.replaceWith($input);
var save = function () {
var $p = $('<span data-editable class="pztest" name="' + name + '" id="' + name + '" />').text($input.val());
$input.replaceWith($p);
};
$input.one('blur', save).focus();
});
$("#test").on('click', function(){
var ok = $("span")
.map(function () {
return this.id;
})
.get()
.join();
var ok2 = $("#" + ok).text();
alert(ok);
alert(ok2);
//return [ok, ok2];
});
Here is the fiddle https://jsfiddle.net/v427zbo1/3/
I would like to return the results as an array example:
{element id : element value}
How can I read ids and values only inside specific form so something like:
<form id = "editableForm">
<span id="test1">Need these details</span>
<span id="test2">Need these details</span>
<input type="submit">
</form>
<span id="test3">Don't need details of this span</span>
Lets say I have got more than 1 form on the page and I want JavaScript to detect which form has been submitted and grab values of these span elements inside the form
I will be grateful for any help
$("#test").on('click', function(){
var result = {};
$("span").each(function (k, v) {
result[v.id] = v.innerHTML;
});
alert(JSON.stringify(result));
//return [ok, ok2];
});
Here is an example: https://jsfiddle.net/v427zbo1/4/
Container issue:
You should use this selector: #editableForm span if you want to get all the divs inside this container.
$("#editableForm span").each(function (k, v) {
result[v.id] = v.innerHTML;
});
But if you want to get only first-level children elements then you should use this selector: #editableForm > span
Example with getting all the spans inside #editableForm container: https://jsfiddle.net/v427zbo1/9/
If you want to have several forms, then you can do like this:
$('form').on('submit', function(e){
e.preventDefault();
var result = {};
$(this).find('span').each(function (k, v) {
result[v.id] = v.innerHTML;
});
alert(JSON.stringify(result));
//return [ok, ok2];
});
Example with two forms: https://jsfiddle.net/v427zbo1/10/
You can't use .text to return the value of multiple elements. It doesn't matter how many elements are selected, .text will only return the value of the first one.
Virtually all jQuery methods that return a value behave this way.
If you want to get an array of values for an array of matched elements, you need another map. You also need to join the strings with , # as you're producing something along the lines of #id1id2id3 instead of #id1, #id2, #id3:
var ok = $("span").map(function () {
return this.id;
}).join(', #')
var ok2 = $("#" + ok).map(function () {
return $(this).text();
});
That said, you're already selecting the right set of elements in your first map. You pass over each element to get its ID, you already have the element. There is no reason to throw it away and reselect the same thing by its ID.
If I got you right following code will do the job
var ok = $("span")
.map(function () {
return {id: $(this).attr('id') , value: $(this).text()};
}).get();
Check this fiddle.
I wish to pass 'selectlang' parameter in javascript and redirect to the MVC controller but the var 'selectlang' have error and mention that it does not exist in current content? Please guide me thanks!
My javascript:
$('.filterlang').on("click", function () {
var selectlang = document.getElementById("Language").value;
location.href = '#Url.Content("~/SURV_Main/SURV_Main_Details/?key=" + Model.Survey_Key +"&Language=" + selectlang)';
});
filterlang is button class and "Language" is dropdownlist id.
Have you tried this:
$(document).on(".filterLang", "click", function(){
var selectedLang = $("#Language").val(); // if it is normal dropdown, this will work for both cases
var selected2Lang = $("#Language").select2("val"); // if it is select2 dropdown
window.location = '#Url.Content("~/SURV_Main/SURV_Main_Details/?key=" + Model.Survey_Key +"&Language=' + selectlang + '")';
});
Hope this helps.
I have 4 <div> tag and <a> tag for each <div> tags.
In each and every div tag i have inserted 2 span tag and a a tag.
When the a tag is clicked i need to get the product name and the price of that div
Here is the demo http://jsfiddle.net/8VCWU/
I get the below warning message when i use the codes in the answer ...
Try this:
$(".get").click(function(e) {
e.preventDefault();
var $parent = $(this).closest(".item");
var itemName = $(".postname", $parent).text();
var itemPrice = $(".price", $parent).text();
alert(itemName + " / " + itemPrice);
});
Example fiddle
Note that you had a lot of repeated id attributes which is invalid code and will cause you problems. I've converted the #item elements and their children to use classes instead.
jQuery
$(".get").click(function(event){
event.preventDefault(); /*To Prevent the anchors to take the browser to a new URL */
var item = $(this).parent().find('#postname').text();
var price = $(this).parent().find('#price').text();
var result = item + " " + price;
alert(result)
});
DEMO
A Quick Note about id:
The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).
A unique identifier so that you can identify the element with. You can use this as a parameter to getElementById() and other DOM functions and to reference the element in style sheets.
solution is below
use the blow code and try it
<a data-role="link" href="javascript:linkHandler('<%= obj.productname %>', '<%= obj.price %>')" class="get" >Add <a>
function linkHandler(name, price)
{
alert(name);
alert(price);
var name = name;
var price = price;
var cartItem = new item(name, parseFloat(price));
// check duplicate
var match = ko.utils.arrayFirst(viewModel.cartItems(), function(item){ return item.name == name; });
if(match){
match.qty(match.qty() + 1);
} else {
viewModel.cartItems.push(cartItem);
var rowCount = document.getElementById("cartcontent1").getElementsByTagName("TR").length;
document.getElementById("Totala").innerHTML = rowCount;
}
}
with jQuery
$('a.get').on('click',function(){
var parent = $(this).parent();
var name = $(parent+' #postname').text();
var price = $(parent+' #price').text();
});
Or again:
$('a').click(function(e){
e.preventDefault();
var $price = $(this).siblings('#price').text();
var $postname = $(this).siblings('#postname').text();
alert($price);
alert($postname);
});
Try
function getPrice(currentClickObject)
{
var priceSpan = $(currentClickObject).parent("div:first").children("#price");
alert($(priceSpan).html());
}
and add to your a tag:
...
I'd suggest to use classed instead of id if you have more than one in your code.
The function you're looking for is siblings() http://api.jquery.com/siblings/
Here's your updated fiddle:
http://jsfiddle.net/8VCWU/14/
Hi I cleaned up the HTML as mentioned using the same Id more than once is a problem.
Using jQuery and the markup I provided the solution is trivial.
Make a note of the CSS on the below fiddle
http://jsfiddle.net/8VCWU/27/
$(document).ready(function(){
$("#itmLst a.get").click(function(){
var $lstItm = $(this).parents("li:first");
var pName = $lstItm.find("span.postname").html();
var price = $lstItm.find("span.price").html();
alert("Product Name: " + pName + " ; Price: " + price);
});
});
I have made some changes in your html tags and replace all repeated Ids with class, because you have repeated many ids in your html and it causes trouble so it is wrong structure. In HTML, you have to give unique id to each and every tag. it will not be conflicted with any other tag.
Here i have done complete bins demo. i have also specified all alternative ways to find tag content using proper jQuery selector. the demo link is as below:
Demo: http://codebins.com/bin/4ldqp8v
jQuery
$(function() {
$("a.get").click(function() {
var itemName = $(this).parent().find(".postname").text().trim();
var itemPrice = $(this).parent().find(".price").text().trim();
//OR another Alternate
// var itemName=$(this).parents(".item").find(".postname").text().trim();
// var itemPrice=$(this).parents(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).closest(".item").find(".postname").text().trim();
// var itemPrice=$(this).closest(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).siblings(".postname").text().trim();
//var itemPrice=$(this).siblings(".price").text().trim();
alert(itemName + " / " + itemPrice);
});
});
Demo: http://codebins.com/bin/4ldqp8v
You can check above all alternatives by un-commenting one by one. all are working fine.
as the title says, I keep getting "undefined" when I try to get the id attribute of an element, basically what I want to do is replace an element with an input box when the value is "other".
Here is the code:
function showHideOther(obj) {
var sel = obj.options[obj.selectedIndex].value;
var ID = $(this).attr("id");
alert(ID);
if (sel == 'other') {
$(this).html("<input type='text' name='" + ID + "' id='" + ID + "' />");
} else {
$(this).css({
'display': 'none'
});
}
}
The HTML:
<span class='left'><label for='race'>Race: </label></span>
<span class='right'><select name='race' id='race' onchange='showHideOther(this);'>
<option>Select one</option>
<option>one</option>
<option>two</option>
<option>three</option>
<option value="other">Other</option>
</select>
</span>
It is probably something small that I am not noticing, what am I doing wrong?
Change
var ID = $(this).attr("id");
to
var ID = $(obj).attr("id");
Also you can change it to use jQuery event handler:
$('#race').change(function() {
var select = $(this);
var id = select.attr('id');
if(select.val() == 'other') {
select.replaceWith("<input type='text' name='" + id + "' id='" + id + "' />");
} else {
select.hide();
}
});
your using this in a function, when you should be using the parameter.
You only use $(this) in callbacks... from selections like
$('a').click(function() {
alert($(this).href);
})
In closing, the proper way (using your code example) would be to do this
obj.attr('id');
Because of the way the function is called (i.e. as a simple call to a function variable), this is the global object (for which window is an alias in browsers). Use the obj parameter instead.
Also, creating a jQuery object and the using its attr() method for obtaining an element ID is inefficient and unnecessary. Just use the element's id property, which works in all browsers.
function showHideOther(obj){
var sel = obj.options[obj.selectedIndex].value;
var ID = obj.id;
if (sel == 'other') {
$(obj).html("<input type='text' name='" + ID + "' id='" + ID + "' />");
} else {
$(obj).css({'display' : 'none'});
}
}
You could also write your entire function as a jQuery extension, so you could do something along the lines of `$('#element').showHideOther();
(function($) {
$.extend($.fn, {
showHideOther: function() {
$.each(this, function() {
var Id = $(this).attr('id');
alert(Id);
...
return this;
});
}
});
})(jQuery);
Not that it answers your question... Just food for thought.
What are you expecting $(this) to refer to?
Do you mean sel.attr("id"); perhaps?
Remove the inline event handler and do it completly unobtrusive, like
$('#race').bind('change', function(){
var $this = $(this),
id = $this[0].id;
if(/^other$/.test($(this).val())){
$this.replaceWith($('<input/>', {
type: 'text',
name: id,
id: id
}));
}
});
I had a similar issue.
`var ID = $(this).attr("id");`
sometimes using this method with arrow function (`
$('div).click(()=>{
console.log($(this).attr("id"))
}
`)
)Could result in undefined output so instead better using the keyword 'function'
In the function context "this" its not referring to the select element, but to the page itself
Change var ID = $(this).attr("id");
to var ID = $(obj).attr("id");
If obj is already a jQuery Object, just remove the $() around it.
I recommend you to read more about the this keyword.
You cannot expect "this" to select the "select" tag in this case.
What you want to do in this case is use obj.id to get the id of select tag.
You can do
onchange='showHideOther.call(this);'
instead of
onchange='showHideOther(this);'
But then you also need to replace obj with this in the function.