I have a piece of code that is working fine in IE, but it doesn’t run in Firefox. I think the problem is that I have not been able to implement $('document').ready(function). The structure of my json is like [{"options":"smart_exp"},{"options":"user_intf"},{"options":"blahblah"}].
I will be very thankful if someone can see my code & help me in correctly implementing it. Here is my code:
<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2
/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$.getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
$.each(jsonData, function (i, j) {
document.form1.fruits.options[i] = new Option(j.options);
});});
});
</script></head>
<body><form name="form1">
My favourite fruit is :
<select name="fruits" id="fruits" /></form></body>
</html>
Short version (suggested by meeger): don't use single quotes around document.
document is a variable that comes with JavaScript (at least in the browser context). Instead, try the following for the relevant line.
$(document).ready(function() {
You'll also want to take the onLoad attribute off of the body tag, else it will run twice.
Just run $(document).ready(function() {doStuff}). This will automatically run when the document is ready.
It's best practice, at least in my opinion, that you don't put any events in the html itself. This way you separate the structure of an html document from it's behavior. Instead attach events in the $(document).ready function.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("http://localhost/conn_mysql.php", function (jsonData) {
var selectElem = $('#fruits');
for(var i = 0; i < jsonData.length; i++) {
selectElem.append($('<option>').html(jsonData[i].options));
}
});
});
</script>
</head>
<body>
<form name="form1">
My favourite fruit is :
<select name="fruits" id="fruits" />
</form>
</body>
</html>
EDIT:
I tested with the following and mocked the json object since I can't make that call myself.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var jsonData = JSON.parse('[{"options":"smart_exp"},{"options":"user_intf"},{"options":"blahblah"}]');
var selectElem = $('#fruits');
for(var i = 0; i < jsonData.length; i++) {
selectElem.append($('<option>').html(jsonData[i].options));
}
});
</script>
</head>
<body>
<form name="form1">
My favourite fruit is :
<select name="fruits" id="fruits" />
</form>
</body>
</html>
Here it is in all its glory. The shorthand, awesome version:
UPDATED
<script type="text/javascript" language="javascript">
$(function() {
$.getJSON("http://localhost/conn_mysql.php", function (jsonData) {
var cacheFruits = $('#fruits'),
cacheOption = $(document.createElement('option'));
$.each(jsonData, function (i, j) {
cacheFruits.append(
cacheOption.clone().attr('value', j.options).html(j.options)
);
});
});
});
</script>
Of course, I don't know what your JSON structure is, so you may need to play around with the append section of the code.
There should be no reason why the above would not work.
You do not need quotes around document. Once the page has completely loaded, it will start executing whatever you have defined in ready()
$(document).ready(function() {
$(this).getJSON("http://localhost/conn_mysql.php", function (jsonData) {
$(this).each(jsonData, function (i, j) {
document.form1.fruits.options[i] = new Option(j.options);
});
});
});
Try this, your json data should be in this format:
[{'text':'sometext','value':'somevalue'},{'text':'sometext','value':'somevalue'}];
$(document).ready(function() {
$(this).getJSON("http://localhost/conn_mysql.php", function (jsonData) {
var options = [];
$.each(jsonData, function (i, j) {
options.push('<option value="' + j.value + '">' + j.text + '</option>');
});
$('#fruits').html( options.join(''));
});
});
Please note that there may be an encoding/escaping issues here.
Make sure that you escape the text properly from the server side.
htmlentities, htmlspecialchars can help you with that.
This should work in most browsers
Related
I have a code like this:
<html>
<head>
<title>Example formBuilder</title>
</head>
<body>
<div class="build-wrap"></div>
<div class="build-wrap"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://formbuilder.online/assets/js/form-builder.min.js"></script>
<script>
jQuery(function($) {
$(document.getElementsByClassName('build-wrap')).formBuilder();
});
</script>
</body>
</html>
If it was initialized by id, then I could have get data with something like this:
var fbEditor = document.getElementById('build-wrap');
var formBuilder = $(fbEditor).formBuilder();
document.getElementById('getJSON').addEventListener('click', function() {
alert(formBuilder.actions.getData('json'));
});
However, I am using classname to initialize form builder. Is there any way, when click on save, get the respective form-builder data? I am using https://formbuilder.online/
Here is jsfiddle: https://jsfiddle.net/xycvbj3r/3/
#PS: there could be numerous form builder inside php loop.
You can try this:
formBuilder.actions.getData('json');
Or:
formBuilder.actions.getData();
The live demo is here: http://jsfiddle.net/dreambold/q0tfp4yd/10/
I was facing the same issue too. This worked for me
var list = ['#ins1', '#ins2', '#ins3'];
var instances = [];
var init = function(i) {
if (i < list.length) {
var options = JSON.parse(JSON.stringify([]));
$(list[i]).formBuilder(options).promise.then(function(res){
console.log(res, i);
instances.push(res);
i++;
init(i);
});
} else {
return;
}
};
init(0);
And to get data, you can use instances[key].actions.getData()
I am not sure how you are planning to save this data, but to help with your problem of getting form data for a particular form you can use something like this
var formBuilder = $(document.getElementsByClassName('build-wrap')).first().data('formBuilder').actions.getData()
Or to use it over a jQuery Collection then
$(document.getElementsByClassName('build-wrap')).each(function () {
var formBuilder = $(this).data('formBuilder').actions.getData()
})
There is a callback mentioned in the documentation, onsave which runs on editor save. So, when clicking on any form builder's save button, the respected form's data can be received.
Here is the code-
<html>
<head>
<title>Example formBuilder</title>
</head>
<body>
<div class="build-wrap"></div>
<div class="build-wrap"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://formbuilder.online/assets/js/form-builder.min.js"></script>
<script>
jQuery(function($) {
var options = {
onSave: function(evt, formData) {
// This is the respected form's data
console.log('MY DATA_________', formData)
},
};
$(document.getElementsByClassName('build-wrap')).formBuilder(options);
});
</script>
</body>
</html>
Here is the fiddle (couldn't create a working snippet due to not working CDNs.
)- https://jsfiddle.net/nehasoni988/rpo1jnuk/1/#&togetherjs=Mka9TJ4cex
I'm running into a very weird javascript issue that uses SPServices js library to get the current SharePoint list's name from site's url, which works perfectly in IE11 and Chrome(newest), but just stuck in FF(newest, 35.0.1).
Codes are simple. Any inputs would be welcome. Thanks much!!!
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/2014.02/jquery.SPServices-2014.02.min.js"></script>
<script language="JavaScript" type="text/javascript">
var siteURL = window.location.href.replace(/\/Lists.*/i, "");
$(document).ready(function() {
console.log("before listId"); // successfully logged
var listId = $().SPServices.SPListNameFromUrl();
console.log(listId); // **NEVER gets hit!!! and NO any error or warning logged**
});
</script>
Figured out that rather than using jquery.SPServices, there is another nice SharePoint extension "SharePointPlus.js" which works out the issue across all modern browsers e.g. IE11, FF35.0.1 and Chrome
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/sharepointplus/3.0.9/sharepointplus.js"></script>
<script language="JavaScript" type="text/javascript">
$(document).ready(function() {
$SP().lists(function(list) {
for (var i=0; i<list.length; i++)
if (decodeURI(window.location.pathname)===list[i]['Url']) {
var listName = list[i]['Name'];
//......
}
}
}
</script>
Special thanks to Raúl Monge for posting a fully working code for me.
My problem was getting JSON data from a file.json and using this data to autocomplete search on it with JavaScript. The code that finaly got it working for me is the following:
<script>
$(document).ready(function(){
var arrayAutocomplete = new Array();
$.getJSON('json/telefoonnummers.json', function(json) {
$.each(json.personen.persoon,function(index, value){
arrayAutocomplete[index] = new Array();
arrayAutocomplete[index]['label'] = value.naam+" - "+value.telefoonnummer;
});
$( "#search" ).autocomplete({source: arrayAutocomplete});
});
});
This is the html:
<body>
<div id="content">
<input type="text" id="search" />
</div>
And this has to be included in the head:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
Thanks stackoverflow!
NEW EDIT CODE WORKING:
<script>
$(document).ready(function(){
var arrayAutocomplete = new Array();
$.getJSON('data.json', function(json) {
$.each(json.persons.person,function(index, value){
arrayAutocomplete[index] = new Array();
arrayAutocomplete[index]['label'] = value.name;
arrayAutocomplete[index]['value'] = value.phoneno;
});
$( "#search" ).autocomplete({source: arrayAutocomplete});
});
});
</script>
Add this in head
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
This is the html
<body>
<div id="content">
<input type="text" id="search" />
</div>
</body>
why not use
var data = [
"Aragorn",
"Arwen",
....
];
since all of those data are labels?
There you go
A working example with the data structure you have.
Just initialize the autocomplete once the JSON is loaded & the data is formatted.
$( "#search" ).autocomplete({source: availableTags});
Your document ready is within your function.
Try to write your function outside of your document ready.
Then write your document ready to call your function.
Some something like this:
function loadJson() {
//alert("Whoohoo, you called the loadJson function!"); //uncomment for testing
var mycontainer = [];
$.getJSON( "data.json" , function(data) {
//alert(data) //uncomment for testing
$.each( data, function( key, val ) {
//alert("key: "+key+" | val: "+val); //uncomment for testing
array.push([key , val]);
});
});
return mycontainer;
}
$(document).ready(function(){
//alert("Boojah! jQuery library loaded!"); //uncomment for testing
var content = loadJson();
dosomethingwitharray(content);
});
Hope this helps!
Also make sure you have jQuery included in your head ( <head> </head> ):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
And add your javascript at the end of your body ( <body> </body> ).
To test if jquery does it's job try this:
<html>
<head>
<title>getting started with jquery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
</head>
<body>
<h1>my page</h1>
<p>this paragraph contains some text.</p>
<!-- javascript at end -->
<script>
$(document).ready(function(){
//show a dialog, confirming when the document is loaded and jquery is used.
alert("boojah, jquery called the document ready function");
//do something with jquery, for example, modify the dom
$("p").append('<br /> i am able to modify the dom with the help of jquery and added this line, i am awesome.');
});
</script>
</body>
</html>
PS. Uncomment alerts for testing stuff, so you can test what happens. If you have space in your document i suggest using $.append to an div that log's all action's so you can see exactly what's going on because alert's in a loop like the .each are quite annoying! more about append: http://api.jquery.com/append/
I am testing putting a text editor on my page and storing it as part of a JSON object.
HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://tinymce.cachefly.net/4.0/tinymce.min.js" type="text/javascript"> </script>
<script type="text/javascript">
tinymce.init({
selector: "textarea"
});
</script>
<link rel="stylesheet" href="/jquery.mobile-1.3.2.min.css"/>
<script src="/jquery-1.9.1.min.js"></script>
<script src="/jquery.mobile-1.3.2.min.js"></script>
</head>
<body>
<form method="post" action="formSubmit.js">
<textarea name ="editor"></textarea>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
JS
$(document).ready(function () {
var text = $("editor").val();
var name = "project name";
var id = 5;
var item = new item(name, text, id);
var itemArray = localStorage.items;
if (itemArray == undefined) {
itemArray = [];
} else {
itemArray = JSON.parse(itemArray);
}
itemArray.push(item);
localStorage.items = JSON.stringify(itemArray);
});
I want to be able to store item in a JSON object. When I run this I receive a "not-well formed" error at line 1 of the Javascript. It's a very simple program I'm running and can't seem to pinpoint what is causing the error. Is the JSON done incorrectly or are scripts in my HTML header causing issues?
$("editor") is looking for an html tag called 'editor'. you probably want to attach an id attribute to your and do $('#editor')
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');
}
}