Is it possible to do ".value +=" in JQuery? - javascript

Classic javascript:
var myvar = document.getElementById("abc");
abc.value += "test";
abc.value += "another test";
Jquery:
$("#abc").val($("#abc").val()+"test");
$("#abc").val($("#abc").val()+"another test");
Is there a way to make my Jquery prettier, maybe with a hidden += function that I could use? I know that .val() is not an attribute, but I feel there must be a way to make this code more beautiful to look at...
Something like this would be great:
$("#abc").valueAttribute += "test"
$("#abc").val().content += "test"
$("#abc").val().add("test")

You could go back to the original DOM element.
$("#abc").get(0).value += "test";
Otherwise, you'd have to write a plugin
$.fn.appendVal = function (newPart) {
return this.each(function(){ $(this).val( $(this).val() + newPart); });
};
$("#abc").appendVal("test");

Since jQuery 1.4, it is possible to pass a function to .val() which gets the current value as second argument:
$("#abc").val(function(i, val) {
return val + "test";
});

I've never come across anything like that, doesn't mean it doesn't exist though.
I usually just store val() in a temporary variable and do the manipulation on that, then call val(temp) in a separate line. It spreads the operation out to three or more lines, but it's still more readable than .val(.val() + ""), IMO. It also scales better than +=, if you have a more complicated expression to do to the value.
var temp = $(".abc").val();
temp += "test";
$(".abc").val(temp);

$() returns a selection; it doesn't return the actual resulting object (although in practice, it simply returns a list of the actual objects). If you want to mutate the object's .value property, you can do this:
$('.abc').each(function(){ this.value += foo; });
If you like, you can create functions that operate on selections, such as .add(), which could be implemented like this:
jQuery.fn.extend({ add: function(k,v) { this[k](this[k]()+v); } });
which can then be used like this:
$('.abc').add('val', foo);
...but I don't think this is any better than using $().each()

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
(function($){
$.fn.valInc = function(vadd)
{
var val = $(this).val() + '' + vadd;
$(this).val(val);
}
})(jQuery);
$(function(){
$("#tst").valInc('test 2');
});
</script>
</head>
<body>
<input id='tst' value="test" />
</body>
</html>

Related

RSS giving me unclosed tag link, couldn't get the innerHTML

I'm doing a study using a RSS, but the Web Site gives me a RSS with an unclosed tag then I couldn't get the innerHTML of this tag.
I don't know how to resolve the problem with jquery and make the tag closed or a possible solution like this.
Here is the code :
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" content="xml">
<script type="text/javascript" src="api/jquery.js"></script>
</head>
<body>
<p id="someElement" visibility="hidden"></p>
<p id="anotherElement"></p>
<script type="text/javascript">
var x = new XMLHttpRequest();
x.open("GET", "http://www.lemonde.fr/rss/une.xml", true);
x.onreadystatechange = function () {
if (x.readyState == 4 && x.status == 200)
{
var doc = x.responseXML;
var string = (new XMLSerializer()).serializeToString(doc);
$("#someElement").append(string);
alert("test");
var tag = document.getElementsByTagName("item");
for(var i = 0, max = tag.length; i < max; i++){
var htmli = tag[i];
//alert(htmli.innerHTML);
//uncomment the alert to see the xml got from the rss
var title = htmli.getElementsByTagName("title")[0].innerHTML;
var link = htmli.getElementsByTagName("link")[0].innerHTML;
var description = htmli.getElementsByTagName("description")[0].innerHTML;
var toAdd = "<ul><li> title : " +title+"</li><li> link : "+ link +" </li><li> description :"+description+" </li></ul>";
$("#anotherElement").append(toAdd);
}
}
};
x.send(null);
</script>
</body>
</html>
Any solution to this?
I have jquery in a folder named api.
Thanks a lot !!
(I notice that while you include jQuery in a script tag, you're not actually using it in your code. It's much better practice to use jQuery's functionality to manage AJAX requests and serialization, if you're going to use it at all, as they cover many more situations and browser versions. I'd also recommend retrieving jQuery from a CDN rather than hosting it yourself. jQuery has had the ability to parse XML natively since 1.5. The following was written using 1.12.)
I ran into the same issue with unclosed tags in an RSS feed and came up with a terrible solution to it. I have not tested this cross-browser and would not recommend incorporating it into production code, but it worked to solve a one-time problem for me.
The idea is to take the raw output of the RSS item's text, cram it into the jQuery HTML parser, and then manually inspect its output until we get to an item that it thinks might have been an HTML <link> tag. Because we know the RSS link tag isn't closed, the next thing it encounters should be parsed as an HTML Text object, which we can extract for our permalink URL.
Here's how I would rewrite your script to take better advantage of jQuery and incorporate my hack. (I'm assuming you have set up CORS or something else so that you can actually retrieve the feed from lemonde.fr cross-domain.)
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" content="xml">
<script type="text/javascript" src="//code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body>
<p id="someElement" visibility="hidden"></p>
<p id="anotherElement"></p>
<script type="text/javascript">
(function($, window, document) {
function fetchFeed(url) {
// use jQuery to handle AJAX
$.get(url, function(data) {
// parse XML result with jQuery
var $XML = $(data);
$XML.find("item").each(function() {
// ensure that we have a jQuery-wrapped _this_ object and
// create a new object with the properties we want
var $this = $(this),
item = {
title: $this.find("title").text(),
description: $this.find("description").text(),
link: ""
};
// since the XML parser will treat the unclosed <link> as valid,
// we instead send the raw output to the HTML parser and tell it do to its best
var $redigested = $($this.html());
// jQuery should produce an array of HTML DOM objects
for (var i = 0; i < $redigested.length; i++) {
// if we found an HTMLLinkElement--a <link> tag--followed by a Text element, that's our URL
if ($redigested[i] instanceof HTMLLinkElement && $redigested.length >= i + 1 && $redigested[i + 1] instanceof Text) {
item.link = $redigested[i + 1].data;
break;
}
}
console.log("link: " + item.link);
var toAdd = "<ul><li> title: " + item.title + "</li><li> link: " + item.link + " </li><li> description: " + item.description + " </li></ul>";
$("#anotherElement").append(toAdd);
});
});
}
$(function() {
// call the fetch function on DOM ready
fetchFeed("http://www.lemonde.fr/rss/une.xml");
});
})(jQuery, window, document);
</script>
</body>
</html>

