I have form (in a ColdFusion program -- not that it matters) with two submit buttons (they look quite different from each other) which submits to different programs depending on which button is clicked. The form looks like this:
<form name = "pers3aa"
action = ""
method = "post"
onkeypress = "return event.keyCode != 13;"
onsubmit = "return subpers3aa('#coltop#');">
Each button calls a Javascript function to set the action -- they look like this:
<input type = "Submit"
name = "subpers4"
class = "submitbut"
value = "Submit"
onclick = "persaasubmit('person4aa.cfm')" >
and
<input type = "Submit"
id = "delbut"
class = "onoffbut"
value = "Delete this Value"
onclick = "persaasubmit('persdel.cfm')">
The javascript function persaasubmit is:
function persaasubmit(target) {
document.pers3aa.action = target;
}//end function persaasubmit
So far, so good -- this works. However, in another program I have a different form "xrefform", which I submit with a similar function:
function aasubmit(target) {
document.xrefform.action = target;
}//end function aasubmit
This situation occurs all throughout my system, and the various javascript submit functions are proliferating. So I tried to combine them by sending the form name as an argument:
function generalsubmit(formname, target) {
document.formname.action = target;
}//end function generalsubmit
This does not work. I infer that Javascript cannot find a form called "formname" so it doesn't submit anything. I'm thinking there probably is syntax for getting Javascript to submit the formname that was passed to it, but I don't know what that might be. Can anyone help?
In object document there is a 'forms' array. You can access a specific form :
document.forms['myform']
You're on the right track; however, that's not how dot notation works in JavaScript.
Consider this:
var someVar = "Foo Bar",
someObject = { someVar: someVar };
// someObject = {"someVar": "Foo Bar"}
someObject[someVar] == undefined
// Resolves to the 'Foo Bar' property in someObject
someObject.someVar == 'Foo Bar'
// Resolves to the 'someVar' property in someObject
someObject['someVar'] = 'Foo Bar'
// Resolves to t 'someVar' property in someObject
This should work as a drop-in replacement for the function in your question:
function generalsubmit(form, target) {
form = document.forms[form];
if (form) {
form.target = target;
}
}
Related
I did a bunch of buttons on a navbar. These buttons can trigger different articles or lesson in two languages from side to side.
Later, I found that this is troublesome when I try to search for a specific article. So I decided that I'll add an input text bar to take my input and trigger a javascript function that I want.
I simplified the numbers in this post, but this is the core of the script. I named the functions with 4 digits numbers MMDD so I wish that I can type in a box 0312 and the function 0312 get executed.
However, I cannot seem to get it to work. Is that even possible in javascrip? If not what approach do you recommend?
function fr01() {
document.getElementById("fr01").innerHTML = "text here will appear in french"
}
function en01() {
document.getElementById("en01").innerHTML = "text here will apear in english"
}
function myFunction01() {
fr01();
en01();
}
function myFunction() {
var x = document.getElementById("myInput").value;
function 'x'
}
<input type="text" id="myInput" oninput="myFunction()">
<button onclick="myFunction01()">CHAPTER01</button>
the top part works perfectly fine and in realtime, when I press the corresponding button it shows both sides, when I try to type in number I get this error message
myFunction is not defined at HTMLInputElement.oninput
Didn't I already define it in the top portion?
Thank you for taking the time to read this.
Do call functions dynamically based on for example a text value, then you could create a map which connects a string to a function. An object is very similar to this. It has properties, which can be strings, and a value, which can be functions.
const actions = {
'foo': function() {
// Do something.
}
};
With this pattern you can create a list of valid options and the connect the corresponding functions that come with the list.
Now let's say you have a string. With that string you can select a function from the object with the bracket notation.
const string = 'foo';
const action = actions[action];
If a value is found, then action will now be a function. Otherwise it will be undefined.
The snippet below demonstrates this principle.
function omg() {
console.log('omg');
}
function bark() {
console.log('bark');
}
const actions = {
'0312': function() { // Regular function.
console.log('Hello')
},
'0420': () => { // Arrow function.
console.log('Wow')
},
'1360': () => console.log('Vroom'), // Arrow function variation.
'1337': () => { // Arrow function that calls two other functions.
omg();
bark();
},
'7331': [omg, bark] // Array with function references.
};
const form = document.querySelector('#form');
const actionField = document.querySelector('#action');
form.addEventListener('submit', event => {
const selector = actionField.value;
const action = actions[selector];
if (typeof action === 'function') {
action();
}
if (Array.isArray(action)) {
action.forEach(subAction => {
subAction()
});
}
event.preventDefault();
});
<form id="form">
<label for="action">Try me (0312, 0420, 1360 and 1337 will work)</label>
<input type="text" id="action" />
<button type="submit">Execute</button>
</form>
Im trying to use global variables for my js and its like below code
var fullName = document.getElementById("elementId").value;
var nameFormat = /^[A-Za-zÀ-ú]+ [A-Za-zÀ-ú]+$/;
but when I try to use it inside a function function dosen't work .So I just pasted the var fullName into the function and then it works. So please tell me can I assign values into a global variable via document.getElementById("elementId").value;
When I try to use nameFormat inside function it works either declare inside or outside.
This is the full code
//common js regular expressions
var emailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var nameFormat = /^[A-Za-zÀ-ú]+ [A-Za-zÀ-ú]+$/;
//global variables
var fullName = document.getElementById("jsname").value;
var email = document.getElementById("jsun").value;
function validateForm() {
//var fullName = document.getElementById("jsname").value;
//onsubmit full name validation
if (!(fullName.match(nameFormat))) {
document.getElementById("pidnamevalidate").innerHTML = "Name should be in a valid format";
document.getElementById("pidnamevalidate").style.color = 'green';
return false;
//onsubmit email validation
} else {
return true;
}
}
It is fine for "nameFormat" to be a global variable, but it looks like you're getting fullName from an editable form field. If you set fullName outside of the validateForm function then you are setting it to the initial value of the field (or as #RobG mentioned, possibly trying to get the value of an element that doesn't yet exist in the DOM which would result in an error). Setting fullName inside validateForm will get its value at that point in time which I assume is what you want.
I have this function which is as follows:
function detectfieldchange(parent = '#slidesContainer', field = '.slide-type-selector') {
$(parent).on('change', field, function(event) {
$this = $(this);
console.log($this);
fieldtype = '.' + $this.val() + '-options';
allfieldtypes = $this.closest('.sliderow').find('.slide-type-properties');
allfieldtypes.fadeOut(300);
$this.closest('.sliderow').find(fieldtype).fadeIn(300);
});
}
and the issue is I want to run the function like this( As follows ) so that I can pass in any selectors I want but this does not work:
detectfieldchange(var1, var2);
Both var1 and var2 are defined variables with CSS selectors in term of strings like this var var1 = '.parent'; etc
While If I simply do a simple call to activate the default values of function params the function works perfectly like this:
detectfieldchange();
So, Having explained this, What could be a possible solution to achieve this. And one thing more to note here is that 'fields' are going to be dynamically added to the page that's why event delegation is necessary.
I'm creating a custom combobox which uses jQuery validator.
At first they all are gray except the first (it means Country). When I choose 'Slovenská republika' the second combobox is enabled.
They all are instances of a a custom autocomplete combobox widget.
To enable the validation I use this code (which is called within _create: function(){..})
There you can find $.validator.addClassRules(); and $.validator.addMethod(). I also added the appropriate class so it really does something.
_registerCustomValidator: function(){
var uniqueName = this._getUniqueInstanceNameFromThisID(this.id);
var that = this;
console.log(this.id);//this prints 5 unique ids when the page is being loaded
$.validator.addMethod(uniqueName, function(value,element){
if(!that.options.allowOtherValue){
return that.valid;
}
console.log(that.id);//this always prints the ID of the last combobox StreetName
return true;
}, "Error message.");
var o = JSON.parse('{"'+uniqueName+'":"true"}');
$.validator.addClassRules("select-validator", o);
}
//this.id is my own property that I set in _create
Problem: When I change the value of any instance of combobox, it always prints the ID of the last instance StreetName, but it should belong to the one that has been changed.
I thought it might be because of registering $.validator.addMethod("someName",handler) using such a fixed string, so now I pass a uniqueName, but the problem remains.
Therefore the validation of all instances is based on the property allowOtherValue of the last instance.
I don't understand why it behaves so. Does anyone see what might be the problem?
EDIT:
see my comments in the following code
_registerCustomValidator is a custom function within a widget factory.
//somewhere a global var
var InstanceRegistry = [undefined];
//inside a widget factory
_registerCustomValidator: function(){
var i=0;
while(InstanceRegistry[i] !== undefined) ++i;
InstanceRegistry[i] = this.id;
InstanceRegistry[i+1] = undefined;
var ID = i; //here ID,i,InstanceRegistry are correct
$.validator.addMethod(uniqueName, function(value,element){
//here InstanceRegistry contains different values at different positions, so its correct
console.log("ID=="+ID);//ID is always 5 like keeping only the last assiged value.
var that = InstanceRegistry[ID];
if(!that.options.allowOtherValue){
return that.valid;
}
return true;
}, "Error message");
var o = JSON.parse('{"'+uniqueName+'":"true"}');
$.validator.addClassRules("select-validator", o);
}
It looks like a sneaky combination of closure logic and reference logic. The callback in $.validator.addMethod is enclosing a reference to this which will equal the last value of this when $.validator.addMethod. (Or something like that?)
Glancing at your code, it's not clear to me what this is in this context. So I can't really offer a concrete solution. But one solution might be to create some kind of global registry for your thises. Then you could do something along the lines of:
_registerCustomValidator: function(){
var uniqueName = this._getUniqueInstanceNameFromThisID(this.id);
$.validator.addMethod(uniqueName, function(value,element) {
var instance = InstanceRegistry[uniqueName];
if(! instance.options.allowOtherValue){
return instance.valid;
}
return true;
}, "Error message.");
var o = JSON.parse('{"'+uniqueName+'":"true"}');
$.validator.addClassRules("select-validator", o);
}
The registry could be keyed to uniqueName or id, just so long as it is a value getting enclosed in your callback.
Sorry for the long winded title, but I think it summaries my problem
I have created a jsfiddle to cut down and create a simplified problem of my dilemma
http://jsfiddle.net/afw6k/3/
<input id="txtA"/>
<!-- after setupOnclick is executed my onlick for txtA should be onclick="someObj.log("Clicked!")"-->
<script>
function someObject(field){
this.field = field;
this.log = function(msg){
if(this.field.value != "") this.field.value += ", ";
this.field.value += msg
}
this.setupOnlick = function(){
field.onlick = function(){//So how do I pass this (as in someObject) to this?
this.log("Clicked!"); //As if I have written someObj.log("Clicked!");
}
}
}
var someObj = new someObject(document.getElementById("txtA"));
someObj.setupOnlick();
</script>
I'm not trying to simply write something to a textbox when clicked, but the above is a simplified version of what I am trying to accomplish here.
Passing this (the object) into an objects functions nested function
Or is there a far better way to accomplish this?
Save this in a variable:
this.setupOnlick = function(){
var theObj = this;
field.onlick = function(){//So how do I pass this (as in someObject) to this?
theObj.log("Clicked!"); //As if I have written someObj.log("Clicked!");
}
}
The value of this is just a value, so it can be copied to another variable. The variable "theObj" will remain in scope of the "click" handler when it runs.