why wouldn't this selector work? JS - javascript

I have a class name active
and in js I have something like this
var selectClass = active;
var a = $("'." + selectCLass + "'");
a.on('click', function(){})
When I do this, it would keep on giving me errors.
What am I missing here?

Generated selector string has errors... make it like
var a = $("." + selectCLass);

Related

Javascript variable... can't reference

Could someone tells me why this reference doesn't work?
var a_nav_href = $(this).attr("data-id"); //get the id data when click in a tag**strong text**
$(".wrapper").find("section[id=a_nav_href]").css({"background-color": "red"});
You have written:
var a_nav_href = $(this).attr("data-id");
$(".wrapper").find("section[id=a_nav_href]").css({"background-color": "red"});
In this code snippet "a_nav_href" is part of selector but as a string. You need to append the value of a_nav_href tot he selector.
Replace it with
$(".wrapper").find("section[id=" + a_nav_href + "]").css({"background-color": "red"});
This will return a selector query looking like this
$(".wrapper").find("section[id=someIDWhichIWantToSearch]").css({"background-color": "red"});
Your code looks for id=a_nav_href
You want:
$(".wrapper").find("section[id=" + a_nav_href + "]").css({"background-color": "red"});

Javascript url content with parameter?

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.

How to select an item by attribute without jquery?

I need select element like this: $('[data-key=' + objectId + ']'), but i need select this without jquery, using document.querySelector or something else on pure JS.
You can do it with document.querySelectorAll('[data-key=' + objectId + ']') and loop through all results
var allKeys = document.querySelectorAll('[data-key=' + objectId + ']');
[].forEach.call(allKeys, function(elem){
console.log(elem); //Do your stuff with each element
});
You can try this
<p data-test="testquery">
document.querySelectorAll('[data-test]')

Dynamic selector

I am trying to do this:
var divString = '#sContainer' + [index];
$(divString).append(SSDisplay);
So that it is
var divString = '#sContainer' + [index];
$('#sContainer0').append(SSDisplay);
$('#sContainer1').append(SSDisplay);
$('#sContainer2').append(SSDisplay);
It doesn't seem to be working. I have also tried
$('#sContainer' + [index]).append(SSDisplay);
Any idea how I can get the jquery selector to do this dynamically?
You are repeatedly appending the same SSDisplay.
Try:
$('#sContainer' + index).append( SSDisplay.clone(true) );

Javascript to get the div info

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.

Categories

Resources