Javascript: How to Iterate Object [Key: value] but skip some keys ([fastest way possible])

If given a script like:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test DOC</title>
<script type="text/javascript" src="../nt_scr/jq_1.9.js"></script>
<script type="text/javascript">
var mainObj = { 0: { "fruitName":"Lemon",
"fruitColor":"green",
"fruitTaste":"bad"},
1: { "fruitName":"Mango",
"fruitColor":"Yellow",
"fruitTaste":"Yammy"},
2: {
"fruitName":"Banana",
"fruitColor":"Yellow",
"fruitTaste":"Yammy"},
"skip_these":
{
"team1":"Liverpool",
"team2":"Manchester United"
}
}
var collect_data = $.parseJSON(JSON.stringify(mainObj)),
getFruitNames=[],getFruitColors=[], getFruitTastes=[];
$.each( collect_data,function(index,val){
//console.log(val); //Un-comment this console.log to see the contents of 'val'
//----->Here is the Challenge:,---------\\\
if(/*How do you SKIP if val is something like */ "val.team1" || "val.team2"){
getFruitNames.push(val.fruitName);
getFruitColors.push(val.fruitColor);
getFruitTastes.push(val.fruitTaste);
//This works well so long as we have not yet reached the "skip_these":
//Once there, it reports an error because there is no "skip_these".fruitName or "skip_these".fruitColor
}
console.log( getFruitNames[index])// Run a test out put :: NOTICE the "Undefined" in the Console. How to avoid that?
//To see well, Comment the previous console.log <<the one on top>>
})
</script>
</head>
<body>
</body>
</html>
I did this sometimes ago but somehow, my brain is just blank now.... Any suggestion is highly appreciated. (Please Run with your jQuery)
As JQuery docs state,
Returning non-false is the same as a continue statement in a for loop;
it will skip immediately to the next iteration.
So, following your example, you can skip the objects with the properties you don't need by using the following:
JavaScript
$.each( collect_data,function(index,val){
//console.log(val); //Un-comment this console.log to see the contents of 'val'
//----->Here is the Challenge:,---------\\\
if(val.team1 || val.team2){
return true;
}
getFruitNames.push(val.fruitName);
getFruitColors.push(val.fruitColor);
getFruitTastes.push(val.fruitTaste);
//This works well so long as we have not yet reached the "skip_these":
//Once there, it reports an error because there is no "skip_these".fruitName or "skip_these".fruitColor
console.log( getFruitNames[index])//No "Undefined"
})
https://plnkr.co/edit/9vOACIpnlWRtSWjmAm5x?p=preview
(not jquery - vanilla)
Iterate properties and skip specific keys: (did not test for syntax but it should be ok)
var skipped = ['keySkipped'];
for (var someProperty in someObject) {
if (someObject.hasOwnProperty(someProperty) && skipped.indexOf(someObject[someProperty] === -1)) {
// do stuff
}
}
Explanation: iterate properties and if propertie indeed is contained by the object but not contained in skiped do whatever

How to check for invalid argument in JS?

