OK, so I have a page that has the following, the function creates a drop down populated with information as q15:
The below code fires when a user selects an option from the drop down q14:
onchange="configureDropDownLists(this,'q15')"
The same function is called when the page loads using the onload option:
<body onload="configureDropDownLists('q14','q15');check();">
These are the two functions used:
function configureDropDownLists(q14,q15) {
if (langu.languag=='English'){
var not = new Array('');
var australia = new Array('Perth','Brisbane','Sydney (Frenchs Forrest)','Sydney (Auburn)','Melbourne','Adelaide','Auckland');
}
switch (q14.value) {
case '':
document.getElementById(q15).options.length = 0;
for (i = 0; i < not.length; i++) {
createOption(document.getElementById(q15), not[i], not[i]);
}
break;
case '1':
document.getElementById(q15).options.length = 0;
for (i = 0; i < australia.length; i++) {
createOption(document.getElementById(q15), australia[i], [i+1]);
}
break;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
Finally, this messy code is in the header section of the page:
<script type="text/javascript">
window.results = ["<?php echo implode ('","', $results); ?>"];
</script>
<script type="text/javascript">
function selected(){
var res = 'test';
document.getElementById("test").value = res;
alert(res);
}
</script>
<script type="text/javascript">
var langu = {
languag : '<?php echo $lang; ?>'
}
</script>
<script src="main.js" type="text/javascript"></script>
<script src="javascripts/scriptaculous.shrunk.js" type="text/javascript" charset="ISO-8859-1"></script>
<script src="javascripts/page2_validation.js" type="text/javascript"> </script>
The code fires correctly using the onchange call when a user selects q14. In addition, on q14 there is PHP code that auto selects an option if the user has visited the page before - in this instance I want the function to run and create q15 when the page loads, hence I'm trying to use onload, however, I simply cannot get it to fire.
Any ideas and suggestions welcomed, please!
H.
"this" is referring to the select so you need to pass a select object
Do this instead of inline
window.onload=function() {
configureDropDownLists(document.getElementById('q14'),'q15');
check();
}
You have passed a string as q14 when you intended to pass an element.
Having said that, this would be a lot easier to debug if you gave us a jsfiddle.net workspace to tinker with.
Related
My lack of experience with both Wordpress and Javascript is tripping me up.
I have a Wordpress page that has a Jotform embedded using this tag:
<script type="text/javascript" src="https://form.jotform.com/jsform/FORMCODE"></script>
But I have a value coming into my Wordpress through the URL that I need to pass along in the embedded Jotform's URL. I cannot figure out how to do that. Do I want to use PHP? Javascript?
I tried this, which didn't work at all:
<script type="text/javascript">
function getURL(){
let paramString = urlString.split('?')[1];
let params_arr = paramString.split('&');
let pair = params_arr[0].split('=');
return "https://form.jotform.com/jsform/230391120310032?coursecode=" + pair[1];
}
</script>
<script type="text/javascript" src="getURL();"></script>
Thanks for any help!
To add a javascript code to a WordPress page you need the page id else the js code will be on all the pages.
You can either add the js code to the head of the page likes so:
add_action('wp_head',function () {
// 10 is the page id;
if (is_page ('10')) {
?>
<script type="text/javascript">
function getURL(){
let paramString = urlString.split('?')[1];
let params_arr = paramString.split('&');
let pair = params_arr[0].split('=');
return "https://form.jotform.com/jsform/230391120310032?coursecode=" + pair[1];
}
</script>
<script type="text/javascript" src="getURL();"></script>
<?php
}
}
);
Then put the js code on the footer like so:
add_action('wp_footer',function () {
// 10 is the page id;
if (is_page ('10')) {
?>
<script type="text/javascript">
function getURL(){
let paramString = urlString.split('?')[1];
let params_arr = paramString.split('&');
let pair = params_arr[0].split('=');
return "https://form.jotform.com/jsform/230391120310032?coursecode=" + pair[1];
}
</script>
<script type="text/javascript" src="getURL();"></script>
<?php
}
}
);
Whichever snippet you pick should be added to your theme functions.php or code snippet plugin if you have one
I have two functions in external file, then I call A and B in HEAD script, and A can be run and B can't, but if I put B into head script, B also can be run. I am not sure why, what can I do?
HTML:
<head>
<script language="JavaScript" type="text/JavaScript">
<!--
function B(id) {
var selected = document.getElementById(id)
var arr = selected.options[selected.selectedIndex].text.split(" ");
var value = ""
for (var i = 1; i < arr.length; i++) {
if (value != "") value = value + " ";
value = value + arr[i];
}
return value;
}
function save() {
A("msg");
var x = B(id);
}
-->
...
<script type="text/JavaScript" src="js/my.js"></script>
</body>
...
my.js:
function A(msg) {
scroll(0,0);
var outerPane = document.getElementById('FreezePane');
var innerPane = document.getElementById('InnerFreezePane');
if (outerPane) outerPane.className = 'FreezePaneOn';
if (innerPane) innerPane.innerHTML = msg;
}
function B(id) {
var selected = document.getElementById(id)
var arr = selected.options[selected.selectedIndex].text.split(" ");
var value = ""
for (var i = 1; i < arr.length; i++) {
if (value != "") value = value + " ";
value = value + arr[i];
}
return value;
}
The safest thing to do is wrap the code in the head in a window.onload handler like this...
<head>
<script type="text/javascript">
window.onload = function(){
// your external files are guaranteed to be loaded now
// you can call A or B
}
</script>
</head>
onload is only fired after all external scripts have been loaded.
Here is a full example...
index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
<script>
function save() {
A()
B()
}
window.onload = function() {
save()
}
</script>
</head>
<body>
The content of the document......
<script src="./external.js"></script>
</body>
</html>
external.js
function A() {
alert('A ran')
}
function B() {
alert('B ran')
}
NOTE: This is better than moving the external script to the head, like the other answers suggest, because external resources loaded in the head block the entire page render until they are loaded.
By leaving the external script at the end of the body tag, the page load will seem faster as the css/html will display immediately. Even if the javascript isn't loaded yet.
Add your external file before the script tag contains your "save" function.
<script language="JavaScript" src = "yourfile.js" type="text/JavaScript">
</script>
<script language="JavaScript" type="text/JavaScript">
function save(){
A();
B();
}
</script>
I have page A, where I have three anchor.
And page B, where I have select #days with values 30,180,365
So when I click on page A an anchor with href like page?v=30 I should jump to page B, where automatically would be selected option with value=30 on select #days.
Is it possible? I guess easiest would be using jquery or something.
Thanks!
EDIT: I have following PHP code for showing values.
<select id="days" name="days">
<?php foreach($prices as $current_days => $details): ?>
<option value="<?php echo $current_days ?>" <?php selected( $subscription_days, $current_days ); ?>>
<?php echo $details['desc']; ?>
</option>
<?php endforeach; ?>
</select>
Taking the function written here for getting the URL vars, all you need is:
$('#days').val($.getUrlVar('v'));
Demo fiddle
Code fiddle
Fetching the Variable is pretty described here: Getting value GET OR POST variable using JavaScript?
Now you only need a Javascript that checks if this Value is set, and then simply manipulates the Select Box.
I dont do stuff like that in pure Javascript. jQuery for Example provides verry good functions for this in their API.
You can use something like
function getParameter(paramName) {
var searchString = window.location.search.substring(1),
val, params = searchString.split('&');
for (var i=0; i<params.length; i++) {
val = params[i].split('=');
if (val[0] === paramName) {
return unescape(val[1]);
}
}
return false;
}
var v = getParameter('v');
if (v) {
$('#days').val(v);
}
You can get the parameter from the URL with JavaScript and set the select to the desired value.
An example using jQuery would be this one:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function selectItem() {
var i = getParam('v');
$('#days').val(i);
}
function getParam(paramName) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
</script>
</head>
<body onload="selectItem()">
<select id='days'><option value='1'>1</option><option value='2'>2</option></select>
</body>
</html>
Something like this should work:
Anchor A
Anchor B
Anchor C
And from your Page B you have to put this script:
function GetQueryStringParams(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
var valueFromUrl = GetQueryStringParams("value");
$("#your-select-id option").each(function()
{
this.selected = (this.text() == valueFromUrl);
});
I have an application that needs to retrieve a value out of a hidden input form field. However, this application has a base page which calls another page that is in an iFrame and then it also can call itself inside another iFrame:
default.asp -> screen.asp (in iFrame)
screen.asp -> a new instance of screen.asp (in iFrame)
document.getElementById('focusValue').value
window.frames[0].document.getElementById('focusValue').value
parent.frames[arrVal].document.getElementById('focusValue').value
When I reference the hidden input form field from default -> screen I can use the standard document.getElementById('focusValue').value;. Then when I'm in the 1st level iFrame I have to use window.frames[0].document.getElementById('focusValue').value;. Then when I'm in the 2+ levels in an iFrame I have to use the parent.frames[arrVal].document.getElementById('focusValue').value;.
A common structure that I'm starting to see is this:
if(document.getElementById('focusValue') == undefined){
window.frames[0].document.getElementById('focusValue').value = focusValue;
console.log('1');
}else if((parent.frames.length -1) == arrVal){
console.log('2');
if (arrVal > 0) {
parent.frames[arrVal].document.getElementById('focusValue').value = focusValue;
}
}else{
document.getElementById('focusValue').value = focusValue;
console.log('3');
}
Now I can certainly do this but outside of writing a novel worth of comments I'm concerned with other programmers(or me 1 month from now) looking at this code and wondering what I was doing.
My question is there a way to achieve what I'm looking to do in a standard form? I'm really hoping that there is a better way to achieve this.
I would suggest you have each page do the work of finding the value you want by calling a method. Basically exposing a lookup interface. Then you only need to call a method on the target page from the parent page. Proper naming will help developers understand what is going on and using methods will simplify the logic.
Or if you only need to get the value from the parent page, then you could register a hook with each page in an iframe using a common interface. Each page can just call that hook to get the value. This prevents your complex logic of determining what level the page is. Something like
iframe1.GetValueHook = this.GetValue;
iframe2.GetValueHook = this.GetValue;
Then each page can just call
var x = this.GetValueHook();
If you have nested pages, you could make this recursive. If you need communication between all pages then use the same approach but with a registration process. Each page registers itself (and it's children) with it's parent. But if you need to do this then you should reevaluate your architecture.
Example:
register.js
var __FRAMENAME = "Frame1";
var __FIELDID = "fieldId";
var __frames = [];
function RegisterFrame(frame) {
__frames.push(frame);
for (var i = 0; i < frame.children.length; i++) {
__frames.push(frame.children[i]);
}
RegisterWithParent();
}
function RegisterWithParent() {
var reg = {
name: __FRAMENAME,
getvalue: GetFieldValue,
children: __frames
};
if(parent != undefined && parent != this) {
parent.RegisterFrame(reg);
}
}
function SetupFrame(name, fieldId) {
__FRAMENAME = name;
__FIELDID = fieldId;
RegisterWithParent();
}
function GetFieldValue() {
return document.getElementById(__FIELDID).value;
}
function GetValueFrom(name) {
for (var i = 0; i < __frames.length; i++) {
if (__frames[i].name == name) {
return __frames[i].getvalue();
}
}
}
index.html
<html>
<head>
<script language="javascript" type="text/javascript" src="register.js"></script>
</head>
<body>
PAGE
<input type="hidden" id="hid123" value="123" />
<iframe id="frame1" src="frame1.html"></iframe>
<iframe id="frame2" src="frame2.html"></iframe>
<script type="text/javascript">
SetupFrame("Index", "hid123");
setTimeout(function () { //Only here for demonstration. Make sure the pages are registred
alert(GetValueFrom("frame3"));
}, 2000);
</script>
</body></html>
frame1.html
<html>
<head>
<script language="javascript" type="text/javascript" src="register.js"></script>
</head>
<body>
<input type="hidden" id="hid" value="eterert" />
<script type="text/javascript">
SetupFrame("frame1", "hid");
</script>
</body></html>
frame2.html
<html>
<head>
<script language="javascript" type="text/javascript" src="register.js"></script>
</head>
<body>
<input type="hidden" id="hid456" value="sdfsdf" />
<iframe id="frame2" src="frame3.html"></iframe>
<script type="text/javascript">
SetupFrame("frame2", "hid456");
</script>
</body></html>
frame3.html
<html>
<head>
<script language="javascript" type="text/javascript" src="register.js"></script>
</head>
<body>
<input type="hidden" id="hid999" value="bnmbnmbnm" />
<script type="text/javascript">
SetupFrame("frame3", "hid999");
</script>
</body></html>
This would be better if you can change it up to use a dictionary/hash tbale instead of loops.
Your best bet will be to set varables named correctly so it's self documenting. Something like this...
var screenFrame = window.frames[0];
var screenFrame2 = parent.frames[arrVal];
var value = screenFrame2.document.getElementById('focusValue').value
This will make it easier to read.
If you really must search frames for a given element, then you should just make your own function to do that and use that function everywhere. Put a lot of comments in the function explaining why/what you're doing and give the function a meaningful name so it will be more obvious to future programmers looking at your code what you are doing or where they can look to find what you are doing.
function setValueByIdFrames(name) {
if(document.getElementById(name) == undefined){
window.frames[0].document.getElementById(name).value = name;
console.log('1');
} else if((parent.frames.length -1) == arrVal){
console.log('2');
if (arrVal > 0) {
parent.frames[arrVal].document.getElementById(name).value = name;
}
} else {
document.getElementById(name).value = name;
console.log('3');
}
}
<div id="example">
</div>
<script type="text/javascript">
function insert() {
var data = '<script type="text/javascript"> function test() { a = 5; }<\/script>';
$("#example").append(data);
}
function get() {
var content = $("#example").html();
alert(content);
}
</script>
INSERT
GET
</body>
</html>
what i want to do:
when i click on insert, i want to insert this code into example div:
<script type="text/javascript"> function test() { a = 5; }<\/script>
when i click on get, i want to get that code, which i inserted there.
but when i click on insert, and then on get, there's no code.. where is problem ? thanks
According to your comment to Adam Bellaire, you want the script tag to display as normal text. What you are looking to do is encode the text with HTML entities, this will prevent the browser from processing it as normal HTML.
var enc = $('<div/>').text('<script type="text/javascript"> function test() { a = 5; }<\/script>').html();
$("#example").append(enc);
This works:
function insert() {
var data = '<script type="text/javascript"> function test() { a = 5; }<\/script>';
$('#example').text(data);
}
function get() {
var content = $('#example').text();
alert(content);
}
Are you checking for the code by browsing the live version of the DOM, using a tool like Firebug? If you are expecting to see your code rendered in your regular browser window, you won't, because the script tags are actually parsed when they are inserted, and script tags aren't visible elements in an HTML page.