Get Attribute of Dynamic string - javascript

I have this container:
<Div id="ListContainer">
I append these data to it :
' <a class="lesson" subjectID="'+sbj_ID+'"><b>
<span class="lesson_subject">' + sbj_Name + '</span></b></a> ';
I want to put the value of sbj_ID & sbj_Name in a variable.
localStorage['SubjectID']= "value of sbj_ID";
localStorage['SubjectName']="value of sbj_Name";
But I can't access them.
I tried :
$('#ListContainer').find('.lesson').attr('subjectID')
$('#ListContainer .lesson').children[0].getAttribute('SubjectID')
$('#ListContainer .lesson').children[2].innerHTML;
But they didn't work.

I don't know how you are appending the string, but the following is a working example:
var sbj_ID = 3;
var sbj_Name = "test";
var str = '<a class="lesson" subjectID="'+sbj_ID+'"><b><span class="lesson_subject">' + sbj_Name + '</span></b></a>';
$("#ListContainer").append(str);
alert($('#ListContainer').find('.lesson').attr('subjectID'));
-- See Demo --
I'm also not sure how LocalStorage is being used, but you should set the variables as the value, not the strings you have used:
localStorage['SubjectID']= sbj_ID;
localStorage['SubjectName']= sbj_Name;

Try this
localStorage['SubjectID']= $('.lesson').attr('subjectID');
localStorage['SubjectName']=$('.lesson_subject').text();
or
localStorage['SubjectName']=$('.lesson_subject').html();

This should work
localStorage['SubjectID'] = $('.lesson').attr('subjectID');
localStorage['SubjectName'] = $('.lesson_subject').text();

Related

Sanitizing input to stick into a hidden input value with jQuery