What can I do to attain the below thing... The argument generated is bit weird!
function function1(argument1,argument2)
{
if argument1 = "
") do something;
}
"argument1" and "argument2" are generated by the CMS. I can't do anything with those contents.
Either it will generate:
<script type='text/javascript'>
document.write(function1("argument1","argument2"));
</script>
OR
<script type='text/javascript'>
document.write(function1("
","argument2"));
</script>
You can use String.prototype.trim():
function function1(argument1,argument2)
{
if(argument1.trim() == ''){
// do something
}
}
If you're worried about old browsers, you can implement the trim function yourself, see this question.

How to remove <script> tags from an HTML page using C#?

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
if (window.self === window.top) { $.getScript("Wing.js"); }
</script>
</head>
</html>
Is there a way in C# to modify the above HTML file and convert it into this format:
<html>
<head>
</head>
</html>
Basically my goal is to remove all the JavaScript from the HTML page. I don't know what is be the best way to modify the HTML files. I want to do it programmatically as there are hundreds of files which need to be modified.
It can be done using regex:
Regex rRemScript = new Regex(#"<script[^>]*>[\s\S]*?</script>");
output = rRemScript.Replace(input, "");
May be worth a look: HTML Agility Pack
Edit: specific working code
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
string sampleHtml =
"<html>" +
"<head>" +
"<script type=\"text/javascript\" src=\"jquery.js\"></script>" +
"<script type=\"text/javascript\">" +
"if (window.self === window.top) { $.getScript(\"Wing.js\"); }" +
"</script>" +
"</head>" +
"</html>";
MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(sampleHtml));
doc.Load(ms);
List<HtmlNode> nodes = new List<HtmlNode>(doc.DocumentNode.Descendants("head"));
int childNodeCount = nodes[0].ChildNodes.Count;
for (int i = 0; i < childNodeCount; i++)
nodes[0].ChildNodes.Remove(0);
Console.WriteLine(doc.DocumentNode.OuterHtml);
I think as others have said, HtmlAgility pack is the best route. I've used this to scrape and remove loads of hard to corner cases. However, if a simple regex is your goal, then maybe you could try <script(.+?)*</script>. This will remove nasty nested javascript as well as normal stuff, i.e the type referred to in the link (Regular Expression for Extracting Script Tags):
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
if (window.self === window.top) { $.getScript("Wing.js"); }
</script>
<script> // nested horror
var s = "<script></script>";
</script>
</head>
</html>
usage:
Regex regxScriptRemoval = new Regex(#"<script(.+?)*</script>");
var newHtml = regxScriptRemoval.Replace(oldHtml, "");
return newHtml; // etc etc
This may seem like a strange solution.
If you don't want to use any third party library to do it and don't need to actually remove the script code, just kind of disable it, you could do this:
html = Regex.Replace(html , #"<script[^>]*>", "<!--");
html = Regex.Replace(html , #"<\/script>", "-->");
This creates an HTML comment out of script tags.
using regex:
string result = Regex.Replace(
input,
#"</?(?i:script|embed|object|frameset|frame|iframe|meta|link|style)(.|\n|\s)*?>",
string.Empty,
RegexOptions.Singleline | RegexOptions.IgnoreCase
);

JavaScript to read content between <a> tags

Below is my html page:
<html>
<head>
<title>My Cat website</title>
</head>
<script type="text/javascript" src="script12.js"></script>
<body>
<h1>
My_first_cat_website
</h1>
</body>
</html>
Below is my JavaScript:
window.onload=initall;
function initall()
{
var ans=document.getElementsByTagName('a')[0].firstChild.data;
alert(ans);
if(ans<10)
{
alert(ans);
}
var newans=ans.subString(0,9)+"...";
}
Here my code is not going into if block. My requirement is if var "ans" length is above 10 then append it with ... else throw an alert directly. Can anyone help me?
Here is Solution using data property
window.onload=initall;
function initall()
{
var ans=document.getElementsByTagName('a')[0].firstChild.data;
if(ans.length<10)
{
alert("hmmm.. its less then 10!");
}
var newans= ans.substring(0,9)+"...";
document.getElementsByTagName('a')[0].firstChild.data = newans;
}
Here is it live view you wise to check example: http://jsbin.com/obeleh
I have never heard of the data property on a DOM element. Thanks to you, I learned it's a property on textNode elements (the same as nodeValue).
Also, using getElementsByTagName when the ID is available is unperformant.
subString doesn't work, it is substring. The case is important for methods as javascript is case sensitive (like most programming languages).
The other thing you're missing is an else. In your code, the var newans... will always be ran.
Here is something working:
window.onload = function() {
var ans = document.getElementById( 'message' ).textContent;
if ( ans.length < 10 ) {
alert( ans );
}
else {
var newans = ans.substring( 0, 9 ) + '...';
}
}

Categories