I write a form that inserts some xml tags into textarea. I use this function:
(function ($) {
addCustomTag = function (name, param, value) {
var code = "<" + name + " " + param + "=\"" + value + "\">\n</" + name + ">";
document.getElementById("codeArea").value += code;
};
})(jQuery);
How can I make that some other function will insert subtags into tags that were created before?
XML code will never be used on server. All I need is to insert tex in specific line which is depends on what was on this line before not cutting it. Something like this:
addCustomSubtag = function(name,param,value,parent) {
document.getElementById("codeArea").selectionStart = document.getElementById("codeArea").value - parent.length;
var code = "<" + name + " " + param + "=\"" + value + "\">\n</" + name + ">";
document.getElementById("codeArea").value += code;
};
Javascript isn't necessary. It also can be written on jQuery.
Thanks.
You can any of these jQuery functions
http://api.jquery.com/append/
http://api.jquery.com/appendTo/
http://api.jquery.com/prepend/
Update:
Actually we can use jQuery DOM manipulation methods to manipulate XML also.
var xml = "<main/>";
alert(xml); // <main/>
var $xml = $(xml).append($("<sub1/>"));
alert($xml.html()); // <sub1></sub1>
$xml.find("sub1").append($("<sub2/>"));
alert($xml.html()); // <sub1><sub2></sub2></sub1>
alert($xml.get(0).outerHTML); // <main><sub1><sub2></sub2></sub1></main>
Related
My question is this, if I have an Text html element that looks like...
<a id='1' onmouseover="changeImage('setname/setnumber')">Cardname</a>
Can I retrieve the id (in this case 1) on a mouseover event so that I may use it in javascript to do something else with it.
Not sure if I can do this, but I'm hoping I can. What I have is a bit of javascript code that is taking data from an xml document. I have a list of 500+ cards that I have parsed through and stored by categories that are used often. Here are the relevant functions as they apply to my question.
var Card = function Card(cardName, subTitle, set, number, rarity, promo, node)
{
this.cardName = cardName;
this.subTitle = subTitle;
this.set = set;
this.number = number;
this.rarity = rarity;
this.promo = promo;
this.node = node;
}
Where node is the position within the list of cards, and due to the formatting of the document which I started with contains each card alphabetically by name, rather than numbered logically within sets.
Card.prototype.toLink = function()
{
var txt = "";
this.number;
if (this.promo == 'false')
{
var image = this.set.replace(/ /g, "_") + '/' + this.number;
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + "')>";
txt += this.toString() + "</" + "a>";
}
else
{
var image = this.set.replace(/ /g, "_") + '/' + this.rarity + this.number;
var txt = "";
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ')>";
txt += this.toString() + "</a>";
}
return txt;
}
Here is what I am using to populate a list of cards, with names that upon hovering over will display a card image.
function populateList () {
for (i = 0; i<cards.length; i++)
document.getElementById('myList').innerHTML += '<li>'+cards[i].toLink()+</li>;
}
What I am trying to do is retrieve the id of the element with the onmouseover event so that I can retrieve everything that is not being saved to a value.
I realized I can pass the id as part of the changeImage function as a temporary workaround, though it involves rewriting my toLink function and my changeImage function to include a second argument. As a married man, I've enough arguments already and could do with one less per card.
In summary, and I suppose all I needed to ask was this, but is there a way using only javascript and html to retrieve the id of an element, onmouseover, so that I may use it in a function. If you've gotten through my wall of text and code I thank you in advance and would appreciate any insights into my problem.
if I have an Text html element that looks like...
<a id='1' onmouseover="changeImage('setname/setnumber')">Cardname</a>
Can I retrieve the id (in this case 1) on a mouseover event so that I may use it in javascript to do something else with it.
Yes, if you can change the link (and it looks like you can):
<a id='1' onmouseover="changeImage('setname/setnumber', this)">Cardname</a>
Note the new argument this. Within changeImage, you'd get the id like this:
function changeImage(foo, element) {
var id = element.id;
// ...
}
Looking at your code, you'd update this line of toLink:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', this)>";
Of course, you could also just put the id in directly:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', " + this.node + ")>";
And then changeImage would be:
function changeImage(foo, id) {
// ...
}
I didn't use quotes around it, as these IDs look like numbers. But if it's not reliably a number, use quotes:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', '" + this.node + "')>";
I am trying to create text node in xml using jQuery.
Below is the code which create text node in xml, but it is creating textnode with default namespace.
function CheckChildNodeExistance(bindName, $xml) {
$xmlNode = $xml.find(bindName);
if ($xmlNode.length <= 0) {
debugger;
var bName = bindName.split(' ');
//$xml.find(bName[0] + ' ' + bName[1]).append('<' + bName[2] + '></' + bName[2] + '>');
//var str1 = $xml.createTextNode(bName[2]); //this line gives me error
//$xml.append(str1);
$xml.append($('<' + bName[2] + '></' + bName[2] + '>'));
}
}
$xml is my jQuery xml object.
Output of this method create xml element with default namespace.
if you closely look into address node, it has default namespace which is causing the problem. I want to remove this namespace.
<address xmlns="http://www.w3.org/1999/xhtml" />
Can anybody help me on this
<row><CardCode>ABCDEFGH</CardCode><Name>HO</Name><Position>1</Position><Phone1>1</Phone1><Phone2>1</Phone2><MobilePhone>1</MobilePhone><Fax>1</Fax><E_Mail>1</E_Mail><Pager>1</Pager><Remarks1>1</Remarks1><Remarks2>1</Remarks2><InternalCode>1307</InternalCode><Gender>gt_Undefined</Gender><Active>tYES</Active><FirstName>Manish</FirstName><MiddleName>S</MiddleName><LastName>Chourasia</LastName><address xmlns="http://www.w3.org/1999/xhtml" /></row>
I am trying to get the value of a javascript variable within an html page. I have figured out how to get the text of all script tags but can't seem to figure out how to get the text of a specific variable within a script tag. Does anyone know how to get the text of a javascript variable?
The following is an example of what I'm trying to parse from. I'm trying to get the value of "var d"
<div id="box" style="position:absolute;z-index:6;left:px;top:450px;"></div>
<script language="javascript">
function showTooltip(element, town_name, p, points, a, town_type){
var t = $('tt');
t.style.top = (-75 + element.offsetTop) + 'px';
t.style.left = (25 + element.offsetLeft) + 'px';
t.style.backgroundImage="url('images/odd.png')";
t.innerHTML = '<font color=#AD4100>' + unescape(town_name) + '<br/>' + unescape(p) + '<br/>' + points + '<br/>' + unescape(a) + '<br/>' + unescape(town_type) + '</font>';
t.show();
}
function hideTooltip(){
$('tt').hide();
}
var d = [[1490.77265625,1373.4140625,30983,'TownID: 30983','GREY','circle_grey.png',1248,'planet x\'s city 5','','N/A'],[1186.45390625,1538.265625,33009,'TownID: 33009','GREY','circle_grey.png',1150,'wendyshome','','N/A'],[1234.496875,856.18203125,31646,'TownID: 31646','GREY','circle_grey.png',1312,'...','','N/A'],[1041.30078125,812.55859375,35358,'TownID: 35358','GREY','circle_grey.png',1207,'Waterville','','N/A'],
The following is a snippet of my code that gets the text of all script tags.
for element in page.iter('script'):
scriptText = element.text_content()
print(scriptText)
You'll have to use string processing on scriptText once you have that extracted. lxml cannot help you any more here.
If var d is the last entry in the script, you could use:
var_d_source = scriptText.split('var d =', 1)[-1].rsplit(';', 1)[0].strip()
which should give you everything after var d = up to the last semicolon.
You'd then convert the value to Python with the json module:
var_d_value = json.loads(var_d_value)
I have a jQuery function that is executed by two different buttons.
$("#btnSearch, #btnDirectorSearch").click(function () {
Part of the html that this function builds depends on which button was hit. I am using data- attributes to store my variables like this:
var div = $(this).data("str");
And the html string I am building depends on what value the variable "div" is. Is there a way to do an inline if/else statement in jQuery?
if div = "choice1" {
html += '<tr data-str = "str1" data-dataItem = "dataItem1" data-result-title = "' + name + '" data-result-id="' + sel + '">';
} else {
html += '<tr data-str = "str2" data-dataItem = "dataItem2" data-result-title = "' + name + '" data-result-id="' + sel + '">';
}
That seems cumbersome and I'm hoping there is a better jQuery way of doing this.
Thanks!
you have a syntax error
if div = "choice1"
should be
if (div == "choice1")
Anyway, the pattern you're looking for is:
div == "choice1" ? <code for true> : <code for false>
you can use condition ? code when true: code when false
but i would suggest you to stick with curley braces only, as it looks better and easier to debug.
one more thing , do it as below
if(div==="choice1"){
}
else{
}
use ===
Since it's only the number that changes in the output, you could do this:
var num = div == "choice1" ? 1 : 2;
html += '<tr data-str="str'+num+'" data-dataItem="dataItem'+num+'" data-result-title="'+name+'" data-result-id="' + sel + '">';
If your choices are limited, you could add a small lookup array:
var choices = {
choice1: {
str: "str1",
data: "dataItem1"
},
choice2: { ... }
};
html += '<tr data-str="' + choices[div].str
+ '" data-dataItem="' + choices[div].data
+ '" data-result-title="' + name + ... etc;
I'm attempting to split a string I'm passing into
$("#groupUL").append("<li>" + "<h2>About Item:</h2> " + response.data[i].message + "<br /> " + "<h2>Posted By:</h2> <a href='#' onclick='splitName('" + response.data[i].from.name + "');'>" + response.data[i].from.name + "</a>" + "<br />");
Seems to be passing me the error
SyntaxError: syntax error
splitName(
Not sure how that's wrong...Here is the splitname function if that helps
function splitName(txt){
var myString = txt;
var mySplitResult = myString.split(" ");
console.log("The first element is " + mySplitResult[0]);
console.log("<br /> The second element is " + mySplitResult[1]);
console.log("<br /> The third element is " + mySplitResult[2]);
};
It's too hard to get it right when you put quotes in quotes in quotes and you try to escape it right. You got it wrong.
A solution is to make it in small parts :
var action = "splitName('" + response.data[i].from.name + "');";
$("#groupUL").append("<li>" + "<h2>About ... onclick=\""+action+"\">...");
But the best solution would be to follow best practice, that is not inline the javascript but use jQuery's binding function :
$("#groupUL").append("... <a id=myid ...");
$("#myid").click(function(){ splitName(response.data[i].from.name) });
I think the only problem with your code is with your readability issue. So I would suggest please improve it. Lets have a look at it. My code example # JSbin.
Here is the code :- (which i think is better)
var response = {
data : {
message: 'Cleaning code',
from: {
name: 'Clean Code works'
}
}
};
var li = $('<li>'); //Create empty li (Not Appending to DOM now due to performance issues)
$('<h2>').html('About Item:' + response.data.message + '<br />').appendTo(li);
$('<h2>').html('Posted By:').appendTo(li);
$('<a>').attr('href', '#')
.html(response.data.from.name)
.appendTo(li)
.click(function() {
splitName(response.data.from.name);
});
$('<br>').appendTo(li);
// Append li to ul (Final operation to DOM)
li.appendTo('#groupUL');
function splitName(txt){
var myString = txt;
var mySplitResult = myString.split(" ");
console.log("The first element is " + mySplitResult[0]);
console.log("The second element is " + mySplitResult[1]);
console.log("The third element is " + mySplitResult[2]);
}