how can i run any javascript in double quotes ?
For example:
<input type="text" value="" />
i would like to execute an alert or any other code in the value = "" (double quotes). Like:
<input type="text" value="<script> onmouseover=alert(0);</script>" />
the code show as a string on page. So is there anyway to execute script in double quotes ?
Ah, I see, you probably want to do something like this:
<input type="text" onchange="try{eval(this.value)}catch(e){}" />
That inline script will attempt to execute what's in its value attribute every time the tag is changed (and you blur out of the element). The try catch block is so that anything that would normally not work won't get executed. The eval function parses a string and runs it as Javascript code.
You leave yourself open to many forms of attacks when you use eval, so unless this is for purely educational or in house purposes, I would advise you don't use this.
The input object has its own events and you have to assign to them
For example to execute an alert when the mouse hovers over it:
<input type="text" value="testbox" onMouseOver="alert('testing');"/>
<input type="text" onmouseover="alert(0);" />
Related
I need to add some HTML after a radio-button, I want to add an image and function so I check the radio button when I click on it. I would check the radio button with my own selectRadioButton() function.
The existing code is, I can't edit this part:
<span class="ms-RadioText">
<input id="idFirstRadioButton" type="radio" name="idFirstRadioButton" value="1" />
</span>
My idea, to add my image with function, was to do it like this:
$("#idFirstRadioButton").after("Image 1:<br/><img src=\"http://urltoimage/image.jpg\" border=\"0\"/>");
But when I use this code, the HTML of my page is this:
<span class="ms-RadioText">
<input id="idFirstRadioButton" type="radio" name="idFirstRadioButton" value="1" /> Image 1:<br/><IMG src="http://urltoimage/image.jpg" border=0>
</span>
He's adding "shape="" idFirstRadioButton?)?="""
The correct code should be:
<span class="ms-RadioText">
<input id="idFirstRadioButton" type="radio" name="idFirstRadioButton" value="1" /> Image 1:<br/><a href="javascript:selectRadioButton("idFirstRadioButton")><IMG src="http://urltoimage/image.jpg" border=0></a>
</span>
I already tried with ', with \", combination of both, with a variable, ...
$("#idFirstRadioButton").after("Image 1:<br/><img src=\"http://urltoimage/image.jpg\" border=\"0\"/>");
$("#idFirstRadioButton").after('Image 1:<br/><img src="http://urltoimage/image.jpg" border="0"/>');
$("#idFirstRadioButton").after('Image 1:<br/><img src="http://urltoimage/image.jpg" border="0"/>');
What am I doing wrong or what is the code that I should use?
You should use different quotes inside your .after string, because they will be required. For example:
$("#idFirstRadioButton").after("Image 1:<br/><img src=\"http://urltoimage/image.jpg\" border=\"0\"/>");
This is the result:
<img src="http://urltoimage/image.jpg" border="0">
However, this is only if you have no other option. As #CBroe mentioned, you should try not to bind event handlers inside appended html, but try to handle them using proper way.
Example #Dan O provided seems to be something you should be looking for.
what you're doing wrong is using strings of HTML instead of constructing and appending Elements themselves, which (in addition to potential security concerns) can lead to the sort of confusing and annoying behavior you're seeing here. You want something like this:
var myImg = $("<img/>");
myImg.attr("src", "http://urltoimage/image.jpg");
myImg.on("click", function(e) {
selectRadioButton("idFirstRadioButton");
});
$("#idFirstRadioButton").after(myImg);
When you have more than 1 level deep of " or ' you need to intercalate them or escape them.
The last one should be right, except you kept using " inside instead of escaping them or alternating them.
The correct should be:
$("#idFirstRadioButton").after('Image 1:<br/><img src="http://urltoimage/image.jpg" border="0"/>');
So we start with single quote for the after, then double quote for the href, then we escape a single quote for the inside of the selectRadioButton, then a single quote to exit the string and dump the var, then back inside the string and keep going on.
Fiddle
NOTE: Remember to declare your var "VARidFirstRadioButton" that's the
shape of error.
I'm trying to pass the entered text to the controller using an ajax request. But i'm getting athe error "Uncaught TypeError: Cannot set property 'value' of null " when I tried to execute JS file..
Here is the HTMLcode:
<form action="">
<input type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
<input type="button" class="searchbox_submit1" name="submit" value="text" onClick="javascript:getSearchText();">
</form>
Here is the JS code:
function getSearchText() {
var searchText = document.getElementByName("search").value;
h_url=document.getElementById("u").value;
var theURL = h_url+'search_all/' + deptid + '/' + searchText + '/1';
$.ajax({
url : theURL,
fail: function(){
},
success : function() {
},
error:function(){
}
});
}
Please help me to fix this.
You don't have an element with the id u.That's why the error occurs.
Note that you are trying to get the value of the input element with the name 'u' and it's not defined in your code.
The problem may where the code is being executed. If you are in the head of a document executing JavaScript, even when you have an element with id="u" in your web page, the code gets executed before the DOM is finished loading, and so none of the HTML really exists yet... You can fix this by moving your code to the end of the page just above the closing html tag. This is one good reason to use jQuery.
In case anyone landed on this page for a similar issue, I found that this error can happen if your JavaScript is running in the HEAD before your form is ready. Moving your JavaScript to the bottom of the page fixed it for my situation.
The problem is that you haven't got any element with the id u so that you are calling something that doesn't exist.
To fix that you have to add an id to the element.
<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
And I've seen too you have added a value for the input, so it means the input is not empty and it will contain text. As result placeholder won't be displayed.
Finally there is a warning that W3Validator will say because of the "/" in the end. :
For the current document, the validator interprets strings like according to legacy rules that break the expectations of most authors and thus cause confusing warnings and error messages from the validator. This interpretation is triggered by HTML 4 documents or other SGML-based HTML documents. To avoid the messages, simply remove the "/" character in such contexts. NB: If you expect <FOO /> to be interpreted as an XML-compatible "self-closing" tag, then you need to use XHTML or HTML5.
In conclusion it says you have to remove the slash. Simply write this:
<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item...">
I knew that i am too late for this answer, but i hope this will help to other who are facing and who will face.
As you have written h_url is global var like var = h_url; so you can use that variable anywhere in your file.
h_url=document.getElementById("u").value;
Here h_url contain value of your search box text value whatever user has typed.
document.getElementById("u");
This is the identifier of your form field with some specific ID.
Your Search Field without id
<input type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
Alter Search Field with id
<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
When you click on submit that will try to fetch value from document.getElementById("u").value; which is syntactically right but you haven't define id so that will return null.
So, Just make sure while you use form fields first define that ID and do other task letter.
I hope this helps you and never get Cannot set property 'value' of null Error.
guys This error because of Element Id not Visible from js Try to inspect element from UI and paste it on javascript file:
before :
document.getElementById('form:salesoverviewform:ticketstatusid').value =topping;
After :
document.getElementById('form:salesoverviewform:j_idt190:ticketstatusid').value =topping;
Credits to Divya Akka .... :)
It seems to be this function
h_url=document.getElementById("u").value;
You can help yourself using some 'console.log' to see what object is Null.
h_url=document.getElementById("u") is null here
There is no element exist with id as u
Add defer to your script tag, if it's in header. It will allow your script to execute after the DOM is loaded.
<script src="script.js type="text/javascript"></script>
It should look like this:
<script src="script.js type="text/javascript" defer></script>
This is my first time using jquery and while this is a fairly simple task I'm stuck already.
I've got a input box with the time of day in it. I would like to create a button to grab the time and send it to a variable (setTime) so I can use the time elsewhere in the script.
However I'm having trouble the variable to pass, I've added an alert window but all I get is either a blank alert or an "undefined" alert.
The first line Start Time.... works fine its the setTime stuff that's broken.
Page header:
setTime = $('#setTime').text();
$('#formTime').timeEntry({show24Hours: true});
Page body:
<p>Start Time <input type="text" size="2" id="formTime" class="spinners" value="" /> </p>
<input type="button" value="Set Time" onclick="$('#setTime').val('#formTime');" />
<input type="button" value="Show Date" onclick="alert(setTime);" />
Thanks
You have to make a few changes to your code.
Update your Html by adding some ids for example.
<p>
Start Time <input type="text" size="2" id="formTime" class="spinners" value="" />
</p>
<input id="setTime" type="button" value="Set Time" />
<input id="showTime" type="button" value="Show Date" />
Personally I don't like assigning script to events within the html controls as they become hard to maintain and add clutter to the page.
You can write script at the bottom of the html page within a script tag or better yet, use an external js file. External js files will also keep your Html clean and your scripts unobtrusive.
var setTime = 0;
var $fromTime = $("#formTime")
$("#setTime").off("click").on("click", function(){
setTime = $fromTime.val();
});
$("#showTime").off("click").on("click", function(){
alert(setTime);
});
See working DEMO
Using jQuery can be confusing at times but the on-line documentation is fantastic.
#setTime means "The element with the id 'setTime'" - you have no element with that id, and the control you are trying to get the value of has no id at all.
timeEntry is not a jQuery method, so will error when you try to call it. If you are using a plugin that you think should add that method then you should say so.
.val('#formTime') will set the value of a form control to the string #formTime. If you want to get the value, don't pass that method an argument … and do assign the return value of the method call to something.
You should probably work through an introduction to programming and JavaScript.
Let's say I have this part.
<input id="text1" type="text" name="text1" onchange="alert('valueA');" /><br />
<input id="text2" type="text" name="text2" /><br />
What I'd want to do is to get the onchange event handler of the input="text1" and attach to another element's event, "text2".
So far , it's okay.I can get DOM0 hanlder of input "text1" and attach to text 2 as DOM2 .
_handler= $('#text1')[0].onchange;
$('#text2').change(function (event) {
if (typeof _handler=== "function") {
_handler.call(this, event);
}
But, the problem is , I want to change/add some js codes before attaching into "text2".
For example , before attaching into "text2", I want to change "alert('valueA');" into "alert('valueA.This is text2')";
How can I do to achieve this?
The alert statement is just the example ,and please don't give solutions something like storing alert message into global variable, show the variable's value..etc.
Thanks.
This cannot be done. You cannot change the code inside of a function.
Although Javascript functions are mutable objects, you can only add properties and methods to them, but you can't change the code inside of 'em.
If you want to use the evil eval (as you've specified in the comments), you could convert the function to a string, replace whatever text you want inside the function, and then eval it:
$('#text2').change(function (event) {
eval(
'(' + $('#text1')[0].onchange.toString().replace('valueA', 'valueB') + ')()'
);
});
And here's the fiddle: http://jsfiddle.net/A4w2W/
But, please please please don't do this. This is the worst possible way to write code, ever!!
You should seriously reconsider your approach to this whole matter.
Technically, no. But there are other solutions.
<script type="text/javascript">
<!--
alertvalue = "valueA";
//-->
</script>
<input id="text1" type="text" name="text1" onchange="alert(alertvalue);" /><br />
<input id="text2" type="text" name="text2" /><br />
<script type="text/javascript">
$('#text2').change(function(event) {
alert(alertvalue + '. This is text2');
});
</script>
There is already the html() function in jQuery.
The problem I am having with this function is that, in its returned html string, all the self-closing / are stripped off from the elements. For example,
<div>
<input type="text" name="textbox1" value="" />
</div>
Becomes:
<div>
<input type="text" name="textbox1" value="">
</div>
I know this is normal for this function since this is valid in html.
But I would like to have a function that returns valid xml so that the / is still there in the returned string.
It seems jQuery itself does not provide such a function, so I wonder if anyone knows of any plugin that can make this possible.
Thanks in advance.
I think you are misconceiving how browsers interpret HTML. They don't keep a copy of your source file and modify it according to your Javascript. Rather, a browser reads your HTML and parses it into a DOM representation. This corrects any mistakes you may have made in your HTML. When you try to get the HTML of an element, the element is converted to a string according to the current DOCTYPE. Since you probably have an HTML doctype (it's quite hard to get a browser to genuinely treat your document as XHTML), you get HTML returned to you.
Doing this in Javascript is almost certainly not the way to go.
I think this is what I need.
Thank you very much for everyone's reply.
http://code.google.com/p/jquery-clean/
UPDATE 1: I thought this plugin would work but actually it does not. The way I use it is that, I pass it the html string returned by html() and let it fix the tags which do not properly self-close.
However, the way it corrects the tags is not what I need (seems like a bug).
For example, passing it the following html:
<div><input type="text" id="txt1" name="txt1"><label for="txt1">TextBox1</label></div>
It gives:
<div><input type="text" id="txt1" name="txt1"><label for="txt1">TextBox1</label></input></div>
Rather than:
<div><input type="text" id="txt1" name="txt1" /><label for="txt1">TextBox1</label></div>
UPDATE 2: The bug I mention above is already fixed. This plugin works now. If you want to test it out, feel free to paste your html in this page and see if it works for you:
http://www.antix.co.uk/Content/Demos/jQuery-htmlClean/Test.htm
You could try using the native .innerHTML property (you cen get the native element using .get() in jQuery).