function searchString(user_input, search) {
var user_string = document.getElementById('user_input');
var search_string = document.getElementById('search');
document.write(search_string.value);
}
The document would'nt print the value.I am new to javascript and finding it hard to figure out why? I also tried this:
function searchString(user_input, search) {
var user_string = document.getElementById('user_input');
var search_string = document.getElementById('search').value;
document.write(search_string);
}
But no results. I am a noob, please help?
Don't use document.write. Add jQuery to your site instead, then you'd simply do something like:
$('#search').val(search_string);
And you'd get the values using:
var test = $('#searchBox').val();
If you want to do something professional grade I recommend getting into Vue.js as early as possible, it's essentially built to tackle this specific type of problem.
Doing "raw" javascript is sometimes a good thing but don't make things difficult for you. When you have to edit the DOM, use jQuery. If you want to build a website that is highly responsive to various data on your website, use Vue.js. Don't use raw javascript if you're a noob.
Related
Code example:
<c:out value="${slide.textContent}"/>
Output example: ' <script> alert("Hello! I am an alert box!")</script> 😃 '
So what I am trying to do is that the last part of the example is a normal emoji and I want it to be displayed. But at the same time I want it to be save for XSS. So setting escapeXml to false is not the way to do it. what is a good way to solve this problem or are there other ways to let this work out?
Recommendation are more than welcome.
edit: the first part of the example <script> should stay as text. I might understand the confusion so that's why I'm mention it.
Kind of solution:
I did solve it by calling the text with Javascript & than placing it again
function myFunction() {
var inputText = document.getElementById("myList").textContent;
var outputText = inputText.replace(/</g,"<").replace(/>/g,">");
document.getElementById("myList").innerHTML = outputText;}
But I am still wondering what the real solution is. It seems that a lot of companies replace the Emoji with a image. Wondering why there is no libary for something like that.
So I have this JS script:
<script>
function getCheckedProperty(obj,args)
{
if(document.getElementById("<%=checkbox1.ClientID %>").checked)
return true;
else
return false;
}
</script>
This only works for checkBox1. I want to be able to pass control id from parameters, so that it can return value of passed control. Also, please, respond with the usage.
<asp:CustomValidator runat="server" ClientValidationFunction="getCheckedProperty()></asp:CustomValidator>
TIY. SRJ.
Check this question it might have your answer.
if I get it right you want to get ids dynamically for example checkbox1, checkbox2,...
You can add the dynamic part to the id like this:
for (var i = 1; i < n; i++) {
var id = "checkbox" + i;
var ch = document.getElementById(id);
if (ch.checked == false)
return false;
}
return true;
Unfortantly, this is a real problem. The control name(s) are generated at runtime, and ALSO THIS:
document.getElementById("<%=checkbox1.ClientID %>")
So at page render time, the .net pre-processor will SWAP out the <% %> at render time.
this is also why you can't say have the js code in a external library and expect this to work.
However, your DEAD OBVIOUS question remains. Stuff a name into a simple variable and use that to get the control. After all, we can't and would not want to HARD code the value as per above, and it would be beyond silly to assume we ONLY have a means to HARD code references to controls.
So, you want of course this:
var MyControl = 'Checkbox1';
var ckBox = document.getElementById(MyControl);
if (ckBox.checked)
alert('Check box ' + MyControl + ' is checked!');
else
alert('Check box ' + MyControl + ' is UN-checked');
Now in fact the ABOVE can and will work if you force the control name generation as static.
so, here is the markup:
<asp:CheckBox ID="CheckBox1" runat="server" ClientIDMode="Static" />
So, if you ARE able and ARE willing to use ClientIDMode static, then the .net processing will NOT re-name your control. As a result you can do this:
var MyControl = 'Checkbox1';
var ckBox = document.getElementById(MyControl);
Or, even this (as HARD coded)
var ckBox = document.getElementById('CheckBox1');
Or even this:
var ckbox2 = document.getElementById(<%= CheckBox1.ClientID %>);
Now, the last one above? Well, we ARE useing the .net pre-processor to swap out the name - but it will still work - and clientID will not be changed - but the pre-processor is STILL involved.
AGAIN: the <%= 'SomeControlName.ClientID%> ONLY works because this expression is SWAPPED out at runtime by the .net web page pre-processor. This occures BEFORE the js code is run.
So you can NOT use a variable in the above <%=%> expressions since the js code HAS NOT even run and the new js code has not even been generated at this point in time.
In effect, you would (have to) do a PAGE search for the control. If you can NOT adopt ClientIdMode="static", then you MUST SEARCH the page.
You can write your OWN search routines - kind of like adopting a nice road to world poverty, or you bite the bullet, and adopt a library that WILL do the heavy lifting for you.
So, without using (forcing) StaticID on the control? then you now have to accept the BIG HUGE LARGE MASSIVE decision and introduce jQuery into your application.
jQuery is able to scour and search and look and loop and find that control for you on the web page. This is a cost not without processing cost, and not without a big speed penalty.
So, without staticID's, then you can adopt jquery and do this:
<script src="Scripts/jquery-3.5.1.js"></script>
<script>
// so if you decide and adopt jQuery, then it can do the searching for you
// BUT YOU ARE now adopting and committing to a whole new js library
// so, with jQuery we cna do this:
function jstest2(){
var ckbox2 = $('#CheckBox1');
var ckboxdom = ckbox2[0];
alert('status of check box = ' + ckboxdom.checked);
// of course the above is STILL hard code
// get control by runtime or NON hard code
// get (search) for check box based on control name in
// a variable
var MyCheckBox = 'CheckBox1';
var ckbox3 = $('#' + MyCheckBox);
var ckboxdom3 = ckbox3[0];
alert('status of check box = ' + ckboxdom3.checked);
</script>
I found after doing a nuget of jQuery, the fans on my laptop became too hot to even keep on my lap. But, things did settle down, and eventually the VS editors caught up, and things did settle down.
Also keep in mind that you have to re-learn how to reference a simple control.
eg:
<script>
function getbox() {
var tbox = document.getElementById('TextBox1');
alert(tbox.value);
// jQuery example
var tbox2 = $('#TextBox1');
alert(tbox2.val());
}
</script>
So notice now, how the long time js standard and approach is "value" as a property?
Well, now you using .val() that is a function (method) of that search result. So just keep in mind that by adopting jQuery, then all of your code that needs to get simple values from controls has to under go a syntax change, and you as a developer will have to re-lean how to reference a simple control with new syntax. The check box is a great example - it now becomes a array, and you use that array to get at the checked property.
And same in above for a simple grab of a value from a text box.
Notice how the syntax and approach to getting the value of the text box NOW has changed!!!! So you need a cheat-sheet since simple things like value now become .val().
And the same changes occur for say a label on a web page (again syntax changes).
You will ALSO notice that the results of the check box example are an array!!! So we had to drill down into the resulting array[] to get the "checked" value.
Of course how big of a deal your code changes are by adopting jQuery? Well, it depends, on relative medium sized or even a small project? $20,000 was budgeted and we still changing things.
On larger projects you simply need more manpower and would add another zero to the above cost to adopt jQuery.
However, jQuery is now widespread used, and it will do the "dirty work" of searching the DOM for you, and if you need runtime resolution as opposed to compile time resolution to find a simple control on a web page, then jQuery is probably your best choice. And I find that jQuery is really nice for ajax calls - so while it is a big change, it still well worth the effort to adopt the jQuery library and risk introducing this framework into your existing projects.
I'm currently looking to run a simple script using jQuery and TamperMonkey as I'm doing a recurent job which is time consuming and that should be pretty basic, not sure how to achieve the below (I've recorderd a gift) - I'm new to jQuery/coding, but searching arround, using this:
//Get
var IPG = $('#txt_name').val();
//Set
$('#txt_name').val(IPG);
might be where to look at?
the script should scan the field IPG ID where -1 are present, copy the name from the channel description and copy it to IPG description
https://gyazo.com/f4bd243827df598edfdd78ec1a2d53b5
any help in achieving this would be appreciate,
many thanks,
I named HTML elements' ids by myself because I simply don't know what are those fields' id named in your app.
What you are trying to achieve it is really simple and this code can do you the trick:
var IPG = $('#IPGid').val();
if (IPG==-1)
{
var toCopy = $('#ChannelDescription').val();
$('#IPGDesc').val(toCopy);
}
Note:
This can only be done once the page is loaded it is not live for every action.
This cannot treat all lines of the table you should figure your way out of how turning it dynamic to the whole table.
I need to use JavaScript to search the source code of the current page for a string, e.g data-userId="2008", then extracts the id number (2008 in this case) and creates a hyperlink to include it, e.g. http://www.google.com?2008.
I've been attempting to use indexOf and document.documentElement.innerHTML approaches but not getting anywhere. I've got closer with the help of this post but no success yet.
Here's what i have so far:
<script type="text/javascript">
function getVals() {
code = document.getElementsByTagName("html")[0].innerHTML;
results = code.match(/data-userId=(\d*)&/g);
for (i=0;i<results.length;i++) {
value = results[i].match(/data-userId=(\d*)&/);
}
}
onload = getVals;
document.write(code);
</script>
Due to restrictions on our network the solution needs to be JavaScript.
Use the getAttribute() method of the Element object http://www.w3schools.com/jsref/met_element_getattribute.asp.
I'm not sure why exactly you'd query the html element and then look at innerHTML. Do you not know which tags/selectors will contain the data attribute you're looking for? If you don't know which selectors you're looking for you can use a recursive function like this to walk the DOM and store the values in a data structure of your choice - I'll use an array of objects in this example (not sure how you need this data formatted).
Also, I'm not sure how you're choosing to visit these pages, but the below code could be easily modified to create hyperlinks when/if the attributes you're looking for are found.
var storeElements = [];
function walkTheDOM(node){
if(node.getAttribute('data-userId') !== null){
storeElements.push({"element": node, "attrValue": node.getAttribute('data-userId'});
}
node = node.firstChild;
while(node){
walkTheDOM(node);
node = node.nextSibling;
}
}
Then you can call the function like this:
walkTheDOM(document.querySelectorAll('html')[0]);
If this isn't what you're looking for let me know and I can change my answer. For those of you who've read Douglas Crockford's "Javascript: The Good Parts" this function may look very familiar :).
I'm writing my first firefox add-on.
It was completed, but mozilla rejected it with this answer:
1) Your add-on creates DOM nodes from HTML strings containing potentially unsanitized data, by assigning to innerHTML or through similar means. Aside from being inefficient, this is a major security risk. For more information, see https://developer.mozilla.org/en/XUL_School/DOM_Building_and_HTML_Insertion. Here are some examples where you do this: (cut...)
I wrote:
var myDiv = content.document.getElementById("myContent");
myDiv.innerHTML = "some html code";
now I'm not a JS programmer and I don't understand how to go on.
I tested some code like this:
var NewNode = content.document.createElement("span");
NewNode.appendChild(content.document.createTextNode("Hello World!"));
//content.document.body.appendChild(NewNode);//ok, works
content.document.getElementById("myContent").appendChild(NewNode);//doesn't work
but it doesn't work until I append it to .body
Samples working on other pages seems not working here. Moreover I don't understand if it fixes the problem that mozilla indicated.
Could you please help me with the code that should replace the two lines I wrote?
If you need the full code, here it is: http://www.maipiusenza.com/LDV/down/ldvgenerator.xpi
Thanks!
Nadia
Just did a quick js fiddle, I was wondering why you have used content.document so I amended it to document and it worked.
http://jsfiddle.net/eDW82/
var NewNode = document.createElement("span");
NewNode.appendChild(document.createTextNode("Hello World"));
document.getElementById("myContent").appendChild(NewNode);
I had a similar problem with unsanitized HTML and as I used it extensively I opted to use jQuery which will pass mozillas rules. It makes life a lot easier to be able to create your nodes that way.
$("<div>", {id:"example"}).text("Hello World")
It just reads so much nicer.
OK then, I did some digging and I think I managed to find your problem:
Whenever you want to inject any kind of html to your extension, The browser considers it as a security hole, that's why you have this problem. you have 2 different solution;
first: you can create an iframe and use it to show your html (in javascript whenever we want to show a file we have 2 option, first pass a file path on the server, or use data: to show your data directly):
var htmlStr = "<span>Hello World!</span>";
var frm = content.document.createElement("iframe");
content.document.getElementById("myContent").appendChild(frm);
frm.src = "data:text/html;charset=utf-8," + encodeURIComponent(htmlStr);
second: this solution would help you out, if you don't want to use an iframe to show your html.
var htmlStr = "<span>Hello World!</span>";
var frm = document.createElement("iframe");
frm.style.display="none";
document.body.appendChild(frm);
var win = frm.contentWindow;
var frmrange = win.document.createRange();
// make the parent of the first div in the document becomes the context node
frmrange.selectNode(win.document.firstChild);
var frg = frmrange.createContextualFragment(htmlStr);
content.document.getElementById("myContent").appendChild(frg);
Old Guess: the problem in your code is different document objects, try this:
var NewNode = content.document.createElement("span");
NewNode.appendChild(content.document.createTextNode("Hello World!"));
content.document.getElementById("myContent").appendChild(NewNode);
this was my first clue to point out.