I am not sure if I understand this correctly.
The following example changes form action depending on a radio button selection. Then a javascript submit is executed.
I tried to build the whole thing after the revealing module pattern.
var myModule= (function () {
function makeSubmit() {
document.getElementById('form').addEventListener('submit', function(event){
event.preventDefault();
var form= document.getElementById('form'),
datasetURL = document.querySelector('input[name = "dataface"]:checked'),
actionURL = datasetURL.dataset.url,
searchterm= document.getElementById('searchterm').value,
submit;
(datasetURL.id == "db-01") ? submit = actionURL+searchterm: submit = actionURL;
form.action = submit;
form.submit();
});
}
return {
search: function () {
makeSubmit();
}
};
})();
$(document).ready(function () {
myModule.search();
});
My question is now whether this procedure is so correct.
Basically it works.
In this case you can pass private function as reference
return {
search: makesubmit
}
And invoke it as you did.
Related
I have this cute class:
validations.js
var Validation = function () {
var load= function () {
$.validator.addMethod("noweirdstuff", function (value, element) {
return !(/\W/.test(value));}, "Username has invalid characters. Only letters, numbres & underscores allowed.");
$.validator.unobtrusive.adapters.add("noweirdstuff", function (options) {
options.rules["noweirdstuff"] = true;
if (options.message) { options.messages["noweirdstuff"] = options.message;}
});
}
return {
init: function () {
load();
}
};
}();
validations.js is bundled and minified with all javascript code into single file. Then, I'm using per page script to load only required code. In this case:
Validation.init();
But it doesn't seem fire the validation. I'm 100% sure that Validation.init() is being called.
It only works when I take it outside:
validations.js
var Validation = function () {
var load = function () {
// goodbye adding validation
}
return {
init: function () {
load();
}
};
}();
$.validator.addMethod("noweirdstuff", function (value, element) {
return !(/\W/.test(value));}, "Username has invalid characters. Only letters, numbres & underscores allowed.");
$.validator.unobtrusive.adapters.add("noweirdstuff", function (options) {
options.rules["noweirdstuff"] = true;
if (options.message) { options.messages["noweirdstuff"] = options.message;}
});
Why?
This is because you are registering your custom script validators after the page is loaded. The validation rules are applied to the whole document once unobtrusive validator loads, if your rules and validators haven't been added to the stack by then, they will be ignored.
I believe you could call $.validator.unobtrusive.parse(document) after you have added your rules and validators, I'm not 100% sure this would work or if would apply validators twice.
Edit: Rephrased the answer
Edit: Added possible solution
i wanted to get the value of my textbox in javascript. this is my javascript-
<script type="text/javascript">
var submitted = false; var type;
window.onbeforeunload = function () {
if (!submitted) {
return "Are you sure you want to leave this page, your test will not be saved?"+type;
}
};
document.getElementById('form1').onsubmit = function () {
type=document.getElementById('TextBox1').value;
submitted = true;
};
</script>
no matter what i type it does not give me the value of textbox1
<script type="text/javascript">
var submitted = false; var type;
$(document).ready(function ()
{
$('#form1').submit(function ()
{
type = document.getElementById('TextBox1').value;
submitted = true;
});
window.onbeforeunload = function ()
{
if (!submitted)
{
return "Are you sure you want to leave this page, your test will not be saved?" + type;
}
};
});
</script>
if you want to display type's value in alert box then,change if(!submitted') to if(submitted) and you will receive an alert with type value.hope this will do.
This looks like just a logic problem:
When you run onsubmit, it sets submitted to true, and then it runs onbeforeunload. Right now it it basically only returns the input value if you've not run onsubmit. If you take the ! out of (!submitted), it will give you an alert with the input's value.
I can not seem to find the code to disable a javascript function. What I want to do is have a javascript function and then I want to disable it. Here is the code:
<script>
var fooFunc = function fooFunction() {
alert("HELLO");
};
$(document).ready(function() {
fooFunc.disable();
});
</script>
<button onclick="fooFunc()">Button</button>
Basically, when the button is click the function should not work, it should be disabled. Thanks
"Disabling" fooFunc is the same as setting it to an empty function (not to null--that will cause an error when it is called the next time). In this case:
$(document).ready(function() {
fooFunc = function() { };
});
But I don't see how this is different from simply removing the onclick handler from the HTML element.
If you want the ability to disable/re-enable the function, you can write it like this:
fooFunc = function() {
function _fooFunc() {
if (!enabled) return;
alert("HELLO");
}
var enabled = true;
_fooFunc.enable = function() { enabled = true; };
_fooFunc.disable = function() { enabled = false; };
return _fooFunc;
}();
If you want to extend this to allow any function to be enabled/disabled, you can write a higher-order function, which takes any function as a parameter, and returns a function with enable and disable methods attached to it:
function disablable(fn) {
function inner() {
if (!enabled) return;
fn();
}
var enabled = true;
inner.enable = function() { enabled = true; };
inner.disable = function() { enabled = false; };
return inner;
}
Now you can define fooFunc as
var fooFunc = disablable(function fooFunction() {
alert("HELLO");
});
and the rest of your code will work as you want.
You can access the onclick property of the element..
<button id="id" onclick="fooFunc()">Button</button>
<script>
document.querySelector('#id').onclick = '';
</script>
If you don't want the function to work at all and be totally disabled then use the below.
If you want the function to work only under certain conditions then you will need if/else statements so it will work only when the conditions that you have set are met.
$(document).ready(function(){
$("button").onclick(function(event){
event.preventDefault();
});
});
You were going to define it back to undefined or null.
fooFunc=undefined;
You Should be doing this :) Change function definition on very first run and you are good to go.
<! DOCTYPE html>
<html lang="en">
<body>
<script>
var fooFunc = function() {
alert("HELLO");
fooFunc = function(){};
};
var enablefooFunc = function()
{
fooFunc = function() {
alert("HELLO");
fooFunc = function(){};
};
}
</script>
<button onclick="fooFunc()">Run once and Disable FooFunc</button>
<button onclick="enablefooFunc()">Enable FooFunc</button>
</body>
</html>
Is it possible to change the order of events to invoke alert function with message Huh? first and only then next alert with 'Yeah!' message?
<div class="elem" onclick="alert('Yeah!')"></div>
My jQuery code.
$('.elem').click(function () {
alert('Huh?');
})
Link to jsFiddle: http://jsfiddle.net/84Lyq3n9/
How about this:
var inline_click_handler_src = $('.elem').attr('onclick');
var inline_click_handler = new Function('e', inline_click_handler_src);
$('.elem').removeAttr('onclick');
$('.elem').click(function () {
alert('Huh?');
inline_click_handler();
});
[Edit] Or without mucking with markup content:
var el = $('.elem').get(0);
var inline_click_handler = el.onclick;
el.onclick = null;
$('.elem').click(function () {
alert('Huh?');
inline_click_handler();
});
[One more edit] In case your inline click handler uses this, use function.call(), to set the execution context:
var el = $('.elem').get(0);
var inline_click_handler = el.onclick;
el.onclick = null;
$('.elem').click(function () {
alert('Huh?');
inline_click_handler.call(el);
});
But you can do it with many ways.
First you can remove the attribute "onclick".You can do it with javascript.
$('.elem').removeAttr("onclick");
$('.elem').click(function () {
alert('Whatever you want');
alert('Huh?');
})
Here is a link: http://www.w3docs.com/learn-javascript/javascript-events.html
So when someone hits Reply, I am attempting to pop-up a form to type your response. Once the form is submitted, it disappears until the next time you hit Reply.
This is working except after the 1st time, I am submitting the information twice. If I do it a third time, the form submits three times. Essentially what is happening is the previous form doesn't seem to be resetting after I hide it again.
I checked this website/google and have tried using reset() but it didn't work. Below is the code:
$(document).on('click', '.secretfeed button', function () {
var message_id = $(this).attr('name');
$(".comment_box").show();
$("#m_id").val(message_id);
var value = document.getElementById("m_id").value;
$('#comment_form').submit(function (e) {
e.preventDefault();
var commentData = $(this).serialize();
$.post('../../process_comment.php', commentData, processData);
function processData(data) {
//$('comment_form').reset()
$(".comment_box").hide();
$('#comment_form')[0].reset();
RefreshFeed();
}
});
});
Rather than initializing the submit function on every click, move it outside the click function. jQuery may be creating an instance of it for each click.
$('#comment_form').submit(function (e) {
e.preventDefault();
var commentData = $(this).serialize();
$.post('../../process_comment.php', commentData, processData);
function processData(data) {
//$('comment_form').reset()
$(".comment_box").hide();
$('#comment_form')[0].reset();
RefreshFeed();
}
});
$(document).on('click', '.secretfeed button', function () {
var message_id = $(this).attr('name');
$(".comment_box").show();
$("#m_id").val(message_id);
var value = $("#m_id").val();
});
The alternative is to unbind the click function before reusing it.
We want a reusable way to handle the state. We will save the state of the button in a boolean which gets turned on and off depending on the status of the request. The pattern is the following:
var isSending = false;
function onSubmit() {
isSending = true;
// Send data
}
function onComplete() {
// done sending data
isSending = false;
}
if (!isSending) {
onSubmit();
}
// When data sending is finished:
onComplete();
The above can be encapsulated in a more functional way that uses promises to manage the state. (jQuery AJAX functions all return a promise-like object):
function oneAtATimeFunction(promisedFunction) {
var pendingPromise;
function reset() { pendingPromise = null; }
return function() {
if (pendingPromise) { return pendingPromise; }
pendingPromise = promisedFunction.apply(promisedFunction, arguments)
.always(reset);
return pendingPromise;
}
}
function submitForm() {
return $.ajax({
url: '/foo',
method: 'POST',
data: { data: 'from form' }
});
}
$('#submit-button').on('click', oneAtATimeFunction(submitForm));
Adding a little flare to the UI We can add a way to turn on and off the submit button. First we will define a helper function to handle the on and off state:
function buttonEnable(enabled) {
$('#submit-button').attr('disabled', !enabled);
}
buttonEnable(false); // disable the button
buttonEnable(true); // enable the button
Putting it all together:
function onClick() {
buttonEnable(false);
return onSubmit()
.always($.proxy(buttonEnable, null, true));
// The above is also the same as:
// .always(function() { buttonEnable(true); });
}
$('#submit-button').on('click', oneAtATimeFunction(onClick));
To see this in action here is a JSBin example.