User edited javascript - javascript

So what I want is to have a html text field where someone can type in a bit of JavaScript code, and then some kind of function that will dynamically add it into the script tag of my webpage. Any ideas?
NOTE: I don't want anything saved permanently to the server, but I do want the user-generated js to "work" and interact with my current scripts.

eval (string) will evaluate and excute the javascript code.

Using jQuery:
$(document).ready(function () {
$('button').click(function () {
eval($('input').val());
});
});
Working example: http://jsfiddle.net/JL9EU/

Create a form, bind a handler to the submit event. Within that handler, execute the code and return false.

Related

How to run a Javascript/Jquery Function using both $(document).ready(function() and Another Event Function?

I'm not a javascript/jquery coder, and not sure if what I'm trying to do is possible.
I have a html/php/ajax form that is updated an sql database as the user fills it out. As they fill the form, there is a progress bar ran by javascript/jquery that updates as the user types in the input. The start of the function looks like this:
$("#update input").keyup(function() {
This works great. My problem is when the page is reloaded. My code is pulling sql data from the database to fill the value of every input on the page that has a value so that a user can come back and completely the form later. When the user reloads the page, the only way for the script to activate is if the user types in an input field.
I thought I would fix the issue by changing the my initial javascript/jquery function with $(document).ready(function() . This caused the script to only run when the page was loaded and not when the form was being filled out. I need both the script to run on page ready, and when a user is typing in the input filled. Is there a way I can run both $(document).ready(function() AND $("#update input").keyup(function() { simultaneously? Or is there a better why to accomplish this? Thanks!
Let me know if I need to post more code.
Here's a generic approach attaching declared functions to events.
function handler (e) {}
element.addEventListener('click', handler);
You're free to call handler everywhere, also inside $(document).ready, or if there's no other code in your DOMReady handler, you can just pass a reference as an argument:
$(document).ready(handler);
In your specific case you most likely want something like this:
$(document).ready(function () {
function handler (e) {...}
handler();
$("#update input").keyup(handler);
});
If the handler function uses the event object (e in the example), in modern browsers it's also available as a global event object, or in jQuery, e.originalEvent. The object doesn't exist if there's no event fired, though, in that case you've to pass a fake event object, containing the provided properties, to the handler, if it is needed.

__doPostBack is not triggering from external Js file

When i tried to trigger __doPostBack() manually from external Js file is not triggering.
$(document).ready(function () {
$("#tabsids a").click(function () {
__doPostBack('<%= btntrigger.ClienID%>', '');
});
});
You need the name attribute of the HTML element of the button you wish to click as the first argument to __doPostBack(). HOw you will get that in your actual case is a different matter, but you cannot use server code blocks ()<%=%> outside of ASP context (i.e., outside of aspx, ascx files). Perhaps you can consider a partial ID selector with jQuery, something like
$("input[id$='btntrigger']").attr("name")
where input is the element type, so you may need to change it.
YOu can also simply try the click() method of the jQuery wrapper that you get, perhaps it will do the job.

Call JavaScript function when button loaded by ajax is clicked

I have an html form that loads its contents through ajax and includes buttons that, when clicked, should execute a JavaScript function that is defined in the html page's script tag. SO: Button is loaded through ajax (works), but when button is clicked, it doesn't trigger the desired action and doesn't trigger a JavaScript error in Firebug. How does one get the onclick signal of a bunch of buttons loaded through ajax to bind to an already existing JavaScript function?
EDIT: I should have noted also that I am not using JQuery. I am willing to do so if it is the only way, but otherwise, I would prefer to use only native JavaScript.
EDIT2: My problem was a bit more involved, but as was stated in the chosen answer, you should be able to set the onclick event handler in the php script before sending the data through ajax. If you have a data-heavy response and want to reduce bandwidth, you might consider doing everything client-side, but I find it easier in most situations just to set the onclick attribute in the php script.
Your dynamically generated button could have an inline event bound to it. When generating the button, simply make sure it has an onclick="alreadyExistingFunc();" and the page will happily execute it.
Alternatively, when your AJAX data is finished writing itself into the document, find the new button(s) and bind the event to them:
function ajaxSuccess()
{
document.getElementById('newButtonIdHere').onClick = function() {
alreadyExistingFunc();
}
}
That should do the trick. Also note that if you ever "need" a small part of jQuery to do something (like selectors or event handling), you can almost always do it without loading the whole library.
Append/insert the HTML (retrieved AJAX response) to DOM and bind click event to it:
function alreadyExistingFunc() {
alert('button is clicked!');
}
var ajax_data ="<button id='my-button'>My Button</button>";
$('body').append(ajax_data).find('#my-button').on('click', function(e){
alreadyExistingFunc();
// some more code...
});
OR:
$('body').append(ajax_data).find('#my-button').on('click', alreadyExistingFunc);
You could also use a callback:
function getAjaxContent(callback) {
$.ajax({url: "url"}).done(function() {
callback(data);
});
}
getAjaxContent(function (data) {
//ajax content has been loaded, add the click event here
}

JavaScript will not run a second time

I am running a script using $(document).ready() it is performing the way I want it to on load up, however, the same script needs to be ran when an html select control is changed.
What I need ultimately is for the filter and sort to run on initial load with sorting on Low to High, and then after the page is loading the user should be able to select any select control and filter and sort as they wish.
Go to http://webtest.ipam.ucla.edu to view the code and on the bottom of the page you can download the folder with all of the files.
How do I fix this?
You can put all your reusable logic into a function:
function myPrettyJavaScriptLogic () {
// All the code that you want to reuse in here
}
Then you can call the above function both from document.ready() and also from the onchange handler of your select control.
Create a function outside of your doc ready closure and call it when you need to. Example is jQuery but doc ready is the same event:
var doSomethingCool = function( coolStuff ) {
// Do cool stuff
}
$(function(){
doSomethingCool( $(this) );
$('#selectControlId').change(function(e){
doSomethingCool();
});
});
Since you are referencing the .ready function I'm assuming you are actually using jQuery.
$(document).ready() or jQuery(document).ready()
Anything within the ready() function will only be called once - when the page is loaded. It waits until the entire DOM is loaded before executing that code.
You can extract out your functionality to a separate function to get kicked off based on your select control changing.
You may benefit from reading a jQuery tutorial I wrote the other week:
http://chadcarter.net/jquery-goodness/
Also, the actual .change event in the jQuery API is here:
http://api.jquery.com/change/
Assuming you want the functionality to be called when the page loads and when the option is changed you will want to create a new function and have that function called inside of both the .ready and the .change functions.
Hope this helps!
put your script in a Named function. call it in domready and select.change().
You will need to set up a handler for the select box's onChange event. What I would do is pull out the code you need to execute into a separate function and then do something like
function dostuff(){
//do whatever you need to
}
$(document).ready(function() {
dostuff();
}
<select onchange"dostuff()" >... </select>
Note this was quick and dirty, just to give you an idea.
Check out this link for more about select's onchange.
If you are using jQuery, which I will assume you are because of this syntax, you just have to bind the event onchange to the element.
$("element").bind("change", function() { /* your logic */ });
You have to run this code after the element is rendered. If you place this code inside the $(document).ready there will be no problem. but the whole page will have to load before the even is bound.
So you can do the following:
<select id="sel">
<option>A</option>
<option>B</option>
</select>
Then bind the event change.
$(function() { /* equivalent to document.ready */
$("#sel").bind("change", function() {
/* code that runs when the selection change */
});
});
Thank you all for your help, this is now fixed. The way i did it was to encapsulate the $(function(){}) in another function (filtersortProcess()) and then created another script that autoselects the Low to High option and calls filtersortProcess() on windows.load.
Within the $(function(){}) I added a variable (complete) and set it to 1 when it goes within the actual filter process, then after the filter process (if the code exits before completing the process) I check for the complete variable and do a simple filter and sort on the data and with all of this it works great.
Thank you again.

triggering a controls event via javascript

im trying to figure out how to trigger a control's event from a javascript function (without touching the actual control itself)
say i have this textbox...
<input type="text" value="" id="my_textbox" onclick="alert('!');" />
then say i was trying to call its onclick event via javascript...
function TriggerTextboxOnClick()
{
//... call the onclick event of 'my_textbox'
}
p.s. I'm not actually trying to pop-up an alert box, I've simplified it for illustrations sake
You could just call document.getElementById("my_text_box").onclick(), see also: http://jsbin.com/ixuwo4.
Bouke's solution works.
In general, you may want to do somthing like this instead as a good practice:
<input id="my_textbox" onclick="my_textbox_onClick()" />
...
function commonLogic() {
// Logic that's common to both the onclick event and the *other* code
}
function my_textbox_onClick() {
// This function should only contain logic that is triggered by a click on the textbox
commonLogic();
}
couple of things:
doing someting via the inline onclick attribute as you've got in your example is not the best way. Attaching event handlers in script blocks is better for accessibility and cleaner, maintainable code.
if you're using a library like jQuery already then let the library handle it for you. see code below:
//assuming using jQuery
$('#my_textbox').click(function(){
//do stuff here
});
//firing the event in some other function
function TriggerTextBoxOnClick(){
//do stuff here
$('#my_textbox').click();
}
Ref: More info on inline click handlers: http://www.quirksmode.org/js/events_early.html
You can do the same as the jQuery code with plain old js too:
element.onclick = doSomething;
if (element.captureEvents) element.captureEvents(Event.CLICK);
Read this for more info on doing this with plain JS: http://www.quirksmode.org/js/introevents.html

Categories

Resources