How can I clicked on that I get a tag index
My Html Code
<html>
<head>
<title>nss plugin</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="nss.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<img src="../img/is1.jpg"/>
<img src="../img/is2.jpg"/>
<img src="../img/is3.jpg"/>
<img src="../img/is4.jpg"/>
</body>
</html>
2 . My jquery plugin code.
(function( $ ) {
$.fn.nss = function( ) {
var thisindx = this.index(this);
console.log(thisindx);
return this;
};
}( jQuery ))
3.my javascript code
$(function(){
$('a[rel="group"]').click(function(){
$('a[rel="group"]').nss();
})
});
Why thisindx value is equal to 0
How can a person get the actual value
Not sure why you need a plugin, you can just do :
$(function(){
$('a[rel="group"]').on('click', function(){
$('a[rel="group"]').index(this);
});
});
to get the current elements index withing the group.
EDIT:
inside a plugin you get the collection, and iterate over it with return this.each, so using each individual iteration and the collection, you can get the elements index in the set of elements in the selector like so:
$.fn.nss = function( ) {
var elems = this
return elems.each(function() {
// all plugin code for multiple elements should normally go in a loop
// like this one to perform the same actions on every element
var thisindx = elems.index(this);
console.log(thisindx);
});
};
Try like this
var thisindx = this.index();
Or from the click event you can directly get the index value like
$(function(){
$('a[rel="group"]').on('click',function(){
$('a[rel="group"]').index();
//Better use like
$(this).index(); //or this.index();
});
});
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
My HTML:
<html>
<head>
<title>Circles!</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="bower_components/jquery/dist/jquery.js"></script>
<script type="text/javascript" src="math.js"></script>
</head>
<body>
<div id="header">
<h1>The area of a circle given the circumfrence</h1>
</div>
<div id="group">
<input type="text" id="input">
<label>Circumfrence</label>
<button type="button" id="button">Calculate</button>
</div>
<div id="answerbox"><span id="answer"></span></div>
</body>
</html>
and my js:
$( document ).ready(function() {
$("#button").click(function() {
var input = $("#input").val;
var answer = (((input * input) * Math.PI) * 0.25);
$(answer).append("#answer")
$("#answerbox").fadeIn(700);
});
});
So the 'answer' value wont display in my 'answer' span, which is inside my 'answerbox' div. What is wrong here?
You must use correct the val and append in code:
Correct:
$( document ).ready(function() {
$("#button").click(function() {
var input = $("#input").val(); // changed added '()'
var answer = (((input * input) * Math.PI) * 0.25);
$("#answer").append(answer); // changed exchaned answer #answer
$("#answerbox").fadeIn(700);
});
});
You wrote the code in reverse order:
$(answer).append("#answer") // wrong
$('#answer').append(answer) // right!
Plus you made a mistake calling .val, it needs the parenthesis since that is a function:
var input = $("#input").val();
Part One, val
val is a function
http://api.jquery.com/val/#val1
Your current code is assigning the function to the variable input.
To call the function and retrieve the content of the input field, you need to call the function using parentheses.
var input = $("#input").val();
Part Two, append
append takes the content to add as a parameter.
http://api.jquery.com/append/
You must first use the CSS selector syntax to choose where to append the content, then pass the content.
$("#answer").append(answer);
So I have a website with a Header.html. In the header are three buttons. I've copied the Header.html into all of my other pages with jquery's load. Now what I would like to do is change the colour of one of the buttons depending on the page it's on. But when I use document.GetElementById in javascript it can't find the div of the button I've copied from the Header.html
Here's the Header.html
<div id="Header_Wrapper">
<div id="Header_PageLinksWrapper">
<div class="Header_PageLink">
<a class="Header_PageLinkText" id="PageLink_Games" href="..\Pages\Games.html">Games</a>
</div>
<div class="Header_PageLink">
<a class="Header_PageLinkText" id="PageLink_AboutMe" href="..\Pages\AboutMe.html">About Me</a>
</div>
<div class="Header_PageLink">
<a class="Header_PageLinkText" id="PageLink_CV" href="..\Pages\CV.html">CV</a>
</div>
</div>
</div>
The javascript file:
$(document).ready(
function ()
{
$("#Header").load("..\\Templates\\Header.html");
var filePath = window.location.pathname;
SetPageLinkColours(filePath);
}
);
function SetPageLinkColours(aPath)
{
var firstIndex = aPath.lastIndexOf("/");
var lastIndex = aPath.indexOf(".html");
var id = "PageLink_" + aPath.slice(firstIndex + 1, lastIndex);
var divElement = document.getElementById(id);
if (divElement == null)
{
console.log("Could not find element " + id);
}
divElement.style.color = 0xffffff;
}
One of the pages (eg. Games.html)
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Adabelle Combrink - Games</title>
<link rel="stylesheet" type="text/css" href="..\Templates\Header.css"/>
<link rel="stylesheet" type="text/css" href="..\Templates\Page.css"/>
<link rel="stylesheet" type="text/css" href="..\Pages\Games.css"/>
<script type="text/javascript" src="..\Scripts\jQuery.js"></script>
<script type="text/javascript" src="..\Scripts\Defaults.js"></script>
</head>
<body>
<header>
<div id="Header"></div>
</header>
</body>
</html>
What this gives me in the console is Could not find element PageLink_Games. I don't get that error if I use something that is in Games.html like Header.
Is there any other way of doing the same thing. I know you can include files into eachother with php but I haven't gotten that right and don't seem to be able to run .php files in Visual Studio.
jQuery.load has a success callback. Use it to assure your code is only executed after the loading is complete.
$(document).ready(
function ()
{
$("#Header").load("..\\Templates\\Header.html", null, function() {
var filePath = window.location.pathname;
SetPageLinkColours(filePath);
});
}
);
Also your SetPageLinkColours function can be improved with jQuery:
function SetPageLinkColours(aPath)
{
var firstIndex = aPath.lastIndexOf("/");
var lastIndex = aPath.indexOf(".html");
var id = "PageLink_" + aPath.slice(firstIndex + 1, lastIndex);
var divElement = $("#"+id);
if (!divElement.length)
{
console.log("Could not find element " + id);
}
else
{
divElement.css('color','white');
}
}
load function makes async request , so your code tries to find element before it rely appears. U need to use load function callback http://api.jquery.com/load/
$(document).ready(
function ()
{
$("#Header").load("..\\Templates\\Header.html", function () {
var filePath = window.location.pathname;
SetPageLinkColours(filePath);
});
}
);
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 using JQuery to populate SELECT elements in order to cut down on the size of the outputted markup.
Everything is working the way I want except for one thing; the sorting.
It looks like by the time I get to the .each in the code below, the JQuery is sorting by the val value instead of the text value. I want the list sorted by the text value or more ideally, in the order that I generate the list in the variable dyn_list_product.
How can I accomplish this?
Many thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Sample Code</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type = "text/javascript" >
$(document).ready(function(){
var dyn_list_product = { 10075:'abc', 10635:'def', 10246:'ghi', 10245:'jkl', 10076:'mno', 10642:'pqr', 10995:'stu', 10255:'vwx', 10230:'yz' };
$('.jquery_list_product').append( $('<option></option>').val('').html('----------') );
$.each( dyn_list_product , function(val, text) { $('.jquery_list_product').append( $('<option></option>').val(val).html(text) ); });
})
</script>
</head>
<body>
<select name="insert-1[]" class="jquery_list_product"></select>
<select name="insert-2[]" class="jquery_list_product"></select>
<select name="insert-3[]" class="jquery_list_product"></select>
</body>
</html>
The jQuery code isn't sorting anything. The order of iteration through the keys of an object is undefined in JavaScript. That is, the fact that you defined the properties in some order means nothing about the order in which the .each() function will pass them to your handler.
Use an array instead:
var dyn_list_product = [ { key: '10075', val: 'abc'}, { key: '10635', val: :'def'}, ... ];
Your .each() loop will then look like:
$.each( dyn_list_product , function(index, obj) {
$('.jquery_list_product').append( $('<option></option>').val(obj.key).html(obj.val) ); });
})