Javascript variable... can't reference - javascript

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

Related

Loop around HTML variable and replace spans with content

I have a variable that contains HTML.
var html = '<p><span id="variable:7" class="variable-source" title="variable:TEXT_CONTAINER">DATA</span> This is a variable</p>'+
'<p><span id="input:10.New Input 2" class="input-source" title="New Screen; New Input 2">DATA</span> This is a input source</p>'+
'<p>Testing</p>';
I am trying to loop around all of the elements and replace with spans specific date. So any spans with a class of variable-source will need to be replaced with specific date, and the same for input-source.
I have tried to use the following:
$('span', html).replaceWith(function () {
var id = $(this).attr('id');
// this returns the correct id
//calculations go here
var value = 'testing';
return value
});
Which outputs the following:
testing This is a variable
All of the paragraph tags have been removed, and it seems to stop after the first paragraph. Is there something that I am missing here? I can post more code or explain more if needed.
Thanks in advance.
You need to create a html object reference, else you won't get a reference to the updated content. Then get the update content from the created jQuery object after doing the replace operations
var html = '<p><span id="variable:7" class="variable-source" title="variable:TEXT_CONTAINER">DATA</span> This is a variable</p>' +
'<p><span id="input:10.New Input 2" class="input-source" title="New Screen; New Input 2">DATA</span> This is a input source</p>' +
'<p>Testing</p>';
var $html = $('<div></div>', {
html: html
});
$html.find('span.variable-source').replaceWith(function() {
var id = this.id;
// this returns the correct id
//calculations go here
var value = 'replaced variable for: ' + id;
return value
});
$html.find('span.input-source').replaceWith(function() {
var id = this.id;
// this returns the correct id
//calculations go here
var value = 'replaced input for: ' + id;
return value
});
var result = $html.html();
$('#result').text(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>

why wouldn't this selector work? JS

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

Fetch html of a tag by id with slash [duplicate]

In html code I am using code
<input type = "text" id = "abc#def.com"> to get text
now it need to get its value which is entered in text field. I am using jquery to do that:
$( document ).ready( function() {
$( ".bid" ).click( function() {
idVal = this.id
bidID = "#" + idVal + "bid"
spanID = "#" + idVal + "cbid"
bidValue = $(bidID).val();
alert(idVal)
alert(bidID)
alert(bidValue) //this alert says undefined
$( spanID ).html( ' ' ).load( '{% url online_machines %}?id=' + idVal + '&bidvalue=' + bidValue);
});
});
By doing this i get the value error undefined.
I tried to remove special characters from the id to get its value. But I need the id with special characters. How can
I get its value using jquery ?
Instead of trying for ID using #, try this to match attribute like this,
$('[id=ID]')
or
$('[id='+ID+']')
so instead of
bidID = "#" + idVal + "bid"
you can try
bidID = "[id=" + idVal + "bid]"
Try escaping it:
$('#abc\\#def.com').val();
First paragraph of http://api.jquery.com/category/selectors/
It looks like JQuery has a useful method for this as of version 3 called escapeSelector.
$('#' + $.escapeSelector(my_id_with_special_chars));
https://api.jquery.com/jQuery.escapeSelector/
$(document.getElementById('abc#def.com')) also works.
Use the function CSS.escape() to select that DOM element.
In your case for the id abc#def.com you can use the below code.
$("#" + CSS.escape('abc#def.com'));
Have a shot at this, not 100% on whether this is what you're after. Let me know:
$( document ).ready(function() {
$(".bid").click(function() {
idVal = $(this).attr('id');
bidID = "#" + idVal + "bid";
spanID = "#" + idVal + "cbid";
bidValue = bidID.val();
alert(idVal);
alert(bidID);
alert(bidValue);
spanID.html(' ').load('{% url online_machines %}?id=' + idVal + '&bidvalue=' + bidValue);
});
});
This solution below worked for me, it is pretty clean:
//your HTML id has special characters:
var option= "Some option with (parenthesis or # )";
//use this type of jquery query:
$(`[id="order_${option}"]`).prop('checked',true)

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]')

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