Maybe I am confusing this a bit, but I have a piece of code that works like the following:
$("#myButton").on('click', function(){
var myValue = $('#myInput').val();
listSize++;
var listItem = "<li>" + myValue + "<input type='hidden' name='foo" +
listSize + "' value='" + myValue + "' /></li>";
$("ol.myList").append(listItem);
});
If the text input value contains for example, a ', then this code breaks in terms of correctly adding the hidden input value.
I was thinking that using encodeURIComponent would do the trick, but it does not.
What's the proper way to handle this?
Instead of doing this with html strings, create an actual element and set it's value property using val().
You can sanitize any possible html out of it by first inserting the string into a content element as text and retrieving it as text.
Note that the value property does not get rendered in the html the same as value attribute does so quotes are not an issue
$("#myButton").on('click', function(){
// sanitize any html in the existing input
var myValue = $('<div>', {text:$('#myInput').val())).text();
listSize++;
// create new elements
var $listItem = $("<li>",{text: myValue});
// set value of input after creating the element
var $input = $('<input>',{ type:'hidden', name:'foo'+listSize}).val(myValue);
//append input to list item
$listItem.append($input);
// append in dom
$("ol.myList").append($listItem);
});
I think this is what you are looking for:
$("#myButton").on('click', function(){
var myValue = $('#myInput').val();
listSize++;
var listItemHTML = "<li>" + myValue + "<input type='hidden' name='foo'></li>";
$(listItemHTML).appendTo('ol.myList').find('input[type=hidden]').val(myValue);
});
The appendTo function returns a reference to the just appended element.
Calling the val() function on the element will render the inserting of a quote useless since it will be interpreted as an actual value.
Safest way would be to write a wrapper
function addslashes (str) {
return (str + '')
.replace(/[\\"']/g, '\\$&')
.replace(/\u0000/g, '\\0')
}
var test= "Mr. Jone's car";
console.log(addslashes(test));
//"Mr. Jone\'s car"

Get Elements By Partial Attribute Value

I've been fiddling with this for several hours and I'm utterly stumped by its behavior. On JSFiddle, it seems to only be returning the values of the href attribute when I want the entire elements, but I can still use getAttribute(attribute) as if it's an element. In the userscript that this is for, it seems to completely break everything after calling the function(hence turning to JSFiddle and having no result to show here).
Why is this happening? How can I accomplish the stated goal?
HTML:
<a name="edit-a" href="http://example.com/edit1">foo</a>
<a name="moo" href="http://example.com/edit2">roo</a>
<a name="edit-b" href="http://example.com/boo">bar</a>
JavaScript function:
function getElementsByPartialValue(searchtext, searchattr, searchtag)
{
var searchreturn = [];
var searchreturni = 0;
var tagmatches = document.getElementsByTagName(searchtag);
for (var tagmatchesi = 0; tagmatchesi < document.getElementsByTagName(searchtag).length; tagmatchesi++)
{
if (tagmatches[tagmatchesi].getAttribute(searchattr).indexOf(searchtext) > -1)
{
searchreturn[searchreturni] = tagmatches[tagmatchesi];
searchreturni++;
}
}
return searchreturn;
}
Checking the result:
alert(getElementsByPartialValue('edit', 'name', 'a')[0]);
Result(https://jsfiddle.net/81s4g42a/3/):
http://example.com/edit1
Accessing other attributes(https://jsfiddle.net/81s4g42a/4/):
alert(getElementsByPartialValue('edit', 'name', 'a')[0].getAttribute('name'));
Result:
edit-a
Use Attribute-Contains Selector like this:
var tagmatches = document.querySelectorAll(searchtag + "[" + searchattr + " *= '" + searchtext + "']");
function getElementsByPartialValue(searchtext, searchattr, searchtag)
{
return document.querySelectorAll(searchtag + "[" + searchattr + " *= '" + searchtext + "']");
}
var elems = getElementsByPartialValue("edit", "name", "a");
for(var i = 0; i < elems.length; i++) {
elems[i].style.background = "red";
}
<a name="edit-a" href="http://example.com/edit1">foo</a>
<a name="moo" href="http://example.com/edit2">roo</a>
<a name="edit-b" href="http://example.com/boo">bar</a>
Use .querySelectorAll(), attribute is equal to or begins with followed by "-" selector
var tagMatches = document.querySelectorAll("a[name|='edit']");
console.log(tagMatches);
<a name="edit-a" href="http://example.com/edit1">foo</a>
<a name="moo" href="http://example.com/edit2">roo</a>
<a name="edit-b" href="http://example.com/boo">bar</a>
I hate to say this, but it's returning "name", not "href", if you want the url you should return the "href", not the "name"... Check your script and you'll find that you've set the name of the first tag to "edit-a", so when alerting the name of [0] you get "edit-a". If you access [1] you get "edit-b", and if you use 1 instead of 'name' you get "http://example.com/boo", and it's skipping the second one with "moo" as a name because you're only searching for ones with "edit" in its name, not its href/url.
alert(getElementsByPartialValue('edit', 'name', 'a')[0].getAttribute('href'));
I tested your code sample and find out, your code execute perfectly well. The problem is from the "alert()" function, try using console log, you will see that your code actually works.

How to add an attribute dynamically using javascript

I want to get an element using id:
var a = document.getElementById("hello");
and then dynamically add an attribute to it called "labelText" and assign the value "{labeltext}" to it.
do i need to use concatenation?
i tried the following but it didn't work:
document.getElementById("hello").setAttribute("labelText", "'{' + labelText + '}' ");
What you are doing basically works, with the syntax errors first explicitly identified by Vohuman corrected.
//Assign the Attribute:
var labelText='Some Value';
document.getElementById("hello").setAttribute('labelText', '{' + labelText + '}' );
//Define some variables for getting the results
var attributeEl = document.getElementById("attribute");
var theHTMLEl = document.getElementById("theHTML");
///Get the attribute value
var textLabelValue = document.getElementById("hello").getAttribute('labelText');
//Show the results:
attributeEl.textContent = textLabelValue;
theHTMLEl.textContent = document.getElementById("hello").outerHTML;
<div id="hello"></div>
The labelText attribute is:
<div id="attribute"></div>
The resulting HTML is:
<div id="theHTML"></div>

Need to display javascript variable as title without space

I have a written a javascript which will return the value in the variable, in the title property.
It is not returning the values with spaces, when i execute the below code it is returning the last value as 'ashok' instead of 'ashok sensiple'
var ltenantName = 'Sensiple,new-tenant-001,tenant-new,Tenant_1208,ashok sensiple';
var ltenantNameLength = '<div style="cursor:Pointer" title='
+ ltenantName
+'>'
+ ltenantName.split(',').length
+'</div>';
return ltenantNameLength;
HTML attribute values containing spaces must be quoted.
You are generating the title attribute without quotes around the value.
Your code:
var ltenantName = 'Sensiple,new-tenant-001,tenant-new,Tenant_1208,ashok sensiple';
var ltenantNameLength = '<div style="cursor:Pointer" title='
+ ltenantName
+'>'
+ ltenantName.split(',').length
+'</div>';
document.body.appendChild(document.createTextNode(ltenantNameLength));
As you can see sensiple is a new attribute and not part of the value of the title attribute.
Add quotes:
var ltenantName = 'Sensiple,new-tenant-001,tenant-new,Tenant_1208,ashok sensiple';
var ltenantNameLength = '<div style="cursor:Pointer" title="'
+ ltenantName
+'">'
+ ltenantName.split(',').length
+'</div>';
document.body.appendChild(document.createTextNode(ltenantNameLength));
Better yet, don't try to mash strings together in JS to make HTML:
var ltenantName = 'Sensiple,new-tenant-001,tenant-new,Tenant_1208,ashok sensiple';
var ltenantNameLength = document.createElement('div');
// This normally indicates a link. If you want a link, why not use <a>?
ltenantNameLength.style.cursor = "pointer";
ltenantNameLength.title = ltenantName;
ltenantNameLength.appendChild(
document.createTextNode(
ltenantName.split(',').length
)
);
document.body.appendChild(ltenantNameLength);

Javascript string HTML composition

I have this function that I use as a Custom Formatter in a JqGrid for ASP.NET WebForm
function formatLink(cellValue, options, rowObject) {
var res = cellValue.split(" - ");
var newLink = "";
var value = rowObject['Filter'];
var link = '<a class=\"clickCell\" href=\"#\" OnClick=\"CellClicked(\'value\')\">' + res[0] + '</a> - ' + res[1];
newLink = link.replace("value", value).replace("'", "\'");
return newLink;
}
the returned link does not work.
Here is an example:
<a onclick="CellClicked('vpd.esercizio = '2011-2012'')" href="#" class="clickCell">3</a>
As you can see, the var value contains string with quote. I will use its content to compose sql where condition.
Can you help me get things work?
Why don't you simply do
value.replace("'","\\'")
var link = '<a class="clickCell" href="#" OnClick="CellClicked('+value+')">' + res[0] + '</a> - ' + res[1];
?
With that replace you should be fine. I also removed some unnecesary back slashes because you can use double quotes inside simple quotes.
document.write(' "" '); returns ""

Categories

Resources